| 1 | //! Types for attaching to processes, managing tracees, and interpreting tracing events. |
| 2 | |
| 3 | use std::collections::BTreeMap; |
| 4 | use std::fs; |
| 5 | use std::io; |
| 6 | use std::marker::PhantomData; |
| 7 | use std::os::unix::process::CommandExt; |
| 8 | use std::process::{Child, Command}; |
| 9 | use std::time::Duration; |
| 10 | |
| 11 | use nix::{ |
| 12 | errno::Errno, |
| 13 | sys::{ |
| 14 | ptrace, |
| 15 | wait::{self, WaitPidFlag, WaitStatus}, |
| 16 | }, |
| 17 | }; |
| 18 | use tracing::{debug, info, trace}; |
| 19 | |
| 20 | use crate::error::{Error, Result, ResultExt}; |
| 21 | |
| 22 | #[cfg(target_arch = "aarch64")] |
| 23 | use crate::aarch64; |
| 24 | |
| 25 | #[cfg(target_arch = "x86_64")] |
| 26 | use crate::x86; |
| 27 | |
| 28 | #[cfg(target_arch = "x86_64")] |
| 29 | use x86::DebugRegister; |
| 30 | |
| 31 | #[cfg(target_arch = "aarch64")] |
| 32 | pub type DebugRegisters = aarch64::user_hwdebug_state; |
| 33 | |
| 34 | pub use nix::unistd::Pid; |
| 35 | pub use nix::sys::ptrace::Options; |
| 36 | |
| 37 | /// POSIX signal. |
| 38 | pub use nix::sys::signal::Signal; |
| 39 | |
| 40 | /// Register state of a tracee. |
| 41 | #[cfg(target_arch = "aarch64")] |
| 42 | pub type Registers = aarch64::user_pt_regs; |
| 43 | |
| 44 | /// Register state of a tracee. |
| 45 | #[cfg(target_arch = "x86_64")] |
| 46 | pub type Registers = libc::user_regs_struct; |
| 47 | |
| 48 | /// Extra signal info, such as its cause. |
| 49 | pub type Siginfo = libc::siginfo_t; |
| 50 | |
| 51 | /// Linux constant defined in `include/uapi/linux/elf.h`. |
| 52 | #[cfg(target_arch = "aarch64")] |
| 53 | const NT_PRSTATUS: i32 = 0x1; |
| 54 | |
| 55 | /// A _ptrace-stop_, a tracee state in which it is stopped and ready to accept ptrace |
| 56 | /// commands. |
| 57 | /// |
| 58 | /// These ptrace-stops may carry data obtained via additional (internal) ptrace requests |
| 59 | /// to `PTRACE_GETEVENTMSG`. Requests to `PTRACE_GETSIGINFO` may be made to disambiguate |
| 60 | /// stops. |
| 61 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 62 | pub enum Stop { |
| 63 | Attach, |
| 64 | |
| 65 | // signal-delivery-stop |
| 66 | SignalDelivery { signal: Signal }, |
| 67 | |
| 68 | // group-stop |
| 69 | Group { signal: Signal }, |
| 70 | |
| 71 | // syscall-stops |
| 72 | SyscallEnter, |
| 73 | SyscallExit, |
| 74 | |
| 75 | // ptrace-event-stops |
| 76 | Clone { new: Pid }, |
| 77 | Fork { new: Pid }, |
| 78 | Exec { old: Pid }, |
| 79 | Exiting { exit_code: i32 }, |
| 80 | Signaling { |
| 81 | signal: Signal, |
| 82 | core_dumped: bool, |
| 83 | }, |
| 84 | Vfork { new: Pid }, |
| 85 | VforkDone { new: Pid }, |
| 86 | Seccomp { data: u16 }, |
| 87 | } |
| 88 | |
| 89 | /// Restart requests, which resume stopped tracees. |
| 90 | /// |
| 91 | /// The restart mode determines the possible subsequent stops of the restarted tracee. |
| 92 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 93 | pub enum Restart { |
| 94 | Step, |
| 95 | Continue, |
| 96 | Syscall, |
| 97 | } |
| 98 | |
| 99 | /// Tracee task in ptrace-stop, with an optional pending signal. |
| 100 | /// |
| 101 | /// **Warning:** the underlying tracee is not guaranteed to exist, and |
| 102 | /// operations on it may fail between calls to [`Ptracer::wait()`]. |
| 103 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 104 | pub struct Tracee { |
| 105 | pub pid: Pid, |
| 106 | pub pending: Option<Signal>, |
| 107 | pub stop: Stop, |
| 108 | |
| 109 | #[doc(hidden)] |
| 110 | _not_send: PhantomData<*const ()>, |
| 111 | } |
| 112 | |
| 113 | impl Tracee { |
| 114 | pub fn new(pid: Pid, pending: impl Into<Option<Signal>>, stop: Stop) -> Self { |
| 115 | let pending = pending.into(); |
| 116 | let _not_send = PhantomData; |
| 117 | |
| 118 | Self { pid, pending, stop, _not_send } |
| 119 | } |
| 120 | |
| 121 | /// Set a signal to deliver to the stopped process upon restart. |
| 122 | pub fn inject(&mut self, pending: Signal) { |
| 123 | self.pending = Some(pending); |
| 124 | } |
| 125 | |
| 126 | /// Remove any signal scheduled for delivery to `pid` upon restart. |
| 127 | pub fn suppress(&mut self) { |
| 128 | self.pending = None; |
| 129 | } |
| 130 | |
| 131 | /// Set custom tracing options on the tracee. |
| 132 | pub fn set_options(&mut self, options: Options) -> Result<()> { |
| 133 | Ok(ptrace::setoptions(self.pid, options).died_if_esrch(self.pid)?) |
| 134 | } |
| 135 | |
| 136 | #[cfg(target_arch = "x86_64")] |
| 137 | pub fn registers(&self) -> Result<Registers> { |
| 138 | Ok(ptrace::getregs(self.pid).died_if_esrch(self.pid)?) |
| 139 | } |
| 140 | |
| 141 | #[cfg(target_arch = "aarch64")] |
| 142 | pub fn registers(&self) -> Result<Registers> { |
| 143 | |
| 144 | let mut data = std::mem::MaybeUninit::uninit(); |
| 145 | let mut rv = libc::iovec { |
| 146 | iov_base: &mut data as *mut _ as *mut libc::c_void, |
| 147 | iov_len: std::mem::size_of::<Registers>(), |
| 148 | }; |
| 149 | |
| 150 | let res = unsafe { |
| 151 | libc::ptrace(libc::PTRACE_GETREGSET, self.pid, NT_PRSTATUS, &mut rv as *mut _ as *mut libc::c_void) |
| 152 | }; |
| 153 | |
| 154 | Errno::result(res)?; |
| 155 | |
| 156 | Ok( unsafe { data.assume_init() } ) |
| 157 | } |
| 158 | |
| 159 | #[cfg(target_arch = "x86_64")] |
| 160 | pub fn set_registers(&mut self, regs: Registers) -> Result<()> { |
| 161 | Ok(ptrace::setregs(self.pid, regs).died_if_esrch(self.pid)?) |
| 162 | } |
| 163 | |
| 164 | #[cfg(target_arch = "aarch64")] |
| 165 | pub fn set_registers(&mut self, regs: Registers) -> Result<()> { |
| 166 | let mut rv = libc::iovec { |
| 167 | iov_base: ®s as *const _ as *const libc::c_void as *mut libc::c_void, |
| 168 | iov_len: std::mem::size_of::<Registers>(), |
| 169 | }; |
| 170 | |
| 171 | let res = unsafe { |
| 172 | libc::ptrace(libc::PTRACE_SETREGSET, self.pid, NT_PRSTATUS, &mut rv as *mut _ as *mut libc::c_void) |
| 173 | }; |
| 174 | |
| 175 | Errno::result(res)?; |
| 176 | |
| 177 | Ok(()) |
| 178 | } |
| 179 | |
| 180 | pub fn read_memory(&mut self, addr: u64, len: usize) -> Result<Vec<u8>> { |
| 181 | let mut data = Vec::with_capacity(len); |
| 182 | data.resize(len, 0); |
| 183 | let len_read = self.read_memory_mut(addr, &mut data)?; |
| 184 | data.truncate(len_read); |
| 185 | Ok(data) |
| 186 | } |
| 187 | |
| 188 | pub fn read_memory_mut(&self, addr: u64, data: &mut [u8]) -> Result<usize> { |
| 189 | use std::os::unix::fs::FileExt; |
| 190 | |
| 191 | let mem = self.memory()?; |
| 192 | let len = mem.read_at(data, addr)?; |
| 193 | Ok(len) |
| 194 | } |
| 195 | |
| 196 | pub fn write_memory(&mut self, addr: u64, data: &[u8]) -> Result<usize> { |
| 197 | use std::os::unix::fs::FileExt; |
| 198 | |
| 199 | let mem = fs::OpenOptions::new() |
| 200 | .read(true) |
| 201 | .write(true) |
| 202 | .open(self.proc_mem_path())?; |
| 203 | |
| 204 | let len = mem.write_at(data, addr)?; |
| 205 | |
| 206 | Ok(len) |
| 207 | } |
| 208 | |
| 209 | fn proc_mem_path(&self) -> String { |
| 210 | let tid = self.pid.as_raw() as u32; |
| 211 | format!("/proc/{}/mem", tid) |
| 212 | } |
| 213 | |
| 214 | pub fn memory(&self) -> Result<fs::File> { |
| 215 | Ok(fs::File::open(self.proc_mem_path())?) |
| 216 | } |
| 217 | |
| 218 | pub fn siginfo(&self) -> Result<Option<Siginfo>> { |
| 219 | let info = if let Stop::SignalDelivery { .. } = self.stop { |
| 220 | Some(ptrace::getsiginfo(self.pid).died_if_esrch(self.pid)?) |
| 221 | } else { |
| 222 | None |
| 223 | }; |
| 224 | |
| 225 | Ok(info) |
| 226 | } |
| 227 | |
| 228 | #[cfg(target_arch = "x86_64")] |
| 229 | pub fn debug_register(&self, dr: DebugRegister) -> Result<u64> { |
| 230 | let index = 8 * u64::from(dr); |
| 231 | |
| 232 | if let Some(off) = DebugRegister::user_offset().checked_add(index) { |
| 233 | self.peek_user(off) |
| 234 | } else { |
| 235 | internal_error!("unreachable overflow") |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | #[cfg(target_arch = "aarch64")] |
| 240 | pub fn debug_registers(&self, regtype: aarch64::DebugRegisterType) -> Result<DebugRegisters> { |
| 241 | let mut data = std::mem::MaybeUninit::uninit(); |
| 242 | let mut rv = libc::iovec { |
| 243 | iov_base: &mut data as *mut _ as *mut libc::c_void, |
| 244 | iov_len: std::mem::size_of::<aarch64::user_hwdebug_state>(), |
| 245 | }; |
| 246 | let res = unsafe { |
| 247 | libc::ptrace(libc::PTRACE_GETREGSET, self.pid, regtype, &mut rv as *mut _ as *mut libc::c_void) |
| 248 | }; |
| 249 | |
| 250 | Errno::result(res)?; |
| 251 | |
| 252 | Ok(unsafe { data.assume_init() }) |
| 253 | } |
| 254 | |
| 255 | #[cfg(target_arch = "x86_64")] |
| 256 | pub fn set_debug_register(&self, dr: DebugRegister, data: u64) -> Result<()> { |
| 257 | let index = 8 * u64::from(dr); |
| 258 | |
| 259 | if let Some(off) = DebugRegister::user_offset().checked_add(index) { |
| 260 | self.poke_user(off, data) |
| 261 | } else { |
| 262 | internal_error!("unreachable overflow") |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | #[cfg(target_arch = "aarch64")] |
| 267 | pub fn set_debug_registers(&self, regtype: aarch64::DebugRegisterType, mut state: DebugRegisters) -> Result<()> { |
| 268 | let mut rv = libc::iovec { |
| 269 | iov_base: &mut state as *mut _ as *mut libc::c_void, |
| 270 | iov_len: std::mem::size_of::<aarch64::user_hwdebug_state>(), |
| 271 | }; |
| 272 | let res = unsafe { |
| 273 | libc::ptrace(libc::PTRACE_SETREGSET, self.pid, regtype, &mut rv as *mut _ as *mut libc::c_void) |
| 274 | }; |
| 275 | |
| 276 | Errno::result(res)?; |
| 277 | |
| 278 | Ok(()) |
| 279 | } |
| 280 | |
| 281 | #[cfg(target_arch = "x86_64")] |
| 282 | fn peek_user(&self, off: u64) -> Result<u64> { |
| 283 | // SAFETY: `off` does not require validation, because it is not actually used as a |
| 284 | // pointer offset by the kernel. |
| 285 | // |
| 286 | // See: https://github.com/torvalds/linux/blob/v4.9/arch/x86/kernel/ptrace.c#L774-L791 |
| 287 | |
| 288 | let data = unsafe { |
| 289 | libc::ptrace( |
| 290 | libc::PTRACE_PEEKUSER, |
| 291 | self.pid, |
| 292 | off, |
| 293 | 0, |
| 294 | ) |
| 295 | }; |
| 296 | |
| 297 | Ok(data as u64) |
| 298 | } |
| 299 | |
| 300 | #[cfg(target_arch = "x86_64")] |
| 301 | fn poke_user(&self, off: u64, data: u64) -> Result<()> { |
| 302 | // SAFETY: `off` does not require validation, because it is not actually used as a |
| 303 | // pointer offset by the kernel. |
| 304 | // |
| 305 | // See: https://github.com/torvalds/linux/blob/v4.9/arch/x86/kernel/ptrace.c#L774-L791 |
| 306 | |
| 307 | unsafe { |
| 308 | libc::ptrace( |
| 309 | libc::PTRACE_POKEUSER, |
| 310 | self.pid, |
| 311 | off, |
| 312 | data, |
| 313 | ) |
| 314 | }; |
| 315 | |
| 316 | Ok(()) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 321 | enum State { |
| 322 | // Traced, no special expectation for next stop. |
| 323 | Traced, |
| 324 | |
| 325 | // Newly-attached, expecting a SIGSTOP. |
| 326 | Attaching, |
| 327 | |
| 328 | // Self-attached, via `spawn()` with a pre-exec `TRACEME` request. |
| 329 | Spawned, |
| 330 | |
| 331 | // After a syscall-exit-stop or seccomp-stop. |
| 332 | Syscalling, |
| 333 | |
| 334 | // Stopped mid-exit (but not yet reaped) and pending detach. |
| 335 | Exiting, |
| 336 | } |
| 337 | |
| 338 | /// Tracer for a Linux process. |
| 339 | /// |
| 340 | /// By default, [spawning](Ptracer::spawn()) a child tracee will follow calls to `fork()`, |
| 341 | /// `clone()`, and `exec()`, tracing any child tasks (both threads and processes). |
| 342 | /// |
| 343 | /// This can be configured for any stopped tracee via [`Tracee::set_options()`]. |
| 344 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 345 | pub struct Ptracer { |
| 346 | /// Ptrace options that will be applied to tracees, by default. |
| 347 | options: Options, |
| 348 | |
| 349 | /// Time to sleep for before polling tracees for new events. |
| 350 | poll_delay: Duration, |
| 351 | |
| 352 | /// Known tracees, and their state. |
| 353 | tracees: BTreeMap<i32, State>, |
| 354 | } |
| 355 | |
| 356 | const DEFAULT_POLL_DELAY: Duration = Duration::from_micros(1); |
| 357 | |
| 358 | impl Ptracer { |
| 359 | pub fn new() -> Self { |
| 360 | let options = Options::all(); |
| 361 | let poll_delay = DEFAULT_POLL_DELAY; |
| 362 | let tracees = BTreeMap::new(); |
| 363 | |
| 364 | Self { options, poll_delay, tracees } |
| 365 | } |
| 366 | |
| 367 | /// Return the default ptrace options applied to newly-spawned tracees. |
| 368 | pub fn default_options(&self) -> Options { |
| 369 | self.options |
| 370 | } |
| 371 | |
| 372 | /// Set the default ptrace options applied to newly-spawned tracees. |
| 373 | pub fn set_default_options(&mut self, options: Options) { |
| 374 | self.options = options; |
| 375 | } |
| 376 | |
| 377 | /// Return the initial tracee poll delay. |
| 378 | pub fn poll_delay(&self) -> Duration { |
| 379 | self.poll_delay |
| 380 | } |
| 381 | |
| 382 | /// Set the initial tracee poll delay. |
| 383 | pub fn set_poll_delay(&mut self, poll_delay: Duration) { |
| 384 | self.poll_delay = poll_delay; |
| 385 | } |
| 386 | |
| 387 | /// Resume the stopped tracee, delivering any pending signal. |
| 388 | pub fn restart(&mut self, tracee: Tracee, restart: Restart) -> Result<()> { |
| 389 | let Tracee { pid, pending, .. } = tracee; |
| 390 | |
| 391 | if let Some(State::Exiting) = self.tracee_state(tracee.pid) { |
| 392 | // Override restart request with a detach. |
| 393 | let r = ptrace::detach(tracee.pid, tracee.pending); |
| 394 | r.died_if_esrch(tracee.pid)?; |
| 395 | |
| 396 | // We must not wait on this PID again, or we will reap it and break `std::process::Child`. |
| 397 | self.remove_tracee(tracee.pid); |
| 398 | |
| 399 | return Ok(()); |
| 400 | } |
| 401 | |
| 402 | let r = match restart { |
| 403 | Restart::Step => |
| 404 | ptrace::step(pid, pending), |
| 405 | Restart::Continue => |
| 406 | ptrace::cont(pid, pending), |
| 407 | Restart::Syscall => |
| 408 | ptrace::syscall(pid, pending), |
| 409 | }; |
| 410 | |
| 411 | r.died_if_esrch(pid)?; |
| 412 | |
| 413 | Ok(()) |
| 414 | } |
| 415 | |
| 416 | /// Spawn `cmd` for tracing. |
| 417 | /// |
| 418 | /// The command will be configured to request `PTRACE_TRACEME` after `fork()` and |
| 419 | /// pre-`exec()`. The caller will use this to avoid races and missed events. |
| 420 | pub fn spawn(&mut self, mut cmd: Command) -> Result<Child> { |
| 421 | // On fork, request `PTRACE_TRACEME`. |
| 422 | unsafe { |
| 423 | cmd.pre_exec(|| ptrace::traceme().map_err(|err| io::Error::from_raw_os_error(err as i32))) |
| 424 | }; |
| 425 | |
| 426 | let child = cmd.spawn()?; |
| 427 | |
| 428 | // Register the tracee as having been spawned with a pre-exec `TRACEME` request. |
| 429 | // This lets us interpret the `SIGTRAP` that will be issued for `execve()`, set |
| 430 | // the desired trace options, &c. |
| 431 | let pid = Pid::from_raw(child.id() as i32); |
| 432 | self.set_tracee_state(pid, State::Spawned); |
| 433 | |
| 434 | Ok(child) |
| 435 | } |
| 436 | |
| 437 | /// Attach to a running tracee. This will deliver a `SIGSTOP`. |
| 438 | /// |
| 439 | /// **Warning:** the tracee may not be considered stopped until it has been seen to |
| 440 | /// stop via `wait()`. |
| 441 | pub fn attach(&mut self, pid: Pid) -> Result<()> { |
| 442 | let r = ptrace::attach(pid); |
| 443 | let r = r.map_err(|source| Error::Attach { pid, source }); |
| 444 | |
| 445 | self.mark_tracee(pid); |
| 446 | |
| 447 | r |
| 448 | } |
| 449 | |
| 450 | // Poll tracees for a `wait(2)` status change. |
| 451 | fn poll_tracees(&self) -> Result<Option<WaitStatus>> { |
| 452 | let flag = WaitPidFlag::__WALL | WaitPidFlag::WNOHANG; |
| 453 | |
| 454 | for tracee in self.tracees.keys().copied() { |
| 455 | let pid = Pid::from_raw(tracee); |
| 456 | |
| 457 | match wait::waitpid(pid, Some(flag)) { |
| 458 | Ok(WaitStatus::StillAlive) => { |
| 459 | // Alive, no state change. Check remaining tracees. |
| 460 | continue; |
| 461 | }, |
| 462 | Ok(status) => { |
| 463 | // One of our tracees changed state. |
| 464 | return Ok(Some(status)); |
| 465 | }, |
| 466 | Err(errno) if errno == Errno::ECHILD => { |
| 467 | // No more children to wait on: we're done. |
| 468 | return Ok(None) |
| 469 | }, |
| 470 | Err(err) => { |
| 471 | // Something else went wrong. |
| 472 | return Err(err.into()) |
| 473 | }, |
| 474 | }; |
| 475 | } |
| 476 | |
| 477 | // No tracee changed state. |
| 478 | Ok(None) |
| 479 | } |
| 480 | |
| 481 | /// Wait for some running tracee process to stop. |
| 482 | /// |
| 483 | /// If there are no tracees to wait on, returns `None`. |
| 484 | pub fn wait(&mut self) -> Result<Option<Tracee>> { |
| 485 | use Signal::*; |
| 486 | |
| 487 | let mut poll_delay = self.poll_delay; |
| 488 | |
| 489 | // Wait on known tracees with exponential backoff. |
| 490 | let status = loop { |
| 491 | if self.tracees.is_empty() { |
| 492 | debug!("no tracees to wait on"); |
| 493 | |
| 494 | return Ok(None); |
| 495 | } |
| 496 | |
| 497 | if let Some(status) = self.poll_tracees()? { |
| 498 | // A tracee changed state; examine its `wait(2)` status. |
| 499 | break status; |
| 500 | } else { |
| 501 | trace!(tracees = self.tracees.len(), ?poll_delay, "no tracee updates, backing off"); |
| 502 | |
| 503 | std::thread::sleep(poll_delay); |
| 504 | |
| 505 | // Back off before next attempt. |
| 506 | poll_delay *= 2; |
| 507 | } |
| 508 | }; |
| 509 | |
| 510 | let tracee = match status { |
| 511 | WaitStatus::Exited(_pid, _exit_code) => { |
| 512 | internal_error!("consumed wait status for exited tracee"); |
| 513 | }, |
| 514 | WaitStatus::Signaled(_pid, _sig, _is_core_dump) => { |
| 515 | internal_error!("consumed wait status for signaled tracee"); |
| 516 | }, |
| 517 | WaitStatus::Stopped(pid, SIGTRAP) => { |
| 518 | let state = self.tracee_state_mut(pid); |
| 519 | |
| 520 | if let Some(state @ State::Spawned) = state { |
| 521 | // A `SIGTRAP` for a tracee in the `Spawned` state means it has returned from a |
| 522 | // successful `execve()` after requesting `PTRACE_TRACEME`. From the manual: |
| 523 | // |
| 524 | // If the `PTRACE_O_TRACEEXEC` option is not in effect, all successful calls |
| 525 | // to `execve(2)` by the traced process will cause it to be sent a `SIGTRAP` |
| 526 | // signal, giving the parent a chance to gain control before the new program |
| 527 | // begins execution. |
| 528 | // |
| 529 | // `PTRACE_O_TRACEEXEC` is not set by default, so it is not set when the child |
| 530 | // requests the attach. We will thus see its exec as a `SIGTRAP`, no matter what |
| 531 | // is set in `self.options`. |
| 532 | let stop = Stop::SyscallExit; |
| 533 | let mut tracee = Tracee::new(pid, None, stop); |
| 534 | |
| 535 | // Update the tracee state so subsequent traps are interpreted correctly. |
| 536 | *state = State::Traced; |
| 537 | |
| 538 | // Set global tracing options on this root tracee. Auto-attached tracees from |
| 539 | // fork, clone, and exec will inherit them. |
| 540 | tracee.set_options(self.options)?; |
| 541 | |
| 542 | tracee |
| 543 | } else { |
| 544 | let stop = Stop::SignalDelivery { signal: SIGTRAP }; |
| 545 | Tracee::new(pid, None, stop) |
| 546 | } |
| 547 | }, |
| 548 | WaitStatus::Stopped(pid, signal) => { |
| 549 | if signal == SIGSTOP { |
| 550 | if let Some(state) = self.tracee_state_mut(pid) { |
| 551 | if *state == State::Attaching { |
| 552 | *state = State::Traced; |
| 553 | let stop = Stop::Attach; |
| 554 | let tracee = Tracee::new(pid, None, stop); |
| 555 | return Ok(Some(tracee)); |
| 556 | } |
| 557 | } |
| 558 | else { |
| 559 | // We may see an attach-stop out-of-order, before the ptrace-event-stop |
| 560 | // which would otherwise have us mark it as `Attaching`. Since `Attaching` |
| 561 | // only exists to let us know that the next stop (i.e. this stop) is an |
| 562 | // attach-stop, we can directly initialize this tracee as `Traced`. |
| 563 | self.set_tracee_state(pid, State::Traced); |
| 564 | let stop = Stop::Attach; |
| 565 | let tracee = Tracee::new(pid, None, stop); |
| 566 | return Ok(Some(tracee)); |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | let stop = if is_group_stop(pid, signal)? { |
| 571 | Stop::Group { signal } |
| 572 | } else { |
| 573 | Stop::SignalDelivery { signal } |
| 574 | }; |
| 575 | |
| 576 | Tracee::new(pid, signal, stop) |
| 577 | }, |
| 578 | WaitStatus::PtraceEvent(pid, signal, code) => { |
| 579 | match code { |
| 580 | libc::PTRACE_EVENT_FORK => { |
| 581 | let evt_data = ptrace::getevent(pid).died_if_esrch(pid)?; |
| 582 | let new = Pid::from_raw(evt_data as u32 as i32); |
| 583 | |
| 584 | // When we return, `new` will start as a tracee, but will be delivered a |
| 585 | // `SIGSTOP`. Mark it so we can recognize the `SIGSTOP` as an attach-stop. |
| 586 | self.mark_tracee(new); |
| 587 | |
| 588 | let stop = Stop::Fork { new }; |
| 589 | Tracee::new(pid, signal, stop) |
| 590 | }, |
| 591 | libc::PTRACE_EVENT_CLONE => { |
| 592 | let evt_data = ptrace::getevent(pid).died_if_esrch(pid)?; |
| 593 | let new = Pid::from_raw(evt_data as u32 as i32); |
| 594 | |
| 595 | // When we return, `new` will start as a tracee, but will be delivered a |
| 596 | // `SIGSTOP`. Mark it so we can recognize the `SIGSTOP` as an attach-stop. |
| 597 | self.mark_tracee(new); |
| 598 | |
| 599 | let stop = Stop::Clone { new }; |
| 600 | Tracee::new(pid, signal, stop) |
| 601 | }, |
| 602 | libc::PTRACE_EVENT_EXEC => { |
| 603 | // We are in one of two cases. The exec has either occurred on the main |
| 604 | // thread of the thread group, or not. In either case, the new tid of the |
| 605 | // execing thread will be equal to the tgid. In the off-main case, this is |
| 606 | // a change, and the old state for the tid == tgid will be invalid. |
| 607 | |
| 608 | // The current `pid` is now equal to the tgid of `old`. |
| 609 | let evt_data = ptrace::getevent(pid).died_if_esrch(pid)?; |
| 610 | let old = Pid::from_raw(evt_data as u32 as i32); |
| 611 | |
| 612 | if old != pid { |
| 613 | // We exec'd off-thread, and previous tid state is now invalid. |
| 614 | self.remove_tracee(old); |
| 615 | } |
| 616 | |
| 617 | // We know we are in a syscall. Make sure we can correctly label the next |
| 618 | // syscall-stop as an exit-stop. |
| 619 | // |
| 620 | // Important: if we trace all the syscall-stops, we will report the syscall- |
| 621 | // enter-stop as occurring on `old`, but its matching syscall-exit-stop as |
| 622 | // occurring on `pid`. This is correct, but might look odd. |
| 623 | self.set_tracee_state(pid, State::Syscalling); |
| 624 | |
| 625 | let stop = Stop::Exec { old }; |
| 626 | |
| 627 | Tracee::new(pid, signal, stop) |
| 628 | }, |
| 629 | libc::PTRACE_EVENT_EXIT => { |
| 630 | // In this context, `PTRACE_GETEVENTMSG` returns the pending wait status |
| 631 | // as an `unsigned long`. We are only interested in the low 16-bit word. |
| 632 | let status = ptrace::getevent(pid).died_if_esrch(pid)? as u16; |
| 633 | |
| 634 | // Mark the tracee as exiting so we can detach on next restart. |
| 635 | self.set_tracee_state(pid, State::Exiting); |
| 636 | |
| 637 | let stop = match ExitType::parse(status)? { |
| 638 | ExitType::Exit(exit_code) => |
| 639 | Stop::Exiting { exit_code }, |
| 640 | ExitType::Signaled(signal, core_dumped) => |
| 641 | Stop::Signaling { signal, core_dumped }, |
| 642 | }; |
| 643 | |
| 644 | Tracee::new(pid, signal, stop) |
| 645 | }, |
| 646 | libc::PTRACE_EVENT_VFORK => { |
| 647 | let evt_data = ptrace::getevent(pid).died_if_esrch(pid)?; |
| 648 | let new = Pid::from_raw(evt_data as u32 as i32); |
| 649 | self.mark_tracee(new); |
| 650 | |
| 651 | let stop = Stop::Vfork { new }; |
| 652 | |
| 653 | Tracee::new(pid, signal, stop) |
| 654 | }, |
| 655 | libc::PTRACE_EVENT_VFORK_DONE => { |
| 656 | let evt_data = ptrace::getevent(pid).died_if_esrch(pid)?; |
| 657 | let new = Pid::from_raw(evt_data as u32 as i32); |
| 658 | let stop = Stop::VforkDone {new }; |
| 659 | |
| 660 | Tracee::new(pid, signal, stop) |
| 661 | }, |
| 662 | libc::PTRACE_EVENT_SECCOMP => { |
| 663 | // `SECCOMP_RET_DATA`, which is the low 16 bits of an int. |
| 664 | let data = ptrace::getevent(pid).died_if_esrch(pid)? as u16; |
| 665 | let stop = Stop::Seccomp { data }; |
| 666 | |
| 667 | if let Some(state) = self.tracee_state_mut(pid) { |
| 668 | *state = State::Syscalling; |
| 669 | } else { |
| 670 | internal_error!("seccomp ptrace-event-stop for non-tracee"); |
| 671 | } |
| 672 | |
| 673 | Tracee::new(pid, signal, stop) |
| 674 | }, |
| 675 | libc::PTRACE_EVENT_STOP => { |
| 676 | // Unreachable by us, since we do not expose `PTRACE_SEIZE` &c. |
| 677 | internal_error!("unreachable ptrace-event-stop") |
| 678 | }, |
| 679 | _ => { |
| 680 | // All kernel-delivered `event` values are matched above. |
| 681 | internal_error!("unexpected ptrace-event-stop code") |
| 682 | }, |
| 683 | } |
| 684 | }, |
| 685 | // A signal-delivery-stop never happens between syscall-enter-stop and syscall-exit-stop. |
| 686 | // It will always happen _after_ syscall-exit-stop, and not necessarily immediately. We |
| 687 | // may observe ptrace-event-stops in-between -enter and -exit. |
| 688 | // |
| 689 | // From the manual: |
| 690 | // |
| 691 | // No matter which method caused the syscall-entry-stop, if the tracer restarts |
| 692 | // the tracee with PTRACE_SYSCALL, the tracee enters syscall-exit-stop |
| 693 | // when the system call is finished, or if it is interrupted by a sig‐ |
| 694 | // nal. (That is, signal-delivery-stop never happens between syscall- |
| 695 | // enter-stop and syscall-exit-stop; it happens after syscall-exit- |
| 696 | // stop.). If the tracee is continued using any other method (including |
| 697 | // PTRACE_SYSEMU), no syscall-exit-stop occurs. |
| 698 | // |
| 699 | // [...] |
| 700 | // |
| 701 | // Syscall-enter-stop and syscall-exit-stop are indistinguishable from |
| 702 | // each other by the tracer. The tracer needs to keep track of the |
| 703 | // sequence of ptrace-stops in order to not misinterpret syscall-enter- |
| 704 | // stop as syscall-exit-stop or vice versa. In general, a syscall- |
| 705 | // enter-stop is always followed by syscall-exit-stop, PTRACE_EVENT |
| 706 | // stop, or the tracee's death; no other kinds of ptrace-stop can occur |
| 707 | // in between. However, note that seccomp stops (see below) can cause |
| 708 | // syscall-exit-stops, without preceding syscall-entry-stops. If sec‐ |
| 709 | // comp is in use, care needs to be taken not to misinterpret such stops |
| 710 | // as syscall-entry-stops. |
| 711 | // |
| 712 | WaitStatus::PtraceSyscall(pid) => { |
| 713 | let stop = match self.tracee_state_mut(pid) { |
| 714 | Some(state) => { |
| 715 | match state { |
| 716 | State::Syscalling => { |
| 717 | *state = State::Traced; |
| 718 | Stop::SyscallExit |
| 719 | }, |
| 720 | State::Traced => { |
| 721 | *state = State::Syscalling; |
| 722 | Stop::SyscallEnter |
| 723 | }, |
| 724 | State::Attaching => { |
| 725 | // A tracee in this state is waiting for a `SIGSTOP`, which is an |
| 726 | // artifact of `PTRACE_ATTACH`. The next wait status will thus be |
| 727 | // either a `SIGSTOP`, `SIGKILL`, or a `PTRACE_EVENT_EXIT`. |
| 728 | internal_error!("syscall-stop for `Attaching` tracee") |
| 729 | }, |
| 730 | State::Spawned => { |
| 731 | // We only set the tracee state to `Spawned` after a successful call |
| 732 | // to `Command::spawn()` with a pre-exec `TRACEME` request. |
| 733 | // |
| 734 | // The self-attached tracee will continue until `execve()`. Since it |
| 735 | // can only self-attach with default options, the `execve()` will be |
| 736 | // seen as a `SIGTRAP` signal-delivery-stop, not a syscall-stop or |
| 737 | // ptrace-event-stop, and so we can never reach this case. |
| 738 | internal_error!("syscall-stop for `Spawning` tracee") |
| 739 | }, |
| 740 | State::Exiting => { |
| 741 | // If the tracee was in the `Exiting` state, we should have detached on |
| 742 | // the next restart request. |
| 743 | internal_error!("unexpected event for detached tracee") |
| 744 | }, |
| 745 | } |
| 746 | }, |
| 747 | None => { |
| 748 | // Assumes any pid we are tracing is also indexed in `self.tracees`. |
| 749 | internal_error!("syscall-stop for unregistered tracee") |
| 750 | }, |
| 751 | }; |
| 752 | |
| 753 | Tracee::new(pid, None, stop) |
| 754 | }, |
| 755 | // Assume `!WNOHANG`, `!WCONTINUED`. |
| 756 | WaitStatus::Continued(_) | |
| 757 | WaitStatus::StillAlive => |
| 758 | internal_error!("unreachable `wait()` status"), |
| 759 | }; |
| 760 | |
| 761 | Ok(Some(tracee)) |
| 762 | } |
| 763 | |
| 764 | fn remove_tracee(&mut self, pid: Pid) -> Option<State> { |
| 765 | info!(pid = pid.as_raw(), "removing tracee"); |
| 766 | self.tracees.remove(&pid.as_raw()) |
| 767 | } |
| 768 | |
| 769 | fn tracee_state(&self, pid: Pid) -> Option<State> { |
| 770 | self.tracees.get(&pid.as_raw()).copied() |
| 771 | } |
| 772 | |
| 773 | fn set_tracee_state(&mut self, pid: Pid, state: State) { |
| 774 | debug!(pid = pid.as_raw(), ?state, "setting tracee state"); |
| 775 | |
| 776 | self.tracees.insert(pid.as_raw(), state); |
| 777 | } |
| 778 | |
| 779 | fn tracee_state_mut(&mut self, pid: Pid) -> Option<&mut State> { |
| 780 | self.tracees.get_mut(&pid.as_raw()) |
| 781 | } |
| 782 | |
| 783 | // Mark `pid` as a new tracee pending attach-stop, if it isn't already known. |
| 784 | fn mark_tracee(&mut self, pid: Pid) { |
| 785 | debug!(pid = pid.as_raw(), "marking tracee as attaching if unknown"); |
| 786 | |
| 787 | if !self.tracees.contains_key(&pid.as_raw()) { |
| 788 | info!(pid = pid.as_raw(), "attaching to new tracee"); |
| 789 | } |
| 790 | |
| 791 | self.tracees.entry(pid.as_raw()).or_insert(State::Attaching); |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 796 | enum ExitType { |
| 797 | Exit(i32), |
| 798 | Signaled(Signal, bool), |
| 799 | } |
| 800 | |
| 801 | impl ExitType { |
| 802 | fn parse(status: u16) -> Result<Self> { |
| 803 | // The bit layout of the word `status` is: |
| 804 | // |
| 805 | // 15 8 7 0 |
| 806 | // +-------------------------+---+---------------------+ |
| 807 | // | exit_code | c | sig_no | |
| 808 | // +-------------------------+---+---------------------+ |
| 809 | // |
| 810 | // If `status[6:0]` is nonzero, then `pid` is being signaled with `sig_no`, |
| 811 | // and a set `status[7]` bit flags a core dump. Otherwise, it is a normal |
| 812 | // exit with exit code `status[15:8]`. |
| 813 | let sig_no = status & 0x7f; |
| 814 | let exiting = sig_no == 0; |
| 815 | |
| 816 | let ty = if exiting { |
| 817 | // Extract, zero-extend, cast. |
| 818 | let exit_code = (status >> 8) as u8 as u32 as i32; |
| 819 | |
| 820 | ExitType::Exit(exit_code) |
| 821 | } else { |
| 822 | use std::convert::TryFrom; |
| 823 | |
| 824 | let core_dump = (status & (1 << 7)) >> 7; |
| 825 | let signal = Signal::try_from(sig_no as i32)?; |
| 826 | let core_dump = core_dump > 0; |
| 827 | |
| 828 | ExitType::Signaled(signal, core_dump) |
| 829 | }; |
| 830 | |
| 831 | Ok(ty) |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | // Check if a wait stop with signal delivery is a group-stop. |
| 836 | // |
| 837 | // Assumes attach-stop has already been ruled out. |
| 838 | fn is_group_stop(pid: Pid, sig: Signal) -> Result<bool> { |
| 839 | use Signal::*; |
| 840 | |
| 841 | match sig { |
| 842 | SIGSTOP | SIGTSTP | SIGTTIN | SIGTTOU => { |
| 843 | // Possible group-stop. Check `siginfo` to disambiguate. |
| 844 | // |
| 845 | // From the manual: |
| 846 | // |
| 847 | // If PTRACE_GETSIGINFO fails with EINVAL, then it is definitely a |
| 848 | // group-stop. (Other failure codes are possible, such as ESRCH |
| 849 | // ("no such process") if a SIGKILL killed the tracee.) |
| 850 | // |
| 851 | match ptrace::getsiginfo(pid) { |
| 852 | Err(Errno::EINVAL) => |
| 853 | Ok(true), |
| 854 | Err(err) => |
| 855 | Err(err.into()), |
| 856 | Ok(_) => |
| 857 | Ok(false) |
| 858 | } |
| 859 | }, |
| 860 | _ => { |
| 861 | // Definitely not a group-stop. |
| 862 | // |
| 863 | // From the manual: |
| 864 | // |
| 865 | // The call can be avoided if the signal is not SIGSTOP, SIGTSTP, |
| 866 | // SIGTTIN, or SIGTTOU; only these four signals are stopping signals. |
| 867 | // If the tracer sees something else, it can't be a group-stop. |
| 868 | // |
| 869 | Ok(false) |
| 870 | }, |
| 871 | } |
| 872 | } |