|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <limits.h> |
| 4 | +#include <sys/ptrace.h> |
| 5 | +#include <sys/wait.h> |
| 6 | + |
| 7 | +#define pageLength 4096 |
| 8 | + |
| 9 | +static void dump_memory_region(FILE* pMemFile, unsigned long start_address, long length) { |
| 10 | + static unsigned char page[pageLength]; |
| 11 | + fseeko(pMemFile, start_address, SEEK_SET); |
| 12 | + size_t bytes_read=1; |
| 13 | + for (unsigned long address=start_address; address < start_address + length; address += bytes_read) { |
| 14 | + bytes_read = fread(&page, 1, pageLength, pMemFile); |
| 15 | + fwrite(&page, 1, bytes_read, stdout); |
| 16 | + if (bytes_read == 0) { |
| 17 | + break; |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +static FILE* open_proc(int pid, const char* basename) { |
| 23 | + static char buf[256]; |
| 24 | + sprintf(buf, "/proc/%d/%s", pid, basename); |
| 25 | + return fopen(buf, "r"); |
| 26 | +} |
| 27 | + |
| 28 | +int main(int argc, char **argv) { |
| 29 | + if (argc != 2) { |
| 30 | + fprintf(stderr, "Usage:\n"); |
| 31 | + fprintf(stderr, "%s <pid>\n", argv[0]); |
| 32 | + exit(1); |
| 33 | + } |
| 34 | + const int pid = atoi(argv[1]); |
| 35 | + if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) { |
| 36 | + printf("Unable to attach to the pid specified\n"); |
| 37 | + exit(1); |
| 38 | + } |
| 39 | + wait(NULL); |
| 40 | + |
| 41 | + FILE* pMapsFile = open_proc(pid, "maps"); |
| 42 | + FILE* pMemFile = open_proc(pid, "mem"); |
| 43 | + |
| 44 | + char line[256]; |
| 45 | + while (fgets(line, 256, pMapsFile) != NULL) { |
| 46 | + unsigned long start_address; |
| 47 | + unsigned long end_address; |
| 48 | + sscanf(line, "%lx-%lx %*[^\n]\n", &start_address, &end_address); |
| 49 | + fprintf(stderr, "%lx-%lx\n", start_address, end_address); |
| 50 | + dump_memory_region(pMemFile, start_address, end_address - start_address); |
| 51 | + } |
| 52 | + fclose(pMapsFile); |
| 53 | + fclose(pMemFile); |
| 54 | + |
| 55 | + ptrace(PTRACE_CONT, pid, NULL, NULL); |
| 56 | + ptrace(PTRACE_DETACH, pid, NULL, NULL); |
| 57 | + return 0; |
| 58 | +} |
0 commit comments