commit old stuff
[tools.git] / tools / strscan.c
index 6060969..613319a 100644 (file)
@@ -6,6 +6,8 @@
 #include <assert.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/wait.h>
+#include <sys/ptrace.h>
 #include <fcntl.h>
 #include <jh.h>
 #include <stdbool.h>
@@ -31,11 +33,28 @@ int main(int argc, char **argv) {
   if (argc != 3) xperror("invocation: anondump <pid> <searchstr>", 0);
   TPRINTF(maps_path, "/proc/%s/maps", argv[1])
   char *maps = CHK_PTR(slurp_file(maps_path, NULL, JH_SLURP_NO_STAT), "unable to read /proc/$pid/maps", 1);
+
+/*
+  char argbuf[8192];
+  size_t arglen = strlen(argv[2])*4;
+  for (int i=0; i<strlen(argv[2]); i++) {
+    argbuf[i*4] = argv[2][i];
+    argbuf[i*4+1] = 0;
+    argbuf[i*4+2] = 0;
+    argbuf[i*4+3] = 0;
+  }*/
+
+  if (ptrace(PTRACE_ATTACH, atoi(argv[1]), NULL, NULL)) {
+    fputs("warning: unable to ptrace\n", stderr);
+  } else {
+    wait(NULL);
+  }
+
   TPRINTF(mem_path, "/proc/%s/mem", argv[1])
   int memfd = fail_on_neg(open(mem_path, O_RDONLY), "unable to open /proc/$pid/mem", 1);
 
   size_t n_mappings = count_char_occurences(maps, '\n');
-  mappings = CHK_PTR(calloc(n_mappings, sizeof(struct range)), "memory allocation failed", 1);
+  mappings = CHK_PTR(calloc(n_mappings+1, sizeof(struct range)), "memory allocation failed", 1);
 
   // do magic
   for (char *line = strtok(maps, "\n"); line != NULL; line = strtok(NULL, "\n")) {
@@ -47,7 +66,17 @@ int main(int argc, char **argv) {
   FOR_EACH_MAPPING {
     size_t len = mapping->b - mapping->a;
     char *copy = CHK_PTR(malloc(len), "malloc failed", 1);
-    if (pread(memfd, copy, len, (off_t)mapping->a) != (ssize_t)len) xperror("pread failed", 0);
+    ssize_t read_res;
+    size_t read_done = 0;
+read_more:;
+    if ((read_res=pread(memfd, copy+read_done, len-read_done, (off_t)mapping->a-read_done)) != (ssize_t)len) {
+      if (read_res <= 0) {
+        fputs("warning: some read failed\n", stderr);
+        continue;
+      }
+      read_done += read_res;
+      goto read_more;
+    }
     size_t pos = 0;
     while (1) {
       char *ptr = memmem(copy + pos, len, argv[2], strlen(argv[2]));