Skip to main content

reverie_ptrace/
lib.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! Reverie ptrace backend.
10//!
11//! Part of [Hermit](https://hermetic-infra.org). For the command-line interface,
12//! see [`hermit-run`](https://crates.io/crates/hermit-run), and for background,
13//! see [Hermit: Deterministic Linux for Controlled Testing and Software Bug-finding](https://developers.facebook.com/blog/post/2022/11/22/hermit-deterministic-linux-testing/).
14//!
15//! Default features build on stable Rust. The optional `nightly` feature lets
16//! [`spawn_fn_with_config`] clear libtest's capture of printing macros before
17//! forking; see that function's documentation for stable test alternatives.
18//!
19//! ptraced task implements `Guest` trait.
20//!
21//! `TracedTask` implements handlers for ptrace events including
22//! seccomp. Notable ptrace events include:
23//!
24//! `PTRACE_EVENT_EXEC`: `execvpe` is about to return, tracee stopped
25//!  at entry point.
26//!
27//! `PTRACE_EVENT_FORK/VFORK/CLONE`: when `fork`/`vfork`/`clone` is about
28//! to return
29//!
30//! `PTRACE_EVENT_SECCOMP`: seccomp stop caused by `RET_TRACE`
31//! NB: we patch syscall in seccomp ptrace stop.
32//!
33//! `PTRACE_EVENT_EXIT`: process is about to exit
34//!
35//! signals: tracee's pending signal stop.
36#![deny(missing_docs)]
37#![deny(rustdoc::broken_intra_doc_links)]
38#![cfg(target_os = "linux")]
39#![cfg_attr(feature = "nightly", feature(internal_output_capture))]
40
41// The crate's own unit tests share test modules with its integration tests
42// (`task::sigtrap_repair_page_tests` includes `tests/sigtrap_steps`), which
43// name the crate as `reverie_ptrace`.
44#[cfg(test)]
45extern crate self as reverie_ptrace;
46
47mod backend;
48#[cfg(any(test, target_arch = "aarch64"))]
49mod branch_step;
50mod capture;
51mod children;
52mod cp;
53#[allow(unused)]
54#[cfg(target_arch = "x86_64")]
55mod debug;
56#[cfg(target_arch = "x86_64")]
57pub mod decoder;
58mod descriptor_status;
59mod error;
60mod failure;
61mod gdbstub;
62mod injected_syscall;
63mod link_path;
64mod memory_map;
65#[cfg(all(test, target_arch = "x86_64"))]
66mod offset_step_interruption_tests;
67mod perf;
68mod pidfd_self;
69mod poll_on_wake;
70pub mod regs;
71mod segv_state;
72#[cfg(all(test, target_arch = "x86_64"))]
73mod signal_action_boundary_tests;
74mod signal_sets;
75mod sigtrap_state;
76mod stack;
77mod stats;
78mod task;
79pub mod testing;
80mod timer;
81mod tool_memory;
82mod tracer;
83mod validation;
84mod vdso;
85mod watch;
86
87// Shared with the transient opens in reverie-core and safeptrace.
88pub use backend::PtraceBackend;
89pub use failure::BrokenSignalApproval;
90pub use failure::CapturedPrefix;
91pub use failure::LegacyCleanupDiagnostics;
92pub use failure::LegacyFailureProjection;
93pub use failure::PendingSigtrapAtStep;
94pub use failure::PtraceCallbackDecision;
95pub use failure::PtraceCallbackDiagnostic;
96pub use failure::PtraceCallbackOutcome;
97pub use failure::PtraceCallbackRefusal;
98pub use failure::PtraceCallbackStop;
99pub use failure::PtraceCleanupFailure;
100pub use failure::PtraceRunFailure;
101pub use failure::QueuedSigtrapAtStep;
102pub use failure::ToolRunCompletion;
103pub use failure::UnattributedSigtrap;
104pub use failure::UnprovenPrivateSyscallCompletion;
105pub use failure::UntracedStubSyscall;
106pub use injected_syscall::InjectedSyscallFrame;
107pub use perf::is_perf_supported;
108pub use perf::pmu_validation;
109pub use reverie::InGuestRcbCounter;
110use reverie::process::launch_window;
111pub use reverie::vdso::VdsoSyscallSite;
112#[cfg(target_arch = "x86_64")]
113pub use reverie::vdso::patch_current_vdso;
114#[cfg(target_arch = "x86_64")]
115pub use reverie::vdso::patch_current_vdso_trapping;
116#[cfg(target_arch = "x86_64")]
117pub use reverie::vdso::patch_current_vdso_trapping_owned;
118pub use stats::PtraceBackendStatsSnapshot;
119pub use stats::PtraceBackendStatsSource;
120pub use timer::PmuConfig;
121pub use timer::SKID_OVERSHOOT_MARKER;
122pub use timer::host_pmu_profile;
123pub use timer::set_pmu_config;
124pub use timer::set_skid_margin_override;
125pub use tool_memory::ToolMemory;
126pub use tracer::CleanupAdmissionRefused;
127pub use tracer::CleanupLookupError;
128pub use tracer::CleanupUnconfirmed;
129pub use tracer::GdbConnection;
130pub use tracer::InjectedCleanupUnconfirmed;
131pub use tracer::PendingPtraceCleanup;
132pub use tracer::PtraceCleanupResource;
133pub use tracer::PtraceTerminationHandle;
134pub use tracer::ToolRunOutcome;
135pub use tracer::Tracer;
136pub use tracer::TracerBuilder;
137pub use tracer::quarantine_cleanup_resource;
138pub use tracer::spawn_fn;
139pub use tracer::spawn_fn_with_config;
140pub use validation::PmuValidationError;
141
142/// CPU-seconds a test's `cc` fixture build may consume. Each fixture
143/// is tens of lines of C and builds in well under a CPU-second, so
144/// this is generous headroom against a runaway compiler, not a
145/// scheduling deadline.
146#[cfg(test)]
147const FIXTURE_COMPILE_CPU_SECONDS: u64 = 30;
148
149/// Compiles one `tests/fixtures` C source for a unit test, bounding
150/// the compiler by CPU time rather than wall time.
151///
152/// Fixtures build on the test host at run time (the binary may be
153/// built elsewhere), so the bound must not be a wall clock: under
154/// host load a 1 s wall timeout killed compiles that had used only
155/// milliseconds of CPU, failing tests before they tested anything
156/// (dh-uelw3). `RLIMIT_CPU` is inherited by the `cc` driver's
157/// children, each holding its own budget; wall time is left to the
158/// test harness.
159#[cfg(test)]
160pub(crate) fn compile_c_fixture(
161    source: &std::path::Path,
162    output: &std::path::Path,
163) -> std::process::ExitStatus {
164    compile_c_fixture_bounded(source, output, FIXTURE_COMPILE_CPU_SECONDS)
165}
166
167#[cfg(test)]
168fn compile_c_fixture_bounded(
169    source: &std::path::Path,
170    output: &std::path::Path,
171    cpu_seconds: u64,
172) -> std::process::ExitStatus {
173    use std::os::unix::process::CommandExt;
174
175    let mut command = std::process::Command::new("cc");
176    command
177        .args(["-std=c11", "-O1"])
178        .arg(source)
179        .arg("-o")
180        .arg(output);
181    // SAFETY: the callback only sets this child's own CPU rlimit
182    // between fork and exec and touches no other state.
183    unsafe {
184        command.pre_exec(move || {
185            let limit = libc::rlimit {
186                rlim_cur: cpu_seconds,
187                rlim_max: cpu_seconds,
188            };
189            if libc::setrlimit(libc::RLIMIT_CPU, &limit) != 0 {
190                return Err(std::io::Error::last_os_error());
191            }
192            Ok(())
193        });
194    }
195    command.status().expect("run cc")
196}
197
198#[cfg(test)]
199mod compile_c_fixture_tests {
200    #[test]
201    fn fixture_compile_uses_a_cpu_bound_not_a_wall_bound() {
202        let directory =
203            std::env::temp_dir().join(format!("reverie-compile-fixture-{}", std::process::id()));
204        std::fs::create_dir_all(&directory).unwrap();
205        let source = directory.join("probe.c");
206        std::fs::write(&source, "int main(void) { return 42; }\n").unwrap();
207
208        let output = directory.join("probe");
209        let status = super::compile_c_fixture(&source, &output);
210        assert!(status.success(), "compile probe fixture: {status}");
211        let ran = std::process::Command::new(&output).status().unwrap();
212        assert_eq!(ran.code(), Some(42));
213
214        // A zero CPU budget kills the compiler itself: the bound is
215        // really on the toolchain's CPU, and a nonzero budget many
216        // times the fixture's own CPU cost is what lets it build.
217        let starved = super::compile_c_fixture_bounded(&source, &directory.join("starved"), 0);
218        assert!(!starved.success(), "zero CPU budget built: {starved}");
219
220        std::fs::remove_dir_all(&directory).unwrap();
221    }
222}