PTRACE_PEEKDATA和PTRACE_POKEDATA:允许在目标进程的地址空间中读写内存。
cargo new ptrace-example在Cargo.toml文件中,加入nix依赖项:
[dependencies] nix = {version = "0.27.1", features = ["ptrace", "process"]}nix crate简化了系统调用和进程相关的操作。
use nix::sys::ptrace; use nix::sys::wait::{waitpid, WaitStatus}; use nix::unistd::Pid; use std::process::Command; fn main() { // 替换为你的目标程序-可执行文件的路径 let target_executable = "your_target_executable"; // 堆代码 duidaima.com // 启动目标进程 let child = Command::new(target_executable) .spawn() .expect("Failed to start the target process"); // 获取子进程的PID let child_pid = Pid::from_raw(child.id() as i32); // 附加到子进程 ptrace::attach(child_pid).expect("Failed to attach to the child process"); // 等待子进程停止 match waitpid(child_pid, None) { Ok(WaitStatus::Stopped(_, _)) => { println!("Child process stopped"); // 从子进程读取内存(例如:在地址0x1000读取8字节) let addr: *mut i8 = 0x1000 as *mut i8; let data = ptrace::read(child_pid, addr).expect("Failed to read memory"); println!("Read data from memory: {:?}", data); // 从子进程分离 ptrace::detach(child_pid, None).expect("Failed to detach from the child process"); } _ => { println!("Child process not in a stopped state"); } } }总结