1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#![cfg(unix)]
extern crate nix;
use nix::sys::ptrace::ptrace;
use nix::sys::ptrace::ptrace::PTRACE_TRACEME;
use nix::sys::signal::Signal;
use nix::sys::wait::{waitpid, WaitStatus};
use std::io::{self, Result};
use std::os::unix::process::CommandExt;
use std::process::{Command, Child};
use std::ptr;
pub trait CommandPtraceSpawn {
fn spawn_ptrace(&mut self) -> Result<Child>;
}
impl CommandPtraceSpawn for Command {
fn spawn_ptrace(&mut self) -> Result<Child> {
let child = self.before_exec(|| {
ptrace(PTRACE_TRACEME, 0, ptr::null_mut(), ptr::null_mut())?;
Ok(())
}).spawn()?;
match waitpid(child.id() as i32, None) {
Ok(WaitStatus::Stopped(_, Signal::SIGTRAP)) => Ok(child),
_ => Err(io::Error::new(io::ErrorKind::Other, "Child state not correct"))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use nix::sys::ptrace::ptrace;
use nix::sys::ptrace::ptrace::PTRACE_CONT;
use nix::sys::wait::{waitpid, WaitStatus};
use std::env;
use std::path::PathBuf;
use std::process::Command;
use std::ptr;
fn test_process_path() -> Option<PathBuf> {
env::current_exe()
.ok()
.and_then(|p| p.parent().map(|p| p.with_file_name("test")
.with_extension(env::consts::EXE_EXTENSION)))
}
#[test]
fn test_spawn_ptrace() {
let path = test_process_path().expect("Failed to get test process path");
let child = Command::new(&path)
.spawn_ptrace()
.expect("Error spawning test process");
let pid = child.id() as i32;
ptrace(PTRACE_CONT, pid, ptr::null_mut(), ptr::null_mut())
.expect("Error continuing child process");
match waitpid(pid, None) {
Ok(WaitStatus::Exited(_, code)) => assert_eq!(code, 0),
Ok(s) => panic!("Unexpected stop status: {:?}", s),
Err(e) => panic!("Unexpected waitpid error: {:?}", e),
}
}
}