+#include <string.h>
+#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <unistd.h>
-
-#define ERROR(...) \
- do { \
- fprintf(stderr, __VA_ARGS__); \
- exit(1); \
- } while (0)
-
-#define LOG(...) \
- fprintf(stderr, __VA_ARGS__)
+#include "util.h"
+#include "vm.h"
int main(int argc, char *argv[])
{
LOG("Attached to process %d\n", pid);
/* Do stuff ... */
- sleep(5);
+ parse_vmmap(pid);
ptrace(PTRACE_DETACH, pid, NULL, NULL);
LOG("Detached from process %d\n", pid);
--- /dev/null
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "util.h"
+
+void* xmalloc(size_t size)
+{
+ void *block = malloc(size);
+ if (!block) {
+ perror("malloc");
+ exit(1);
+ }
+ memset(block, 0, size);
+ return block;
+}
--- /dev/null
+#ifndef _UTIL_H_
+#define _UTIL_H_
+#include <stdlib.h>
+
+#define ERROR(...) \
+ do { \
+ fprintf(stderr, __VA_ARGS__); \
+ exit(1); \
+ } while (0)
+
+#define LOG(...) \
+ fprintf(stderr, __VA_ARGS__)
+
+void* xmalloc(size_t size);
+
+#endif // _UTIL_H_
--- /dev/null
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdint.h>
+#include "vm.h"
+#include "util.h"
+
+static void strtrim (char *str)
+{
+ char *begin = str;
+ while (isspace(*begin)) {
+ begin++;
+ }
+ size_t len = strlen(begin);
+ char *end = begin + len;
+ while (end > begin && isspace(*end)) {
+ end++;
+ }
+
+ memmove(str, begin, end - begin + 1);
+}
+
+VMMapping* parse_vmmap (int pid)
+{
+ char fmaps_path[128];
+ sprintf(fmaps_path, "/proc/%d/maps", pid);
+ FILE *fmaps;
+
+ if ((fmaps = fopen(fmaps_path, "r")) == NULL) {
+ perror("fopen");
+ exit(1);
+ }
+
+ uint64_t begin, end;
+ char perms[16];
+ char filename[1024];
+ VMMapping *head = NULL;
+ VMMapping *cur = NULL;
+
+ while(
+ fscanf(fmaps, "%lx-%lx %15s %*x %*x:%*x %*u%1023[^\n]",
+ &begin, &end, perms, filename) != EOF) {
+ strtrim(filename);
+
+ VMMapping *new_mapping = xmalloc(sizeof(VMMapping));
+ *new_mapping = (VMMapping) {
+ .begin = begin,
+ .end = end,
+ .r = perms[0] == 'r',
+ .w = perms[1] == 'w',
+ .x = perms[2] == 'x',
+ .s = perms[3] == 's',
+ .p = perms[3] == 'p',
+ .name = strdup(filename),
+ .next = NULL,
+ };
+
+ if (head) {
+ cur->next = new_mapping;
+ cur = new_mapping;
+ } else {
+ head = cur = new_mapping;
+ }
+
+ LOG("%lx-%lx %c%c%c%c %s\n",
+ cur->begin,
+ cur->end,
+ cur->r ? 'r' : '-',
+ cur->w ? 'w' : '-',
+ cur->x ? 'x' : '-',
+ cur->s ? 's' : 'p',
+ cur->name);
+ }
+
+ return head;
+}