8000 Isolated Processes 9: Repair ProcessReader API by marti4d · Pull Request #188 · rust-minidump/minidump-writer · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[workspace]
resolver = "3"
members = [
"crates/process-reader",
"crates/linux/process-backend",
]

Expand Down Expand Up @@ -54,6 +55,7 @@ byteorder = "1.4"
error-graph = { version = "0.1.1", features = ["serde"] }
failspot = "0.2.0"
process-backend = { path = "crates/linux/process-backend", features = ["testing"] }

# Used for parsing procfs info.
# default-features is disabled since it pulls in chrono
procfs-core = { version = "0.18", default-features = false, features = ["serde1"] }
Expand Down
3 changes: 2 additions & 1 deletion crates/linux/process-backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ edition.workspace = true
rust-version.workspace = true
license.workspace = true

[dependencies]
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
libc.workspace = true
log.workspace = true
process-reader = { path = "../../process-reader", features = ["serde"] }
serde.workspace = true
thiserror.workspace = true

Expand Down
2 changes: 2 additions & 0 deletions crates/linux/process-backend/src/local/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,6 @@ pub enum Error {
ProcessVmReadvFailed(c_int),
#[error("failed to peek at process data: {0}")]
PtracePeekDataFailed(c_int),
#[error("ProcessReader returned an error")]
ProcessReader(#[source] process_reader::ReadError),
}
92 changes: 36 additions & 56 deletions crates/linux/process-backend/src/local/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use {
crate::regs::*,
core::{
cell::RefCell,
ffi::{CStr, c_int, c_long, c_void},
mem, ptr,
},
libc::pid_t,
syscall_invoker::SyscallInvoker,
use crate::regs::*;
use core::{
cell::RefCell,
ffi::{CStr, c_int, c_long, c_void},
mem, ptr,
};
use libc::pid_t;
use syscall_invoker::SyscallInvoker;

pub use {error::Error, module_reader::MappedModuleMemoryReader};
pub use self::{error::Error, module_reader::MappedModuleMemoryReader};

mod error;
mod module_reader;
Expand All @@ -34,6 +32,9 @@ impl Backend {
syscall_invoker: Default::default(),
}
}
pub fn process_reader(&self) -> ProcessReader {
ProcessReader(process_reader::ProcessReader::new(self.pid))
}
pub fn stop_process(&self) -> Result<(), Error> {
self.standard_syscall(|| unsafe { libc::kill(self.pid, libc::SIGSTOP) })
.map_err(Error::SigStopFailed)?;
Expand Down Expand Up @@ -138,50 +139,6 @@ impl Backend {
Ok(bytes_read)
}

pub fn read_process_io_vec(&self, buf: &mut [u8], offset: usize) -> Result<usize, Error> {
let mut local_iov = [libc::iovec {
iov_base: buf.as_mut_ptr().cast(),
iov_len: buf.len(),
}];

let mut remote_iov = [libc::iovec {
iov_base: offset as *mut _,
iov_len: buf.len(),
}];

let bytes_read = self
.standard_syscall(|| unsafe {
libc::process_vm_readv(
self.pid,
local_iov.as_mut_ptr(),
local_iov.len().try_into().unwrap(),
remote_iov.as_mut_ptr(),
remote_iov.len().try_into().unwrap(),
0,
)
})
.map_err(Error::ProcessVmReadvFailed)?;

Ok(usize::try_from(bytes_read).unwrap())
}

pub fn ptrace_peekdata(&self, offset: usize) -> Result<[u8; mem::size_of::<c_long>()], Error> {
self.special_syscall(|| unsafe {
set_errno(0);
let rv = ptrace(
libc::PTRACE_PEEKDATA,
self.pid,
offset as *mut _,
ptr::null_mut(),
);
if rv == -1 && errno() != 0 {
return Err(());
}
Ok(rv.to_ne_bytes())
})
.map_err(Error::PtracePeekDataFailed)
}

pub fn get_gen_regs(&self, tid: libc::pid_t) -> Result<GenRegs, Error> {
self.getregset(tid).or_else(|_| self.getregs(tid))
}
Expand Down Expand Up @@ -218,6 +175,20 @@ impl Backend {
.map_err(Error::PtracePeekUserFailed)
}

pub fn process_reader_for_virtual_mem(&self) -> ProcessReader {
ProcessReader(process_reader::ProcessReader::for_virtual_mem(self.pid))
}

pub fn process_reader_for_file(&self) -> Result<ProcessReader, Error> {
process_reader::ProcessReader::for_file(self.pid)
.map(ProcessReader)
.map_err(Error::ProcessReader)
}

pub fn process_reader_for_ptrace(&self) -> ProcessReader {
ProcessReader(process_reader::ProcessReader::for_ptrace(self.pid))
}

fn open_file(&self, path: &CStr) -> Result<OwnedFd, Error> {
self.standard_syscall(|| unsafe {
libc::open(path.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC, 0)
Expand Down Expand Up @@ -321,15 +292,15 @@ impl Backend {
Ok(())
}

pub fn standard_syscall<T, F>(&self, f: F) -> Result<T, c_int>
fn standard_syscall<T, F>(&self, f: F) -> Result<T, c_int>
where
F: FnOnce() -> T,
T: From<i8> + core::cmp::PartialEq,
{
self.syscall_invoker.borrow_mut().invoke_standard(f)
}

pub fn special_syscall<T, F>(&self, f: F) -> Result<T, c_int>
fn special_syscall<T, F>(&self, f: F) -> Result<T, c_int>
where
F: FnOnce() -> Result<T, ()>,
{
Expand Down Expand Up @@ -420,6 +391,15 @@ impl Drop for DirReader {
}
}

#[derive(Debug)]
pub struct ProcessReader(process_reader::ProcessReader);

impl ProcessReader {
pub fn read_at(&self, address: usize, buf: &mut [u8]) -> Result<usize, Error> {
self.0.read_at(address, buf).map_err(Error::ProcessReader)
}
}

#[derive(Debug)]
struct OwnedFd(c_int);

Expand Down
14 changes: 14 additions & 0 deletions crates/process-reader/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "process-reader"
Comment thread
marti4d marked this conversation as resolved.
Resolved
version = "0.0.0"
edition = "2024"
rust-version = "1.88.0"
license = "MIT"
readme = "README.md"

[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
libc = { version = "0.2.186", default-features = false }
serde = { version = "1.0.228", default-features = false, features=["derive"], optional = true }

[features]
serde = ["dep:serde"]
130 changes: 130 additions & 0 deletions crates/process-reader/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# process-reader

`process-reader` is a small `no_std` Rust crate for reading raw bytes from another Linux or Android process.

It is designed for crash-reporting and minidump-writing code that needs to inspect process memory without depending on `std`. The crate copies bytes into a caller-provided buffer; it does not interpret the memory it reads.

## Platform support

This crate supports Linux and Android only. Other operating systems fail at compile time.

The intended Android targets are contemporary Android systems. Very old Android releases are not part of the supported configuration.

## Reading memory

The main type is `ProcessReader`:

```rust
use process_reader::ProcessReader;

fn read_some_memory(
pid: libc::pid_t,
address: usize,
) -> Result<usize, process_reader::ReadError> {
let reader = ProcessReader::new(pid);

let mut bytes = [0u8; 16];
let bytes_read = reader.read_at(address, &mut bytes)?;

// Only this prefix was read by the call. It may be shorter than the buffer.
let _bytes = &bytes[..bytes_read];

Ok(bytes_read)
}
```

`read_at(address, buf)` attempts to read bytes from `address` in the target process and returns the number of bytes copied. The returned length is in the range `0..=buf.len()`. The address is a virtual address in the target process, not in the calling process.

A successful read may be shorter than `buf.len()`. Short successful reads are returned as `Ok(n)`, not as errors, so callers should only interpret `buf[..n]` as bytes read by the call.

Passing an empty buffer succeeds immediately, returns `Ok(0)`, and does not perform a system call.

## Strategies

`ProcessReader` supports three Linux/Android process-memory mechanisms:

| Constructor | Strategy |
| --- | --- |
| `ProcessReader::new(pid)` | Automatically choose a strategy on the first non-empty read request |
| `ProcessReader::for_virtual_mem(pid)` | Use only `process_vm_readv(2)` |
| `ProcessReader::for_file(pid)` | Use only `/proc/<pid>/mem` |
| `ProcessReader::for_ptrace(pid)` | Use only `ptrace(PTRACE_PEEKDATA)` |

`ProcessReader::new(pid)` tries strategies in this order:

1. `process_vm_readv(2)`
2. `/proc/<pid>/mem`
3. `ptrace(PTRACE_PEEKDATA)`

The first strategy that returns `Ok(_)` for a non-empty read request is cached by that reader. A successful read can be shorter than the requested buffer; a short successful read still selects the strategy. Later reads use the cached strategy directly and do not fall back to another strategy if the cached strategy fails for a different address.

To force a specific mechanism, use one of the `for_*` constructors.

### Strategy-specific read lengths

The public API allows any strategy to return a short successful read. The current implementation has these strategy-specific behaviors:

- `process_vm_readv(2)` returns the byte count reported by `process_vm_readv`, which may be smaller than the requested buffer.
- `/proc/<pid>/mem` attempts to fill the whole buffer. On success it returns `Ok(buf.len())`; if it cannot fill the buffer, it returns an error.
- `ptrace(PTRACE_PEEKDATA)` attempts to fill the whole buffer. On success it returns `Ok(buf.len())`; if it cannot fill the buffer, it returns an error.

## PID invariant

All constructors require a non-negative process ID. Passing `pid < 0` is considered a caller logic error and will panic.

## Ptrace behavior

`ProcessReader::for_ptrace(pid)` only performs `PTRACE_PEEKDATA` reads.

It does not attach to the target, seize it, wait for it to stop, resume it, or detach from it. The caller must arrange any required ptrace relationship and target stopped state before reading.

The requested address does not need to be word-aligned. The implementation performs aligned word reads internally and copies out the requested byte range.

## Errors

All read failures use `ReadError`.

Short successful reads are not errors. They are returned as `Ok(n)` from `read_at`, where `n` is the number of bytes copied.

When a `ReadError` represents one failed strategy, `ReadError::source()` returns that strategy's lower-level error.

For a reader created with `ProcessReader::new(pid)`, the first read can fail because every strategy failed. That is an aggregate failure rather than a single error chain, so `ReadError::source()` returns `None`. Use the strategy-specific accessors to inspect the individual failures:

```rust
fn inspect_error(error: &process_reader::ReadError) {
if let Some(error) = error.virtual_mem_error() {
let _ = error;
}

if let Some(error) = error.file_error() {
let _ = error;
}

if let Some(error) = error.ptrace_error() {
let _ = error;
}
}
```

The destination buffer may be partially overwritten when a read fails. The error does not report how many bytes were copied before the failure, so callers should not rely on the contents of the buffer after an error.

The crate does not provide snapshot consistency. If the target process mutates memory while it is being read, the caller may observe a mixture of old and new bytes.

## `no_std`

The crate is `#![no_std]`. It depends on `libc` with default features disabled.

## Optional features

### `serde`

Enables `Serialize` and `Deserialize` implementations for `ReadError`.

```toml
[dependencies]
process-reader = { version = "0.0.0", features = ["serde"] }
```

## License

MIT
80BB 6 changes: 6 additions & 0 deletions crates/process-reader/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#![no_std]

pub use platform::*;

#[cfg_attr(any(target_os = "linux", target_os = "android"), path = "linux/mod.rs")]
mod platform;
Loading
Loading
0