Skip to main content

miri/shims/native_lib/trace/
child.rs

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