miri/shims/native_lib/trace/child.rs
1use std::cell::RefCell;
2use std::ptr::NonNull;
3use std::rc::Rc;
4
5use ipc_channel::ipc;
6use nix::sys::{mman, ptrace, signal};
7use nix::unistd;
8use rustc_const_eval::interpret::InterpResult;
9
10use super::CALLBACK_STACK_SIZE;
11use super::messages::{Confirmation, StartFfiInfo, TraceRequest};
12use super::parent::{ChildListener, sv_loop};
13use crate::alloc::isolated_alloc::IsolatedAlloc;
14use crate::shims::native_lib::MemEvents;
15
16/// A handle to the single, shared supervisor process across all `MiriMachine`s.
17/// Since it would be very difficult to trace multiple FFI calls in parallel, we
18/// need to ensure that either (a) only one `MiriMachine` is performing an FFI call
19/// at any given time, or (b) there are distinct supervisor and child processes for
20/// each machine. The former was chosen here.
21///
22/// This should only contain a `None` if the supervisor has not (yet) been initialised;
23/// otherwise, if `init_sv` was called and did not error, this will always be nonempty.
24static SUPERVISOR: std::sync::Mutex<Option<Supervisor>> = std::sync::Mutex::new(None);
25
26/// The main means of communication between the child and parent process,
27/// allowing the former to send requests and get info from the latter.
28pub struct Supervisor {
29 /// Sender for FFI-mode-related requests.
30 message_tx: ipc::IpcSender<TraceRequest>,
31 /// Used for synchronisation, allowing us to receive confirmation that the
32 /// parent process has handled the request from `message_tx`.
33 confirm_rx: ipc::IpcReceiver<Confirmation>,
34 /// Receiver for memory acceses that ocurred during the FFI call.
35 event_rx: ipc::IpcReceiver<MemEvents>,
36}
37
38/// Marker representing that an error occurred during creation of the supervisor.
39#[derive(Debug)]
40pub struct SvInitError;
41
42impl Supervisor {
43 /// Returns `true` if the supervisor process exists, and `false` otherwise.
44 pub fn is_enabled() -> bool {
45 SUPERVISOR.lock().unwrap().is_some()
46 }
47
48 unsafe fn protect_pages(
49 pages: impl Iterator<Item = (NonNull<u8>, usize)>,
50 prot: mman::ProtFlags,
51 ) -> Result<(), nix::errno::Errno> {
52 for (pg, sz) in pages {
53 unsafe { mman::mprotect(pg.cast(), sz, prot)? };
54 }
55 Ok(())
56 }
57
58 /// Performs an arbitrary FFI call, enabling tracing from the supervisor.
59 /// As this locks the supervisor via a mutex, no other threads may enter FFI
60 /// until this function returns.
61 pub fn do_ffi<'tcx>(
62 alloc: &Rc<RefCell<IsolatedAlloc>>,
63 f: impl FnOnce() -> InterpResult<'tcx, crate::ImmTy<'tcx>>,
64 ) -> InterpResult<'tcx, (crate::ImmTy<'tcx>, Option<MemEvents>)> {
65 let mut sv_guard = SUPERVISOR.lock().unwrap();
66 // If the supervisor is not initialised for whatever reason, fast-return.
67 // As a side-effect, even on platforms where ptracing
68 // is not implemented, we enforce that only one FFI call
69 // happens at a time.
70 let Some(sv) = sv_guard.as_mut() else { return f().map(|v| (v, None)) };
71
72 // Get pointers to all the pages the supervisor must allow accesses in
73 // and prepare the callback stack.
74 let alloc = alloc.borrow();
75 let page_size = alloc.page_size();
76 let page_ptrs = alloc
77 .pages()
78 .flat_map(|(pg, sz)| {
79 // Convert (page, size) pair into list of pages.
80 let start = pg.expose_provenance().get();
81 (0..sz.strict_div(alloc.page_size()))
82 .map(move |i| start.strict_add(i.strict_mul(page_size)))
83 })
84 .collect();
85 let raw_stack_ptr: *mut [u8; CALLBACK_STACK_SIZE] =
86 Box::leak(Box::new([0u8; CALLBACK_STACK_SIZE])).as_mut_ptr().cast();
87 let stack_ptr = raw_stack_ptr.expose_provenance();
88 let start_info = StartFfiInfo { page_ptrs, stack_ptr };
89
90 // Unwinding might be messed up due to partly protected memory, so let's abort if something
91 // breaks inside here.
92 let res = std::panic::abort_unwind(|| {
93 // Send over the info.
94 // NB: if we do not wait to receive a blank confirmation response, it is
95 // possible that the supervisor is alerted of the SIGSTOP *before* it has
96 // actually received the start_info, thus deadlocking! This way, we can
97 // enforce an ordering for these events.
98 sv.message_tx.send(TraceRequest::StartFfi(start_info)).unwrap();
99 sv.confirm_rx.recv().unwrap();
100 // We need to be stopped for the supervisor to be able to make certain
101 // modifications to our memory - simply waiting on the recv() doesn't
102 // count.
103 signal::raise(signal::SIGSTOP).unwrap();
104
105 // SAFETY: We have coordinated with the supervisor to ensure that this memory will keep
106 // working as normal, just with extra tracing. So even if the compiler moves memory
107 // accesses down to after the `mprotect`, they won't actually segfault.
108 unsafe {
109 Self::protect_pages(alloc.pages(), mman::ProtFlags::PROT_NONE).unwrap();
110 }
111
112 let res = f();
113
114 // SAFETY: We set memory back to normal, so this is safe.
115 unsafe {
116 Self::protect_pages(
117 alloc.pages(),
118 mman::ProtFlags::PROT_READ | mman::ProtFlags::PROT_WRITE,
119 )
120 .unwrap();
121 }
122
123 // Signal the supervisor that we are done. Will block until the supervisor continues us.
124 // This will also shut down the segfault handler, so it's important that all memory is
125 // reset back to normal above. There must not be a window in time where accessing the
126 // pages we protected above actually causes the program to abort.
127 signal::raise(signal::SIGUSR1).unwrap();
128
129 res
130 });
131
132 // SAFETY: Caller upholds that this pointer was allocated as a box with
133 // this type.
134 unsafe {
135 drop(Box::from_raw(raw_stack_ptr));
136 }
137 // On the off-chance something really weird happens, don't block forever.
138 let events = sv
139 .event_rx
140 .try_recv_timeout(std::time::Duration::from_secs(5))
141 .map_err(|e| {
142 match e {
143 ipc::TryRecvError::IpcError(_) => (),
144 ipc::TryRecvError::Empty =>
145 panic!("Waiting for accesses from supervisor timed out!"),
146 }
147 })
148 .ok();
149
150 res.map(|v| (v, events))
151 }
152}
153
154/// Initialises the supervisor process. If this function errors, then the
155/// supervisor process could not be created successfully; else, the caller
156/// is now the child process and can communicate via `do_ffi`, receiving back
157/// events at the end.
158///
159/// # Safety
160/// The invariants for `fork()` must be upheld by the caller, namely either:
161/// - Other threads do not exist, or;
162/// - If they do exist, either those threads or the resulting child process
163/// only ever act in [async-signal-safe](https://www.man7.org/linux/man-pages/man7/signal-safety.7.html) ways.
164pub unsafe fn init_sv() -> Result<(), SvInitError> {
165 // FIXME: Much of this could be reimplemented via the mitosis crate if we upstream the
166 // relevant missing bits.
167
168 // On Linux, this will check whether ptrace is fully disabled by the Yama module.
169 // If Yama isn't running or we're not on Linux, we'll still error later, but
170 // this saves a very expensive fork call.
171 let ptrace_status = std::fs::read_to_string("/proc/sys/kernel/yama/ptrace_scope");
172 if let Ok(stat) = ptrace_status {
173 if let Some(stat) = stat.chars().next() {
174 // Fast-error if ptrace is fully disabled on the system.
175 if stat == '3' {
176 return Err(SvInitError);
177 }
178 }
179 }
180
181 // Initialise the supervisor if it isn't already, placing it into SUPERVISOR.
182 let mut lock = SUPERVISOR.lock().unwrap();
183 if lock.is_some() {
184 return Ok(());
185 }
186
187 // Prepare the IPC channels we need.
188 let (message_tx, message_rx) = ipc::channel().unwrap();
189 let (confirm_tx, confirm_rx) = ipc::channel().unwrap();
190 let (event_tx, event_rx) = ipc::channel().unwrap();
191 // SAFETY: Calling sysconf(_SC_PAGESIZE) is always safe and cannot error.
192 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }.try_into().unwrap();
193 super::parent::PAGE_SIZE.store(page_size, std::sync::atomic::Ordering::Relaxed);
194
195 unsafe {
196 // TODO: Maybe use clone3() instead for better signalling of when the child exits?
197 // SAFETY: Caller upholds that only one thread exists.
198 match unistd::fork().unwrap() {
199 unistd::ForkResult::Parent { child } => {
200 // If somehow another thread does exist, prevent it from accessing the lock
201 // and thus breaking our safety invariants.
202 std::mem::forget(lock);
203 // The child process is free to unwind, so we won't to avoid doubly freeing
204 // system resources.
205 let init = std::panic::catch_unwind(|| {
206 let listener = ChildListener::new(message_rx, confirm_tx.clone());
207 // Trace as many things as possible, to be able to handle them as needed.
208 let options = ptrace::Options::PTRACE_O_TRACESYSGOOD
209 | ptrace::Options::PTRACE_O_TRACECLONE
210 | ptrace::Options::PTRACE_O_TRACEFORK;
211 // Attach to the child process without stopping it.
212 match ptrace::seize(child, options) {
213 // Ptrace works :D
214 Ok(_) => {
215 let code = sv_loop(listener, child, event_tx, confirm_tx).unwrap_err();
216 // If a return code of 0 is not explicitly given, assume something went
217 // wrong and return 1.
218 std::process::exit(code.0.unwrap_or(1))
219 }
220 // Ptrace does not work and we failed to catch that.
221 Err(_) => {
222 // If we can't ptrace, Miri continues being the parent.
223 signal::kill(child, signal::SIGKILL).unwrap();
224 SvInitError
225 }
226 }
227 });
228 match init {
229 // The "Ok" case means that we couldn't ptrace.
230 Ok(e) => return Err(e),
231 Err(p) => {
232 eprintln!(
233 "Supervisor process panicked!\n{p:?}\n\nTry running again without using the native-lib tracer."
234 );
235 std::process::exit(1);
236 }
237 }
238 }
239 unistd::ForkResult::Child => {
240 // Make sure we never get orphaned and stuck in SIGSTOP or similar
241 // SAFETY: prctl PR_SET_PDEATHSIG is always safe to call.
242 let ret = libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
243 assert_eq!(ret, 0);
244 // First make sure the parent succeeded with ptracing us!
245 signal::raise(signal::SIGSTOP).unwrap();
246 // If we're the child process, save the supervisor info.
247 *lock = Some(Supervisor { message_tx, confirm_rx, event_rx });
248 }
249 }
250 }
251 Ok(())
252}
253
254/// Instruct the supervisor process to return a particular code. Useful if for
255/// whatever reason this code fails to be intercepted normally.
256pub fn register_retcode_sv(code: i32) {
257 let mut sv_guard = SUPERVISOR.lock().unwrap();
258 if let Some(sv) = sv_guard.as_mut() {
259 sv.message_tx.send(TraceRequest::OverrideRetcode(code)).unwrap();
260 sv.confirm_rx.recv().unwrap();
261 }
262}