Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add brief explanation of how it works to the README #23

Merged
merged 2 commits into from
Jan 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,72 @@ fn in_child() -> Result<()> {
}

```

# How it works

Here's a summary, with some C pseudocode, of how the `read-process-memory`
crate works under the hood on each of the platforms it supports. The three
inputs are:

* `PID`: the process ID to read from
* `LENGTH`: how much memory to read
* `ADDRESS`: the address to read from

## Linux:

Uses [process_vm_readv](https://man7.org/linux/man-pages/man2/process_vm_readv.2.html)

```c
void* TARGET = (void*) 0x123412341324;
struct iovec local;
local.iov_base = calloc(LENGTH, sizeof(char));
local.iov_len = LENGTH;
struct iovec remote;
remote[0].iov_base = TARGET;
remote[0].iov_len = LENGTH;
process_vm_readv(PID, local, 2, remote, 1, 0);
```

## Mac OS:

Uses [vm_read_overwrite](https://developer.apple.com/documentation/kernel/1585371-vm_read_overwrite)

```c
mach_port_name_t task;
task_for_pid(mach_task_self(), PID, &task)
vm_size_t read_len = LENGTH;
char result[LENGTH];
vm_read_overwrite(task, TARGET, LENGTH, &result, &read_len)
```

## FreeBSD:

Uses [ptrace](https://man.freebsd.org/cgi/man.cgi?query=ptrace). This one stops the process to read from it.

```c
// attach
int wait_status = 0;
attach_status = ptrace(PT_ATTACH, PID, null, 0);
waitpid(PID, &wait_status, 0);
WIFSTOPPED(wait_status)
char result[LENGTH];
desc = PtraceIoDesc {
piod_op: PIOD_READ_D,
piod_offs: TARGET;
piod_addr: &result;
piod_len: LENGTH,
};
// read data
ptrace(PT_IO, PID, &desc, 0);
// detach
ptrace(PT_DETACH, PID, null, 0);
```

## Windows:

Uses [ReadProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory):

```c
char result[LENGTH];
ReadProcessMemory(PID, ADDRESS, &result, LENGTH, null);
```