0

I have written some code in order to read another process memory. This is for macOS/GNU Mach.

#include <stdio.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>

int main() {
    pid_t pid;
    printf("PID: ");
    scanf("%d", &pid);
    vm_address_t address;
    printf("Address: ");
    scanf("%lx", &address);
    vm_offset_t readMem;
    vm_map_read_t task = task_for_pid(mach_task_self(), pid, &task);
    mach_msg_type_number_t size = sizeof(int);
    kern_return_t result = vm_read(task, address, (pointer_t)sizeof(int), &readMem, &size);
    if (result) {
        fprintf(stderr, "cant read, result 0x%x\n", result);
    }
    printf("%lu", readMem); 
}

Upon running it and providing a valid PID, it returns MACH_SEND_INVALID_DEST.

lego man
  • 3
  • 1
  • I think your real issue is that `task_for_pid` does _not_ return a `vm_map_read_t`. It returns `kern_return_t`. So, the `&task` would set it correctly but the return value blows that away. You want: `kern_return_t result = task_for_pid(mach_task_self(), pid, &task);` and check the return value as you do for `vm_read` From a web search, other examples use `task_t task;` or `mach_port_t task;` – Craig Estey Jan 11 '23 at 20:26
  • @CraigEstey That's weird... now the return value is `0x5` lol – lego man Jan 11 '23 at 20:32
  • There's scant documentation for `task_for_pid`. The web search produced only _three_ non-dup results. I presume you're using macOS (vs. "real" mach or XNU). I don't have access to one. So, I'm just searching, reading, and guessing. One page says "who needs it" when referring to `task_for_pid`. That aside, you also have to ensure that the `pid` you enter is owned by the same `uid` as your program is running under (or use `sudo`). And, that `address` maps to something in the target process/thread's address space. – Craig Estey Jan 11 '23 at 20:40
  • sorry, the result is 0x5, the return value is gibberish. the actual value in memory is 12. – lego man Jan 11 '23 at 20:40
  • @CraigEstey Using `sudo` returned no error, but I am still getting gibberish. – lego man Jan 11 '23 at 20:42
  • The closest I found is: [Read/Write memory on OS X 10.8.2 with vm_read and vm_write](https://stackoverflow.com/q/12759378/5382650) but it's 10 years old ... – Craig Estey Jan 11 '23 at 20:46
  • Since [IIRC] Apple closed macOS source a few years back, the only way to examine the source might be to find a repo for the mach kernel or XNU kernel. Spotty, at best ... There ought to be a macOS specific API that supports this functionality, just not the [underlying] mach API. – Craig Estey Jan 11 '23 at 20:49

0 Answers0