Skip to main content

reverie/
tool.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//! The API that a Reverie tool (client) should implement.
10//!
11//! Reverie tools consist of two portions: the global and local (per-guest
12//! thread) instrumentation, though in some backends these will execute in the
13//! same process.
14
15use async_trait::async_trait;
16use reverie_syscalls::Syscall;
17use serde::Serialize;
18use serde::de::DeserializeOwned;
19
20use crate::ExitStatus;
21use crate::Pid;
22use crate::Signal;
23use crate::SignalEvent;
24use crate::Subscription;
25use crate::Tid;
26use crate::error::Errno;
27use crate::error::Error;
28use crate::guest::Guest;
29#[cfg(target_arch = "x86_64")]
30use crate::rdtsc::Rdtsc;
31#[cfg(target_arch = "x86_64")]
32use crate::rdtsc::RdtscResult;
33
34/// Who owns a guest thread: the single axis that governs *both* how the thread
35/// executes *and* who owns its thread-synchronization primitives (`futex`,
36/// `CLONE_CHILD_CLEARTID`).
37///
38/// These two concerns must never disagree. If a thread executes under the Tool
39/// (registered in the Tool's scheduler) while its `futex` is serviced by the
40/// host — or vice versa — a `pthread_join` deadlocks: the joiner's `FUTEX_WAIT`
41/// waits in one domain while the exiting thread's `CLEARTID` wake fires in the
42/// other, so the wake never reaches the waiter. Collapsing both concerns onto
43/// this single enum makes that split-brain state *unrepresentable*: a thread is
44/// either wholly `Tool`-owned or wholly `Host`-owned, never half of each.
45///
46/// A backend that runs child threads (e.g. the KVM backend, where each guest
47/// thread runs on its own vCPU) selects the ownership for a tool's threads from
48/// [`Tool::thread_ownership`] and uses the *same* value to decide (a) whether to
49/// drive the thread through the Tool loop and (b) whether its `futex` routes to
50/// the Tool. Backends that do not run child threads (e.g. ptrace, which already
51/// routes every subscribed `futex` to the Tool) may ignore this value.
52#[derive(
53    Debug,
54    Clone,
55    Copy,
56    PartialEq,
57    Eq,
58    Default,
59    Serialize,
60    serde::Deserialize
61)]
62pub enum ThreadOwnership {
63    /// The Tool owns the thread: it is driven through the Tool loop (so the Tool
64    /// observes every one of its syscalls and schedules it) and its `futex` /
65    /// `CLEARTID` synchronization is serviced by the Tool. This is the safe,
66    /// "follow children" default — it matches the golden ptrace backend, where
67    /// the Tool (Detcore) owns every futex and no thread synchronization touches
68    /// the host. Determinism can only be guaranteed for `Tool`-owned threads.
69    #[default]
70    Tool,
71    /// The host owns the thread: it runs uninstrumented on the backend's direct
72    /// execution personality and its `futex` / `CLEARTID` synchronization uses
73    /// real host futex words.
74    ///
75    /// This is the `unmonitored_` opt-out. It is internally consistent (host
76    /// execution + host futex, so it does not by itself deadlock a join), but it
77    /// is a determinism/coverage hazard, **not** a correctness shortcut:
78    ///
79    /// * The Tool never sees the thread's syscalls, so it cannot sanitize,
80    ///   record, or schedule them — determinism is **not** guaranteed for it or
81    ///   for anything ordered against it.
82    /// * Mixing `Host`-owned threads into a tool that expects to schedule the
83    ///   whole thread group (e.g. Detcore) breaks that tool's model.
84    ///
85    /// It is deliberately not named `unsafe_`: it cannot cause undefined
86    /// behavior, only nondeterminism and missed instrumentation.
87    Host,
88}
89
90impl ThreadOwnership {
91    /// Whether a thread with this ownership executes under the Tool loop (as
92    /// opposed to the backend's direct host execution personality).
93    pub fn executes_on_tool(self) -> bool {
94        matches!(self, ThreadOwnership::Tool)
95    }
96
97    /// Whether a thread with this ownership executes on the backend's direct
98    /// host execution personality (as opposed to the Tool loop). The exact
99    /// inverse of [`Self::executes_on_tool`].
100    pub fn executes_on_host(self) -> bool {
101        matches!(self, ThreadOwnership::Host)
102    }
103
104    /// Whether the thread's `futex` / `CLEARTID` synchronization is serviced by
105    /// the host rather than the Tool. This is the exact inverse of
106    /// [`Self::executes_on_tool`]; the two are derived from the same value so
107    /// execution and synchronization ownership can never disagree.
108    pub fn futex_is_host_owned(self) -> bool {
109        matches!(self, ThreadOwnership::Host)
110    }
111}
112
113/// The global half of a complete Reverie tool.
114///
115/// One global instance of this type will exist at runtime (singleton). This
116/// global state is shared by the tool across the whole process tree being
117/// instrumented.
118#[async_trait]
119pub trait GlobalTool: Send + Sync + Default {
120    /// The message to send to the global tool.
121    type Request: Serialize + DeserializeOwned + Send;
122
123    /// The result of sending the message.
124    type Response: Serialize + DeserializeOwned + Send;
125
126    /// Static, read-only configuration data that is available everywhere the
127    /// tool runs code.
128    type Config: Serialize + DeserializeOwned + Send + Sync + Clone + Default;
129
130    /// Initialize the tool, allocating the global state.
131    async fn init_global_state(_cfg: &Self::Config) -> Self {
132        Default::default()
133    }
134
135    /// Offer the actual launcher-created input before sharing this run's global
136    /// state or starting any guest hook. The default does not need the binding.
137    ///
138    /// The launcher prepares this temporary read-end lease before global-state
139    /// initialization, so installing it introduces no fallible startup work.
140    /// A Tool that uses it consumes the
141    /// binding only for the registered root's initial image, validating the
142    /// installed endpoint before marking its open-file description. It must not
143    /// grant the fact to inherited/unknown FIFOs or later reconnects, and must
144    /// release the lease at that handoff (or startup failure), not at run end.
145    fn install_inherited_input(&mut self, _input: crate::InheritedInputLease) {}
146
147    /// Install one run-scoped backend capability before the first guest hook.
148    /// The default preserves backend-owned selection. A Tool may reject a
149    /// missing capability here. A Tool whose
150    /// [`Tool::requires_signal_control`] holds need not: reverie-kvm refuses
151    /// that run with `EINVAL` when it offered a control and this did not
152    /// return `ToolControlled`, and with `ENOSYS`, before asking, when it has
153    /// no control to offer.
154    ///
155    /// `ToolControlled` is valid only when `control` is `Some`: a backend
156    /// refuses a run whose Tool claims control of a capability it did not
157    /// receive.
158    fn install_backend_signal_control(
159        &self,
160        _control: Option<crate::BackendSignalControl>,
161    ) -> Result<crate::BackendSignalControlMode, Error> {
162        Ok(crate::BackendSignalControlMode::Unchanged)
163    }
164
165    /// Whether this run observes signal dequeues through
166    /// [`Tool::handle_signal_dequeue`], given the mode that
167    /// [`Self::install_backend_signal_control`] returned.
168    ///
169    /// The backend asks only when [`Tool::may_observe_signal_dequeues`]
170    /// admitted observation for the run's configuration, and enables
171    /// observation only when both answers are `true`. It asks after
172    /// installation, once for each process it starts, so the answer must
173    /// depend only on `mode` and on state fixed before installation returned.
174    /// The default observes whenever the configuration admitted it, whatever
175    /// the mode.
176    fn observe_signal_dequeues(&self, _mode: crate::BackendSignalControlMode) -> bool {
177        true
178    }
179
180    /// Whether the backend may skip a user-return boundary at which nothing
181    /// could be delivered, without calling
182    /// [`Self::authorize_backend_signal_boundary`]. Such a boundary is one
183    /// where the task holds no reserved permit and the backend's own state
184    /// shows no pending signal that the task's mask leaves unblocked, no
185    /// recorded dequeue or dequeue failure to report, no signalfd readiness to
186    /// refresh, and no parked ledger. A skipped boundary also has no
187    /// [`Self::on_backend_signal_boundary`] receipt.
188    ///
189    /// Return `true` only if authorization never publishes a signal or
190    /// otherwise changes what that boundary would select, and if the Tool
191    /// does not depend on being asked at every boundary; the answer must not
192    /// change during a run. The default `false` authorizes every boundary.
193    fn skip_empty_signal_boundaries(&self) -> bool {
194        false
195    }
196
197    /// Authorize the current real user-return boundary. The backend calls
198    /// this outside signal locks; host callback arrival is not authorization.
199    /// See [`Self::skip_empty_signal_boundaries`] for the boundaries a Tool
200    /// may let the backend skip.
201    fn authorize_backend_signal_boundary(
202        &self,
203        _task: crate::SignalTaskIdentity,
204    ) -> Result<Option<crate::SignalDeliveryPermit>, Error> {
205        Ok(None)
206    }
207
208    /// Consume a real signal boundary before user entry. This hook must retain
209    /// ownership across cancellation; it is not an ordinary grant or syscall.
210    async fn on_backend_signal_boundary(
211        &self,
212        _receipt: crate::SignalBoundaryReceipt,
213    ) -> Result<(), Error> {
214        Ok(())
215    }
216
217    /// Reports final process cleanup after the leader has joined every guest
218    /// thread and released their descriptor references, including its own.
219    /// Only a backend offering `BackendSignalControl` sends this callback. A
220    /// Tool may retain a fence awaiting it only with that capability installed
221    /// in `ToolControlled` mode; a backend offering that mode must complete the
222    /// callback after successful process retirement. A terminal boundary receipt
223    /// can establish this fence and must remain able to cancel peer RPCs.
224    /// The fence then keeps other processes from observing host-timed EOF.
225    ///
226    /// There need not be a preceding terminal boundary receipt: synchronous
227    /// hardware faults can terminate a process without a delivery permit.
228    /// Consumers must distinguish an exact known process with no outstanding
229    /// controlled boundary from an early callback for a still-pending boundary.
230    /// This notification alone does not order an otherwise unfenced exit.
231    ///
232    /// KVM emits this once from a successfully retired process leader, before
233    /// its consuming hooks or joins of independent child processes. It is not
234    /// a child-wait publication or an ordinary scheduling request. The callback
235    /// must settle its exact process generation synchronously and must not wait
236    /// for guest progress. A backend failure ends the run instead of emitting
237    /// a successful retirement notification.
238    fn on_backend_process_retired(&self, _event: BackendProcessRetirement) -> Result<(), Error> {
239        Ok(())
240    }
241
242    /// Reports that guest process `pid` has physically left the host, for a
243    /// backend whose process exits complete asynchronously
244    /// ([`crate::BackendCapabilities::process_exits_complete_asynchronously`]),
245    /// or that the kernel has published `pid`'s exit to its guest parent, for a
246    /// backend that reports child-exit publication
247    /// ([`crate::BackendCapabilities::reports_child_exit_publication`]: under
248    /// ptrace, right after the tracer consumes the final wait status of an
249    /// ordinary, initialized process leader; see that capability for the
250    /// processes it does not cover). The backend calls it once per process,
251    /// after the kernel has published the exit to the parent, and possibly
252    /// before the tool has granted that process's exit. It must not wait for
253    /// guest progress.
254    fn on_backend_process_exited(&self, _pid: i32) {}
255
256    /// The guest processes whose exit the tool has granted and whose physical
257    /// exit has not been reported through
258    /// [`GlobalTool::on_backend_process_exited`] yet. A backend whose process
259    /// exits complete asynchronously reads it from a watchdog, to notice an
260    /// exit that never completes. It must not wait for guest progress.
261    fn backend_pending_process_exits(&self) -> Vec<i32> {
262        Vec::new()
263    }
264
265    /// Receive a (potentially) inter-process upcall on the global state object.
266    /// This intended to be IPC, inter-process communication, in some backends,
267    /// and a local method call in others, but never truly a communication
268    /// between different machines.
269    ///
270    /// It receives a shared reference to the global state object, which must
271    /// manage its own synchronization.
272    ///
273    /// On a fatal KVM or ordinary-ptrace run failure, an in-flight Tool callback and its inline
274    /// RPC future may be dropped at any await point. RPC implementations must
275    /// leave shared state safe for concurrent consuming cleanup when dropped;
276    /// a normal response is not manufactured to complete the abandoned RPC.
277    /// The terminal transition in `report_backend_failure` must also make
278    /// cleanup possible for requests that were admitted but did not complete.
279    async fn receive_rpc(&self, _from: Tid, _message: Self::Request) -> Self::Response;
280
281    /// Reports a fatal backend failure before cleanup can wait on another Tool
282    /// callback. This is a failed run, not a guest exit, signal, or RPC reply.
283    /// Implementations must finish their terminal transition synchronously,
284    /// including making concurrent consuming cleanup safe, before returning.
285    /// Complete that transition before waking any failure subscriber. Several
286    /// workers may report distinct errors in one run, so this method must be
287    /// idempotent and preserve the first terminal cause. It must not wait for
288    /// Tool callbacks or physical worker joins that depend on that transition.
289    fn report_backend_failure(&self, _event: BackendFailure) {}
290
291    /// Called by a backend that holds guest thread `exit.tid` at its exit stop
292    /// while the thread's whole process is exiting because of a signal whose
293    /// default action dumps core, before the thread is released to finish
294    /// exiting. The kernel has already made the fatal decision and its own
295    /// core dump step is over, so the thread's exit status cannot change.
296    ///
297    /// The thread's memory is normally still mapped and may be read through
298    /// `/proc/<tid>/mem`, but holding the thread does not keep it there. The
299    /// kernel's OOM reaper, any process that calls `process_mrelease` on the
300    /// dying process, or anything that ends the exit stop early can unmap it
301    /// before or during the call, including after the backend's last
302    /// successful register read, and a process outside the thread group that
303    /// shares the address space can keep writing to it. A read can therefore fail, come back short, or
304    /// return pages that were reaped or are being changed. A consumer must
305    /// treat unavailable or partial memory as a normal outcome and keep
306    /// whatever it got rather than fail.
307    ///
308    /// The call is per thread: each thread of the dying process reaches its
309    /// own exit stop, in host order, so one process death can produce several
310    /// calls. At most one of them has `exit.dumping` set: the thread that
311    /// took the signal, when the kernel ran its core dump step. A thread that
312    /// ends with a core-dumping signal number but without a process-wide
313    /// fatal signal, such as one killed by `SECCOMP_RET_KILL_THREAD` while
314    /// its process lives on, is not offered.
315    ///
316    /// Delivery is best effort. A death is not offered when the backend never
317    /// holds the thread at a readable exit stop, for example when the stop has
318    /// already been advanced, the registers or `/proc/<tid>/stat` cannot be
319    /// read, the root dies during backend initialization, or the thread is
320    /// reaped as a zombie.
321    ///
322    /// The call runs synchronously on the backend's tracing thread, which
323    /// drives every guest task, so its host time stalls the whole guest tree.
324    /// It can come after `report_backend_failure`, when `exit.deadline` names
325    /// the instant by which cleanup must finish. The method must be bounded,
326    /// must not panic, must not wait for guest progress, and must not modify
327    /// the guest. The default does nothing. Only the ptrace backend calls it.
328    fn on_fatal_signal_exit(&self, _exit: &FatalSignalExit) {}
329
330    /// Waits until this run cannot continue faithfully. Each call must subscribe
331    /// independently: multiple Tool callbacks and the scheduler may be waiting.
332    /// The default preserves Tools that do not own a scheduler.
333    /// Returning allows the backend to drop in-flight callbacks, including
334    /// `receive_rpc`, and proceed to consuming exit hooks. Shared state must
335    /// already support that cleanup; returning is not an ordinary RPC reply.
336    /// The ptrace backend polls the returned future again only after the waker
337    /// it was last polled with fires, so a pending future must arrange that
338    /// wake rather than rely on being polled again for another reason.
339    async fn wait_for_backend_failure(&self) {
340        std::future::pending::<()>().await
341    }
342
343    /// Reports that a backend observed a child transition and committed its
344    /// waitability for the parent process.
345    ///
346    /// Backends that model child lifecycle outside the host kernel should
347    /// invoke this at that boundary rather than inferring state from signal
348    /// delivery. Backends whose host kernel owns child waitability may retain
349    /// the default no-op.
350    ///
351    /// KVM polls this callback through its first suspension before making the
352    /// status visible to a parent wait. A Tool-controlled signal scheduler must
353    /// commit its publication or suppression decision in that synchronous
354    /// prefix: it must neither reach an `.await` nor otherwise block on parent
355    /// progress. The backend may already be holding a concurrent parent wait
356    /// across the whole prefix, so waiting for that parent would deadlock.
357    /// Work after that admission point may await parent progress; the backend
358    /// retains and finishes the same pinned future after publishing waitability.
359    /// If that synchronous prefix makes a concurrent parent runnable, the
360    /// backend fences its wait until publication completes; the parent cannot
361    /// observe the callback decision while still receiving a no-child-ready
362    /// result.
363    ///
364    /// No callback is emitted when the exact parent generation is already
365    /// terminal. Such a child is run-teardown state rather than a new waitable
366    /// transition, and the backend auto-reaps its status. A terminal transitive
367    /// ancestor does not suppress a child event while the direct parent remains
368    /// logically live; that parent retains its exact wait semantics.
369    /// For a live parent, callback admission only controls when waitability is
370    /// exposed. It does not reap the backend status: a Tool-controlled wait must
371    /// still be injected into the Guest before Tool shadow state is consumed.
372    async fn on_backend_child_wait_event(
373        &self,
374        _event: BackendChildWaitEvent,
375    ) -> Result<(), Error> {
376        Ok(())
377    }
378}
379
380/// Final descriptor cleanup and worker joins for one exact process lifetime.
381#[derive(Clone, Copy, Debug, Eq, PartialEq)]
382pub struct BackendProcessRetirement {
383    /// Process identity retained after its last live task has retired.
384    pub process: crate::SignalProcessId,
385    /// Authoritative process status after all guest threads have exited.
386    pub status: ExitStatus,
387}
388
389/// The location of a fatal backend failure. The backend retains its typed cause;
390/// this notification only ends dependent waits and must not invent guest status.
391/// Host-side ordinary-ptrace capture failures use the run root's PID/TID with
392/// a `ptrace stdout capture` or `ptrace stderr capture` phase. Those locations
393/// identify the host run owner, not an inferred guest writer or guest failure.
394#[derive(Clone, Copy, Debug, Eq, PartialEq)]
395pub struct BackendFailure {
396    /// Guest process owning the failed operation.
397    pub pid: Pid,
398    /// Guest thread owning the failed operation.
399    pub tid: Tid,
400    /// Backend operation that failed.
401    pub phase: &'static str,
402}
403
404/// A guest thread held at its exit stop while a core-dumping fatal signal
405/// ends its process. See [`GlobalTool::on_fatal_signal_exit`].
406#[derive(Clone, Copy, Debug)]
407#[non_exhaustive]
408pub struct FatalSignalExit {
409    /// Host thread ID of the dying thread.
410    pub tid: Tid,
411    /// The signal that is ending the thread's process. It is the same for
412    /// every thread of the process and always equals the signal in `status`.
413    pub signal: Signal,
414    /// This thread's exit status at its exit stop. Its core-dumped flag is
415    /// per thread: the kernel sets it only on the thread that dumped core,
416    /// and only when a core was written, so it can differ between threads
417    /// and from the status the process finally reports to its waiter.
418    pub status: ExitStatus,
419    /// Whether this thread took the signal and ran the kernel's core dump
420    /// step, whether or not that step wrote a core. At most one thread of a
421    /// dying process has it, and none when the kernel skipped the step, for
422    /// example for a process that is not dumpable.
423    pub dumping: bool,
424    /// The instant by which the backend must finish cleaning up a run that
425    /// has already failed, or `None` while the run has not failed.
426    pub deadline: Option<std::time::Instant>,
427    /// The thread's general-purpose registers at its exit stop.
428    pub regs: libc::user_regs_struct,
429}
430
431impl FatalSignalExit {
432    /// Describes a thread held at its exit stop, for backends that offer it.
433    pub fn new(
434        tid: Tid,
435        status: ExitStatus,
436        dumping: bool,
437        deadline: Option<std::time::Instant>,
438        regs: libc::user_regs_struct,
439    ) -> Option<Self> {
440        let ExitStatus::Signaled(signal, _) = status else {
441            return None;
442        };
443        Some(Self {
444            tid,
445            signal,
446            status,
447            dumping,
448            deadline,
449            regs,
450        })
451    }
452}
453
454/// Whether the default action of `signal` dumps core (signal(7)).
455pub fn signal_dumps_core(signal: Signal) -> bool {
456    matches!(
457        signal,
458        Signal::SIGABRT
459            | Signal::SIGBUS
460            | Signal::SIGFPE
461            | Signal::SIGILL
462            | Signal::SIGQUIT
463            | Signal::SIGSEGV
464            | Signal::SIGSYS
465            | Signal::SIGTRAP
466            | Signal::SIGXCPU
467            | Signal::SIGXFSZ
468    )
469}
470
471/// A child state and waitability decision observed by an execution backend.
472#[derive(Clone, Copy, Debug, Eq, PartialEq)]
473pub enum BackendChildWaitState {
474    /// The child terminated with this exit status.
475    Exited {
476        /// The terminal status reported by the backend.
477        status: ExitStatus,
478        /// Whether the parent may consume this status with a wait syscall.
479        /// Explicit `SIGCHLD` ignore and `SA_NOCLDWAIT` make this false.
480        waitable: bool,
481        /// Virtual child uid reported through `siginfo_t`.
482        uid: u32,
483        /// Child user CPU time in signed Linux clock ticks.
484        user_ticks: i64,
485        /// Child system CPU time in signed Linux clock ticks.
486        system_ticks: i64,
487    },
488    /// The child entered a job-control stop for this signal number.
489    Stopped(i32),
490    /// A previously stopped child resumed.
491    Continued,
492}
493
494/// A backend-observed child waitability decision.
495#[derive(Clone, Copy, Debug, Eq, PartialEq)]
496pub struct BackendChildWaitEvent {
497    /// Exact process lifetime whose wait syscalls may observe the transition.
498    pub parent: crate::SignalProcessId,
499    /// Exact child process lifetime that changed state.
500    pub child: crate::SignalProcessId,
501    /// The observed child state and whether it remains waitable.
502    pub state: BackendChildWaitState,
503}
504
505impl BackendChildWaitEvent {
506    /// Returns the complete terminal publication payload when the receiving
507    /// parent remains inside the traced process tree.
508    pub fn child_exit_completion(self) -> Option<crate::ChildExitCompletion> {
509        let BackendChildWaitState::Exited {
510            status,
511            waitable,
512            uid,
513            user_ticks,
514            system_ticks,
515        } = self.state
516        else {
517            return None;
518        };
519        Some(crate::ChildExitCompletion {
520            parent: self.parent,
521            child: self.child,
522            status,
523            waitable,
524            uid,
525            user_ticks,
526            system_ticks,
527        })
528    }
529}
530
531#[async_trait]
532impl GlobalTool for () {
533    type Request = ();
534    type Response = ();
535    type Config = ();
536
537    async fn receive_rpc(&self, _from: Tid, _message: ()) {}
538}
539
540/// A trait that every Reverie *tool* must implement. The primary function of the
541/// tool specifies how syscalls and signals are handled.
542///
543/// The type that a `Tool` is implemented for represents the process-level state.
544/// That is, one runtime instance of this type will be created for each guest
545/// process. This type is in turn a factory for *thread level states*, which are
546/// allocated dynamically upon guest thread creation. Instances of the thread
547/// state are also managed by Reverie.
548///
549/// During fatal KVM run cleanup, asynchronous event callbacks may be dropped
550/// at any await point. Their thread state is then passed to `on_exit_thread`
551/// even if the start callback was never entered or did not finish. Exit hooks
552/// must consume partially initialized state without requiring guest execution
553/// or a normal response from an abandoned callback. This contract covers
554/// returned runtime errors; arbitrary panic unwinding is not guaranteed to
555/// invoke consuming hooks.
556///
557/// The ordinary ptrace backend owns execution-control state and wait statuses.
558/// Tools must use Guest/backend APIs for resumes, stepping, detach/attach,
559/// tracing options, wait/reap, and mutations of registers or signal information
560/// (including PTRACE_SETSIGINFO). Raw operations outside those APIs invalidate
561/// its current-stop ownership contract. Read-only ptrace/memory observations
562/// are permitted; supported Guest injection can replace the current stop.
563///
564/// For ordinary non-syscall Errno-only callbacks, the return type erases causal
565/// provenance. If a same-generation observation justifies yielding to the
566/// original lifecycle owner, the callback's errno is retained as a diagnostic
567/// while that owner supplies actual exit or exec status. A live callback error
568/// remains fatal; an actually received Error::Tool or Error::Io is always fatal.
569/// This is cancellation/death precedence, not attribution of an errno to a
570/// memory access. The ptrace completion API exposes these records; successful
571/// legacy waits project them away. No host timeout is used to choose death.
572///
573/// # Example
574///
575/// Here is an example of a tool that simply counts the number of syscalls
576/// intercepted for each thread:
577/// ```
578/// use reverie::syscalls::*;
579/// use reverie::*;
580///
581/// /// Our process-level state.
582/// #[derive(Debug, Default, Clone)]
583/// struct MyTool;
584///
585/// #[reverie::tool]
586/// impl Tool for MyTool {
587///     /// The global state type.
588///     type GlobalState = ();
589///     /// Count of syscalls.
590///     type ThreadState = u64;
591///
592///     async fn handle_syscall_event<T: Guest<Self>>(
593///         &self,
594///         guest: &mut T,
595///         syscall: Syscall,
596///     ) -> Result<i64, Error> {
597///         *guest.thread_state_mut() += 1;
598///
599///         // Inject the syscall. If we don't do this, the syscall will be
600///         // supressed.
601///         let ret = guest.inject(syscall).await?;
602///
603///         Ok(ret)
604///     }
605/// }
606/// ```
607#[async_trait]
608pub trait Tool: Send + Sync + Default {
609    /// The type of the global half that goes along with this Local tool. By
610    /// including this type, the Tool is actually a complete specification for an
611    /// instrumentation tool.
612    type GlobalState: GlobalTool;
613
614    /// Tool-state specific to each guest thread. If unset, this defaults to the
615    /// unit type `()`, indicating that the tool does not have thread-level
616    /// state.
617    ///
618    /// Both thread-local and process-local state may have to be migrated between
619    /// address spaces by a Reverie backend. Hence the `ThreadState` type must
620    /// implement [`Serialize`] and [`DeserializeOwned`].
621    ///
622    /// The thread-local storage must be in a good, consistent state when each
623    /// handler returns, and also when handlers yield.
624    ///
625    /// [`Serialize`]: serde::Serialize
626    /// [`DeserializeOwned`]: serde::de::DeserializeOwned
627    type ThreadState: Serialize + DeserializeOwned + Default + Send + Sync;
628
629    /// A common constructor that initializes state when a process is created,
630    /// including the guest's initial, root process. Of course, every process
631    /// includes at least one thread, but the process level state is allocated
632    /// before thread level-state for the process's main thread is allocated.
633    ///
634    /// For now this method assumes access to the global state, but that may
635    /// change.
636    fn new(_pid: Pid, _cfg: &<Self::GlobalState as GlobalTool>::Config) -> Self {
637        Default::default()
638    }
639
640    /// Events the tool subscribes to. This is only called *once* for the entire
641    /// tree. By default, all syscalls are traced (but CPUID/RDTSC instructions
642    /// are not).
643    fn subscriptions(_cfg: &<Self::GlobalState as GlobalTool>::Config) -> Subscription {
644        Subscription::all_syscalls()
645    }
646
647    /// How this tool's guest threads (children created via `CLONE_THREAD`) are
648    /// owned. See [`ThreadOwnership`]. Called once per tree, like
649    /// [`Tool::subscriptions`].
650    ///
651    /// The default is [`ThreadOwnership::Tool`] — the tool follows its children:
652    /// every guest thread is driven through the Tool loop and its `futex`
653    /// synchronization is serviced by the Tool. This is what a determinizing
654    /// tool such as Detcore needs (it owns every futex and schedules every
655    /// thread, matching the golden ptrace backend), and it is the safe default
656    /// for any tool. Override it to return [`ThreadOwnership::Host`] only to opt
657    /// a tool's child threads *out* of instrumentation, accepting the
658    /// determinism/coverage hazard documented on that variant.
659    ///
660    /// Only backends that themselves run child threads (e.g. KVM) consult this;
661    /// backends like ptrace that already route every subscribed `futex` to the
662    /// Tool ignore it.
663    fn thread_ownership(_cfg: &<Self::GlobalState as GlobalTool>::Config) -> ThreadOwnership {
664        ThreadOwnership::Tool
665    }
666
667    /// A guest process creates additional threads, which need their tool state
668    /// initialized. This method returns a newly-allocated thread state. This
669    /// method necessarily runs before the first instruction of a newly created
670    /// guest thread.
671    ///
672    /// If the parent thread is running a handler which injects a fork, this
673    /// callback executes on behalf of the child and may observe the parent's
674    /// thread-local state just this one time. It is important to know WHEN that
675    /// view into the parent's thread-state occurs. We currently guarantee that
676    /// this is *immediately* upon the `.inject()` call that creates the child
677    /// thread. Any later point of execution for `init_thread_state` could delay
678    /// the creation of the child arbitrarily long, waiting for the parent to
679    /// relinquish its hold on its own thread-local state.
680    ///
681    /// The parent Tid always refers to the thread-ID that called
682    /// fork/clone/vfork in order to create the new guest thread. Access to the
683    /// parent's state allows the child state to be defined in terms of modifying
684    /// the parent's, such as tracking the depth in a tree of threads.
685    ///
686    /// # Arguments
687    ///
688    /// * `&self`: a handle on the process-level state.
689    /// * `child`: the new child thread's ID.
690    /// * `parent`: A tuple of the parent thread ID and a snapshot of the
691    ///    parent's thread-local state. This is `None` if the current thread is the
692    ///    root of the guest process tree.
693    fn init_thread_state(
694        &self,
695        _child: Tid,
696        _parent: Option<(Tid, &Self::ThreadState)>,
697    ) -> Self::ThreadState {
698        Default::default()
699    }
700
701    /// Similar to `handle_syscall_event`, except this traps the first
702    /// instruction executed by a new thread. Typical uses of this method include
703    /// delaying thread execution or running initialization actions (injections
704    /// or rpcs).
705    ///
706    /// `init_thread_state` runs once for every constructed thread state. This
707    /// callback runs once when that thread is allowed to start; cancellation
708    /// before admission can consume the state without entering this callback.
709    /// Fatal run failure may also drop it before completion. This callback is
710    /// guaranteed to run independently from the parent. It does not view the
711    /// parents state, and this handler runs in its own asynchronous task.
712    /// Blocking this task on an `.await` will not interfere with the progress of
713    /// the parent thread.
714    ///
715    /// # Arguments
716    ///
717    ///  * `&self`: The process-level state for this thread.
718    ///  * `guest`: A handle to the guest thread.
719    async fn handle_thread_start<T: Guest<Self>>(&self, _guest: &mut T) -> Result<(), Error> {
720        Ok(())
721    }
722
723    /// Observe this backend's actual thread state after a successful
724    /// `handle_thread_start` or `handle_post_exec`, before ordinary guest
725    /// execution resumes. The ptrace backend supplies this synchronous hook;
726    /// other backends must implement an equivalent owned lifecycle boundary
727    /// before relying on it. The default performs no work.
728    ///
729    /// This associates Tool objects, not kernel FD identity or an injected
730    /// operation. It supplies no capability, preparation, selection, result,
731    /// or scheduler turn. Request serialization remains unchanged. A Tool must
732    /// still validate current owner/MM/table authority when using an association.
733    /// Never await or wait for guest progress here. A failure is a backend/run
734    /// failure: the backend reports it and must stop before guest resume.
735    fn on_thread_state_ready(
736        &self,
737        _tid: Tid,
738        _global_state: &Self::GlobalState,
739        _thread_state: &Self::ThreadState,
740    ) -> Result<(), Error> {
741        Ok(())
742    }
743
744    /// Called upon a *successful* execve. In `handle_syscall_event`, after
745    /// injecting `execve`, it is not possible to run code after a successful
746    /// `execve` because it never returns.
747    ///
748    /// NOTE: Thread and process state are unchanged across this execve boundary.
749    /// Thus, this can be useful for doing something like counting the number of
750    /// times a process successfully calls `execve`.
751    async fn handle_post_exec<T: Guest<Self>>(&self, _guest: &mut T) -> Result<(), Errno> {
752        Ok(())
753    }
754
755    /// The tool receives an event from the guest, via the Reverie program
756    /// instrumentation. A Reverie syscall handler fires in the moment *before* a
757    /// guest syscall executes (like a "prehook").
758    ///
759    /// After the event is trapped, control transfers to `handle_syscall_event`
760    /// which is put in temporary control of the guest thread. Via `guest`, we
761    /// can directly access the thread/process local state, and we can also
762    /// remotely access (1) the global state and (2) the memory/registers of the
763    /// guest thread it controls.
764    ///
765    /// NOTE: Only syscalls we have subscribed to [`Tool::subscriptions`] will
766    /// have this handler invoked.
767    async fn handle_syscall_event<T: Guest<Self>>(
768        &self,
769        guest: &mut T,
770        c: Syscall,
771    ) -> Result<i64, Error> {
772        guest.tail_inject(c).await
773    }
774
775    /// CPUID is trapped, the tool should implement this function to return
776    /// `[eax, ebx, ecx, edx]`.
777    ///
778    /// NOTE:
779    ///  * This is never called by default unless cpuid events are subscribed
780    ///    to.
781    ///  * This is only available on x86_64.
782    #[cfg(target_arch = "x86_64")]
783    async fn handle_cpuid_event<T: Guest<Self>>(
784        &self,
785        _guest: &mut T,
786        eax: u32,
787        ecx: u32,
788    ) -> Result<raw_cpuid::CpuIdResult, Errno> {
789        Ok(raw_cpuid::cpuid!(eax, ecx))
790    }
791
792    /// rdtsc/rdtscp is trapped, the tool should implement this function to
793    /// return the counter.
794    ///
795    /// NOTE:
796    ///  * This is never called by default unless rdtsc events are subscribed
797    ///    to.
798    ///  * This is only available on x86_64.
799    #[cfg(target_arch = "x86_64")]
800    async fn handle_rdtsc_event<T: Guest<Self>>(
801        &self,
802        _guest: &mut T,
803        request: Rdtsc,
804    ) -> Result<RdtscResult, Errno> {
805        Ok(RdtscResult::new(request))
806    }
807
808    /// Handles a guest's signal before it is delivered to guest.
809    ///
810    /// # Return value
811    ///  - `Some(sig)`: The signal `sig` will be delivered to guest.
812    ///  - `None`: The signal is supressed and never delivered to the guest.
813    async fn handle_signal_event<T: Guest<Self>>(
814        &self,
815        _guest: &mut T,
816        signal: Signal,
817    ) -> Result<Option<Signal>, Errno> {
818        Ok(Some(signal))
819    }
820
821    /// Handles a guest's signal that [`Signal`] cannot name before it is
822    /// delivered to the guest: a realtime signal, numbered 32 to 64 (glibc
823    /// reserves 32 and 33, so `SIGRTMIN()` is 34). `signal` is the raw number.
824    /// A backend reports every other signal to [`Tool::handle_signal_event`]
825    /// (<https://github.com/rrnewton/reverie/issues/207>).
826    ///
827    /// # Return value
828    ///  - `Some(sig)`: the raw signal `sig` will be delivered to the guest.
829    ///  - `None`: the signal is suppressed and never delivered to the guest.
830    ///
831    /// The default delivers it unchanged, as a backend that could not report
832    /// it would.
833    async fn handle_raw_signal_event<T: Guest<Self>>(
834        &self,
835        _guest: &mut T,
836        signal: i32,
837    ) -> Result<Option<i32>, Errno> {
838        Ok(Some(signal))
839    }
840
841    /// Decides whether a signal that the backend passes to the guest without
842    /// reporting it to [`Tool::handle_signal_event`] reaches the guest at all.
843    ///
844    /// A backend may pass a signal on unreported where reporting it could
845    /// change what the guest observes: the ptrace backend does so for many
846    /// signals it held while a Tool injection ran, and for signals that arrive
847    /// while it steps the guest through its own setup. Such a signal is
848    /// otherwise invisible to the Tool, so a Tool that must keep exactly one
849    /// copy of a signal (for example, its own copy of one the kernel also
850    /// sent) needs to see it here. Every such signal is shown, whatever its
851    /// number (realtime signals included), siginfo or sender, including the backend's own, which Linux
852    /// does not tell apart from a guest's signal of the same number (the
853    /// ptrace backend's: a SIGSTOP of a gdb freeze or of a group-stop request,
854    /// and its timer's signal, SIGSTKFLT). Dropping one of those breaks the
855    /// backend, so keep every signal you do not own. The hook can be called
856    /// before the guest's first exec, while the backend initializes it; a
857    /// failed GlobalTool ends a hook still waiting on its RPC then as at any
858    /// other time.
859    ///
860    /// The hook can only decide: it gets the signal's read-only description
861    /// and a handle that can send RPCs to the global tool, and no access to
862    /// the guest, so it cannot inject a syscall or change the guest's
863    /// registers or memory. Drop only a signal identified by its siginfo; a
864    /// signal shown without one is one the backend could not record.
865    ///
866    /// # Return value
867    ///  - `true`: the signal is passed on as before.
868    ///  - `false`: the signal is dropped and never delivered to the guest.
869    ///
870    /// The default keeps every signal. A backend that never passes a signal
871    /// on unreported never calls it.
872    async fn filter_unreported_signal<R: GlobalRPC<Self::GlobalState>>(
873        &self,
874        _rpc: &R,
875        _signal: crate::UnreportedSignal,
876    ) -> bool {
877        true
878    }
879
880    /// Whether this Tool wants every guest `rt_sigreturn` reported to
881    /// [`Tool::handle_sigreturn`], known from configuration alone. A backend
882    /// whose capabilities say it reports sigreturns
883    /// ([`BackendCapabilities::reports_sigreturns`](crate::BackendCapabilities::reports_sigreturns))
884    /// then reports each one, except those the capability names; the ptrace
885    /// backend stops at each guest `rt_sigreturn` only for such a Tool, and
886    /// not while its gdbserver is attached. The default wants none, so a
887    /// backend adds no stop.
888    fn observes_sigreturns(_config: &<Self::GlobalState as GlobalTool>::Config) -> bool {
889        false
890    }
891
892    /// Whether this Tool, known from configuration alone, enforces a
893    /// serialized-execution contract:
894    /// - at most one guest thread runs at any time, so no guest thread runs
895    ///   while the backend works on another, stopped one;
896    /// - the guest cannot install a seccomp filter: the Tool refuses
897    ///   `seccomp(SECCOMP_SET_MODE_FILTER)` and `prctl(PR_SET_SECCOMP)`; and
898    /// - no seccomp filter is installed on the tracer's own threads once the
899    ///   trace has started, by the Tool or the program that embeds it: the
900    ///   backend reads each tracer thread's filter state once, and a filter
901    ///   that comes later goes unseen.
902    ///
903    /// The backend trusts the declaration and does not check it. The ptrace
904    /// backend keeps the guest's SIGTRAP action and mask across its own
905    /// single-steps only for such a Tool, on x86-64: that repair injects
906    /// `rt_sigaction` into a stopped thread, which a guest thread running
907    /// meanwhile could defeat, for example by installing with
908    /// `SECCOMP_FILTER_FLAG_TSYNC` a filter that kills the injected call
909    /// (<https://github.com/rrnewton/hermit/issues/4409>). The default
910    /// declares nothing, and the backend then leaves SIGTRAP as Linux's step
911    /// traps leave it.
912    fn enforces_serialized_execution(_config: &<Self::GlobalState as GlobalTool>::Config) -> bool {
913        false
914    }
915
916    /// Records one guest `rt_sigreturn` before it runs, for a Tool for which
917    /// [`Tool::observes_sigreturns`] holds, on a backend that reports
918    /// sigreturns. The backend then carries the call out exactly as it would
919    /// without the hook.
920    ///
921    /// The hook can only record: it gets the calling thread's state and the
922    /// report, and no access to the guest, so it cannot inject a syscall or
923    /// change the guest's registers or memory.
924    fn handle_sigreturn(
925        &self,
926        _thread_state: &mut Self::ThreadState,
927        _report: crate::SigreturnReport,
928    ) {
929    }
930
931    /// Records, in the taking thread's state, one signal the backend passes
932    /// on unreported, after [`Tool::filter_unreported_signal`] decided about
933    /// it: `kept` is that hook's answer. A kept signal is resumed into the
934    /// guest, and Linux then delivers it, puts it back in the queue when the
935    /// thread's mask blocks it (a later stop can take the same instance again
936    /// and pass it once more), queues a new instance with a kernel siginfo
937    /// (a syscall stop), or discards it (an ignored signal, or a ptrace event
938    /// stop or group stop); a dropped one is not resumed. So the hook sees passes, not deliveries.
939    /// The signal's
940    /// [`crate::UnreportedSignal::reason`] says why it was not reported, so
941    /// that a Tool can count what its signal callback never saw.
942    ///
943    /// The hook can only record: it gets the thread's state and the signal's
944    /// read-only description, and no access to the guest. The default
945    /// records nothing.
946    fn note_unreported_signal(
947        &self,
948        _thread_state: &mut Self::ThreadState,
949        _signal: &crate::UnreportedSignal,
950        _kept: bool,
951    ) {
952    }
953
954    /// Admits acknowledgment of real KVM pending removals before thread start.
955    /// Other Tools retain their existing pending-state behavior by default.
956    ///
957    /// This is an upper bound known from configuration alone: a run observes
958    /// dequeues only when this returns `true` and, after installation,
959    /// [`GlobalTool::observe_signal_dequeues`] also returns `true` for the
960    /// installed mode. The bound exists for refusals that must precede
961    /// installation and any guest code. The static-ELF runner requires
962    /// effective [`ThreadOwnership::Tool`], including caller overrides, and
963    /// rejects an incompatible Host choice before initializing GlobalState or
964    /// consuming/executing the installed ELF. Admitting observation does not
965    /// require process signal control: see [`Tool::requires_signal_control`].
966    fn may_observe_signal_dequeues(_config: &<Self::GlobalState as GlobalTool>::Config) -> bool {
967        false
968    }
969
970    /// Whether this run cannot proceed without process signal control, known
971    /// from configuration alone.
972    ///
973    /// reverie-kvm's non-ELF loop, which has no process signal control to
974    /// offer, rejects a `true` answer with `ENOSYS` after initializing
975    /// GlobalState, so that state's startup records are kept, and before
976    /// asking it to install a control. reverie-kvm's runners that offer
977    /// control consult this after
978    /// [`GlobalTool::install_backend_signal_control`] returns: a `true` answer
979    /// with any mode other than `ToolControlled` is refused with `EINVAL`
980    /// before the first guest hook, through the same failure path as an
981    /// installation error. The default requires nothing, so a Tool that only
982    /// observes dequeues runs everywhere it ran before.
983    fn requires_signal_control(_config: &<Self::GlobalState as GlobalTool>::Config) -> bool {
984        false
985    }
986
987    /// Acknowledges one irreversible pending removal before any later Tool/guest work.
988    /// The backend retains the journal entry until this returns success. An error
989    /// is terminal; it is never a rollback or an ordinary guest syscall errno.
990    /// Notifications are process-wide FIFO, but each runs on its removing Guest.
991    /// Another owner can wait here before posting its next Tool scheduler request.
992    /// An opted-in Tool must complete this acknowledgment without requiring that
993    /// waiting owner to make progress or relinquish its scheduler token. FIFO
994    /// sequencing alone does not establish deterministic event membership.
995    async fn handle_signal_dequeue<G: Guest<Self>>(
996        &self,
997        _guest: &mut G,
998        _dequeue: crate::SignalDequeue,
999    ) -> Result<(), Errno> {
1000        Ok(())
1001    }
1002
1003    /// Handles a structured guest signal immediately before a virtual backend
1004    /// delivers it.
1005    ///
1006    /// The default is a compatibility bridge to [`Self::handle_signal_event`]
1007    /// for signal numbers represented by [`Signal`]. It preserves the complete
1008    /// event when the legacy hook keeps it and preserves suppression when that
1009    /// hook drops it. Legacy signal-number replacement and raw real-time signal
1010    /// numbers are rejected with `ENOSYS`, because neither path can produce
1011    /// coherent replacement `siginfo_t`; a structured override must do that
1012    /// rather than silently losing information in the legacy enum.
1013    async fn handle_structured_signal_event<T: Guest<Self>>(
1014        &self,
1015        guest: &mut T,
1016        event: SignalEvent,
1017    ) -> Result<Option<SignalEvent>, Errno> {
1018        let signal = Signal::try_from(event.signal()).map_err(|_| Errno::ENOSYS)?;
1019        match self.handle_signal_event(guest, signal).await? {
1020            None => Ok(None),
1021            Some(replacement) if replacement as i32 == event.signal() => Ok(Some(event)),
1022            // Linux's ptrace reinjection path clears the old siginfo and
1023            // synthesizes SI_USER with the tracer parent's credentials when a
1024            // tracer changes the signal number. A virtual backend has no
1025            // faithful guest-visible identity for that host tracer. Refuse the
1026            // lossy legacy replacement; a structured-hook override can return
1027            // a new SignalEvent with coherent replacement metadata.
1028            Some(_) => Err(Errno::ENOSYS),
1029        }
1030    }
1031
1032    /// Handles a timer event generated by a call to `Guest::set_timer`
1033    async fn handle_timer_event<T: Guest<Self>>(&self, _guest: &mut T) {}
1034
1035    /// Called when a thread will exit shortly or has exited. That means there
1036    /// will be no more intercepted events on this thread.
1037    ///
1038    /// Serves as a "destructor" for the thread state, and thus takes it by move.
1039    /// KVM cleanup consumes each constructed state once on returned runtime
1040    /// errors or cancellation, including states whose `handle_thread_start`
1041    /// was never entered or completed. No further guest event is started to
1042    /// perform this cleanup. Panic unwinding may bypass the hook.
1043    ///
1044    /// # Exit status: exact, or predicted
1045    ///
1046    /// A backend that observes the death from outside the guest (ptrace)
1047    /// passes the kernel's status. A backend that runs the Tool inside the
1048    /// guest reports a death before it happens, because the Tool dies with
1049    /// the guest; then only part of the status is known. For an exit, the
1050    /// code is exact. For a death by a signal the guest sends itself (the
1051    /// in-guest host's `deliver_staged_signals`), the signal is exact, and the
1052    /// core-dump flag of [`ExitStatus::Signaled`] is a prediction from the
1053    /// inputs Linux checks before it writes a core (the signal's default
1054    /// action, the dumpable mode, `RLIMIT_CORE` and `core_pattern`); the
1055    /// kernel's own flag differs when its write of the core fails. A Tool must
1056    /// not rely on that flag from such a backend. The same holds for
1057    /// [`Tool::on_exit_process`].
1058    ///
1059    /// # Signals a Tool sends its own guest, under an in-guest backend
1060    ///
1061    /// The in-guest host holds a signal a Tool's injection sends the guest
1062    /// itself, when it would end the process, until the callback that sent
1063    /// it returns, and then delivers it as a tracer delivers a held signal.
1064    /// An injection that ends the guest (an exit, or a SIGKILL of the guest
1065    /// itself) ends the callback that made it there, as under a tracer; the
1066    /// callback does not resume. That ending is latched when the injection
1067    /// is made, and the guest ends even if the callback then returns. A Tool
1068    /// that abandons the injection's future and goes on gets no further
1069    /// effect on the guest through its [`Guest`]:
1070    ///
1071    /// - `inject`, `tail_inject`, `set_regs`, the signal deliveries
1072    ///   (`defer_signal_delivery`, `defer_signal_delivery_before_syscall`)
1073    ///   and `send_rpc` never complete: the callback stays parked until the
1074    ///   host ends the process, so a request that could block on the
1075    ///   coordinator is never sent;
1076    /// - every read and write through a `memory()` handle, one obtained
1077    ///   before the injection included, fails with ESRCH and copies nothing,
1078    ///   as a tracer's access to a tracee its injection killed fails;
1079    /// - the backend's blocking coordinator request for synchronous Tool
1080    ///   code (LiteInst's `blocking_global_rpc`) fails with ESRCH, unsent.
1081    ///
1082    /// The rest of the interface has no effect on the guest (`regs`, `pid`,
1083    /// `thread_state` and the other reads; `stack`, whose storage is the
1084    /// host's; `set_timer`, which the in-guest host refuses). The exit
1085    /// callbacks run afterwards with their own coordinator connection and no
1086    /// [`Guest`], and may use both the connection and the blocking request.
1087    /// Effects a Tool makes outside these interfaces (its own system calls,
1088    /// direct stores to guest memory, a `LocalMemory` it constructs itself)
1089    /// are not seen by the host, and remain the Tool's responsibility, as
1090    /// every such effect is.
1091    ///
1092    /// These cases are unsupported, and the host ends the process as a Tool
1093    /// error that names the case (exit status 125) before anything is made
1094    /// for it: a `tail_inject` of a call that does not end the guest outside
1095    /// a syscall handler (in a start-up, instruction or signal callback); a
1096    /// process creation (fork, vfork, clone or clone3, refused by syscall
1097    /// number without reading guest memory) injected outside a syscall
1098    /// handler; and a signal callback that has SIGALRM
1099    /// delivered while the guest's SIGALRM handler is kept virtual (signal
1100    /// phase 1), which only the backend's own delivery can reach: in place of
1101    /// another signal, or as the guest's own SIGALRM, held while the Tool
1102    /// installed the guest's handler; and installing a seccomp filter after a
1103    /// self-signal has been staged, including during its signal callback or
1104    /// while the delivery drain owns pending signals. The filter installation
1105    /// is refused before it executes, through both `inject` and `tail_inject`.
1106    ///
1107    /// # Supported self-signal deaths
1108    ///
1109    /// Staging covers `kill`, `tkill`, and `tgkill` aimed at the calling
1110    /// process or thread, for unblocked standard signals 1 through 31 with
1111    /// a terminating default action and no admitted guest seccomp filter.
1112    /// SIGTRAP uses the guest's action behind the runtime's routing handler.
1113    /// Explicit self-kill with SIGPIPE is included; SIGPIPE raised by a failed
1114    /// write is a different source and is excluded. Real-time signals cannot
1115    /// be named by the Tool's `Signal` and are excluded. Process-group and
1116    /// broadcast kill targets are excluded as well.
1117    ///
1118    /// # Self-signal deaths that remain a recorded loss
1119    ///
1120    /// The in-guest host stages a guest's self-directed fatal signal (and
1121    /// runs the exit callbacks before it) only when the signal's action is
1122    /// the guest's own default. Two cases keep the earlier behaviour, where
1123    /// the process dies without its exit callbacks and the Tool records that
1124    /// it exited without deregistering (an explicit determinism loss, never a
1125    /// silent pass): a signal the runtime itself handles for the guest
1126    /// (SIGSEGV while LiteInst routes instruction subscriptions through it,
1127    /// and SIGSYS, the runtime's seccomp trap), and any self-directed signal
1128    /// once a guest seccomp filter has been admitted, where the call runs as
1129    /// the guest's own, so a filter's errno is honoured. Filter admission is
1130    /// possible only without a creation hook and without virtual SIGALRM
1131    /// handler admission; a Tool such as Hermit may refuse guest filters
1132    /// independently. Installing the runtime before any seccomp filter is
1133    /// active remains the backend's unsafe launch precondition.
1134    ///
1135    /// Hardware faults, signals from another process or the scheduler, and
1136    /// syscall-generated SIGPIPE also retain their existing recorded loss.
1137    /// A standalone Tool must arrange to detect missing exit callbacks;
1138    /// Hermit's coordinator records the deregistration loss and strict
1139    /// verification refuses it.
1140    async fn on_exit_thread<G: GlobalRPC<Self::GlobalState>>(
1141        &self,
1142        _tid: Tid,
1143        _global_state: &G,
1144        _thread_state: Self::ThreadState,
1145        _exit_status: ExitStatus,
1146    ) -> Result<(), Error> {
1147        Ok(())
1148    }
1149
1150    /// Called when a process will exit shortly or has exited. That means there
1151    /// will be no more intercepted events on from any thread within this
1152    /// process.
1153    ///
1154    /// Serves as a "destructor" for the process state (`self`), and thus takes
1155    /// it by move.
1156    /// On KVM this also consumes a constructed process cancelled before its
1157    /// initial thread starts, after the thread states have been consumed. It
1158    /// must support cleanup after fatal failure without ordinary guest RPC
1159    /// progress. Panic unwinding may bypass the hook.
1160    ///
1161    /// The status is exact or predicted as described for
1162    /// [`Tool::on_exit_thread`].
1163    async fn on_exit_process<G: GlobalRPC<Self::GlobalState>>(
1164        self,
1165        _pid: Pid,
1166        _global_state: &G,
1167        _exit_status: ExitStatus,
1168    ) -> Result<(), Error> {
1169        Ok(())
1170    }
1171}
1172
1173/// A "noop" tool that doesn't do anything.
1174impl Tool for () {
1175    type GlobalState = ();
1176    type ThreadState = ();
1177
1178    fn subscriptions(_cfg: &()) -> Subscription {
1179        Subscription::none()
1180    }
1181}
1182
1183/// A handle to send messages to the global state (potentially a remote,
1184/// inter-process communication).
1185#[async_trait]
1186pub trait GlobalRPC<G: GlobalTool>: Sync {
1187    /// Send an RPC message to wherever the global state is stored, synchronously
1188    /// blocks the current thread until a response is received.
1189    async fn send_rpc(&self, message: G::Request) -> G::Response;
1190
1191    /// Optionally complete an RPC without constructing or polling a future.
1192    ///
1193    /// An unsupported implementation returns the original request without
1194    /// sending any part of it or changing transport admission. An implementation
1195    /// returning `Ok` uses its ordinary authenticated channel and wire contract.
1196    /// This does not grant a scheduler turn, promise nonallocating arbitrary
1197    /// serialization, or permit a request whose completion requires this caller
1198    /// to yield. Transport failures retain that implementation's normal failure
1199    /// behavior; they must not be relabeled as an unsupported request.
1200    fn try_send_rpc_sync(&self, message: G::Request) -> Result<G::Response, G::Request> {
1201        Err(message)
1202    }
1203
1204    /// Return the read-only tool configuration
1205    fn config(&self) -> &G::Config;
1206}