Skip to main content

kizz_trace_linux/
lib.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The kizz tracer for Linux.
6//!
7//! [`LinuxTracer`] implements the tracer interface of `kizz_trace` with `ptrace` and
8//! a seccomp-bpf filter that stops a traced process only for the system calls that
9//! touch the file system, [`TRACKED_SYSTEM_CALLS`], those that make the trace
10//! incomplete, [`UNTRACEABLE_SYSTEM_CALLS`], and the native calls outside the table
11//! that it knows, [`KNOWN_SYSTEM_CALLS`], and lets every other call run at full
12//! speed. Only the `kizz` binary wires it in.
13//!
14//! The tracer traces only the processes it starts itself: the child requests
15//! tracing with `PTRACE_TRACEME` before it runs the program, and the tracer follows
16//! the whole tree of processes and threads it starts, with the option that kills
17//! all of them if the tracer exits. Nothing in the traced program changes, except
18//! that `io_uring_setup` fails with `ENOSYS`, so its file accesses stay observable.
19//!
20//! At each tracked call the tracer reads the call's path arguments, directory
21//! descriptors and flags from the stopped thread before the call runs, and its
22//! result after it returns, and reports every path the tree touched as an absolute
23//! path with its combined access kinds. Successful and failed calls are recorded
24//! alike: a failed call, including a lookup that found nothing, is a probe. An
25//! `openat2` with `RESOLVE_IN_ROOT` or `RESOLVE_BENEATH` and without `O_NONBLOCK`
26//! that fails with `EAGAIN` records nothing, though: Linux gives that error when a
27//! rename or mount anywhere on the machine races with a `..` step, and abandons the
28//! lookup, so the caller may repeat the call, and each repeated call is recorded
29//! like any other.
30//!
31//! A process that makes one of [`UNTRACEABLE_SYSTEM_CALLS`], which can change what a
32//! path means or use a path in a way that the tracer does not record, marks the run
33//! as incompletely traced when it makes the call, whether or not the call succeeds,
34//! with a reason that names the process and the call; `clone`, `clone3` and
35//! `unshare` count only with `CLONE_NEWNS`, and `setns` only when it can enter a
36//! mount namespace. A native system call outside [`KNOWN_SYSTEM_CALLS`] leaves the
37//! trace complete: the tracer reports its number in the result's unknown system
38//! calls. Either call then runs unchanged.
39//!
40//! The socket calls of [`TRACKED_SYSTEM_CALLS`] name socket addresses: a Unix socket
41//! path is recorded like any path, a write for `bind` and a probe for the others,
42//! and `connect`, and `sendto`, `sendmsg` and `sendmmsg` with a destination, also
43//! report it in the result's connections: each IPv4 or IPv6 address and port
44//! whatever the outcome of the call, and each Unix socket, by path or abstract name,
45//! unless its path was not found. Other socket families are not recorded.
46//!
47//! At the exit of a successful call that opens a regular file for reading or runs
48//! one, the tracer also notes the file's metadata as its first read, unless the
49//! tree wrote that path earlier or the call created or truncated the file: through
50//! the descriptor that an opening call returned, and through the path for the
51//! program of an `exec` and each interpreter and loader that the kernel loaded.
52//!
53//! When the request asks for the process tree, the tracer also keeps, apart from
54//! the combined accesses, which stay exactly as without it, each process of the
55//! tree with the programs it ran and how it ended, and attributes what each call
56//! touched to the program that its thread's process ran, each kind with the call's
57//! outcome: `ok`, the name of the error, or `unknown` for a call whose result it
58//! never saw. A successful `exec` belongs to the program that it starts, whose
59//! arguments the tracer reads at the call's entry. Connections, unknown system
60//! calls and every reason that the trace is incomplete belong to programs in the
61//! same way, while the result keeps the first reason. A command that cannot start
62//! gives an error whose tree holds its one process, without a status, with the
63//! request's program and what the attempt touched. Without the request, the tracer
64//! does none of this extra work.
65//!
66//! [`LinuxTracer`] also answers the platform queries of the tracer interface. It
67//! reads the extended attributes of a path with `listxattr` and `getxattr`, or
68//! `llistxattr` and `lgetxattr` without following a final symbolic link, and a file
69//! system that keeps none (`EOPNOTSUPP`) has none. It reads the machine state that
70//! a command it starts inherits from its own thread: the kernel with `uname`, every
71//! resource limit with `getrlimit`, the CPUs with `sched_getaffinity`, the
72//! `MemTotal` and `MemAvailable` lines of `/proc/meminfo`, and the file system of
73//! the working directory with `statfs`, and its mount flags with `statvfs`. It
74//! names an error number with Linux's name for it, such as `ENOENT`, the kernel's
75//! names for its internal restart errors, such as `ERESTARTSYS`, and `errno` and the
76//! number for any other.
77//!
78//! When a request is cancelled, the tracer interrupts the tree: it sends `SIGINT`
79//! once to every live process. It follows the tree as before for
80//! [`CANCEL_GRACE_PERIOD`], and returns as soon as the whole tree has exited; when
81//! the grace period ends first, it kills whatever remains with `SIGKILL`. A
82//! cancelled run may therefore end with an exit code that the program chose after
83//! it handled the interrupt. The program of a build runs in a process group of its
84//! own, with pipes or `/dev/null` as its standard streams, so an interrupt that a
85//! terminal sends to the tracer's process group never reaches it directly: it
86//! receives the interrupt exactly once, from the tracer.
87//!
88//! A request that keeps the terminal ([`RunRequest::terminal`]), as `kizz execute`
89//! makes, connects nothing: the program uses the standard input, output and error
90//! of the tracer's process directly, and stays in that process's process group and
91//! session, so a terminal's input and signals, Ctrl-C included, reach it as they
92//! would without kizz. Nothing is captured or echoed, no thread feeds or reads its
93//! streams, and the result's output is empty, in the shape of the request's capture
94//! mode. In both ways the program starts with an empty signal mask and `SIGPIPE`
95//! at its default action, and inherits every other disposition, so a signal that
96//! the tracer's process ignores stays ignored in it.
97//!
98//! The caller forwards a signal with [`Cancellation::forward`]; until the request
99//! is cancelled, the watchdog delivers each one once, to the first process until
100//! the tracer has collected its end, and afterwards to each live process of the
101//! tree, signaling only the process IDs of the live set. The tracer knows the
102//! first process by its identity, not by its process ID, which Linux may give to a
103//! later process of the tree once the first is collected. A signal sent to the
104//! whole process group of a program that keeps the terminal reaches it directly,
105//! and once more when the caller forwards it, since neither can tell it from one
106//! sent to the caller alone.
107//!
108//! The tracer resumes a process that a stop signal stopped, because with
109//! `PTRACE_TRACEME` it cannot learn when `SIGCONT` would end the stop. A terminal's
110//! Ctrl-Z therefore stops the tracer's process, which keeps the default action of
111//! `SIGTSTP`, `SIGTTIN` and `SIGTTOU`, and each traced process waits at its next
112//! stop for the tracer, while a stop signal sent to one traced process alone does
113//! not keep it stopped.
114//!
115//! Each run starts its threads through `kizz_threads`, which waits and retries while
116//! the system cannot start a thread for the moment, and never panics: the thread
117//! that feeds `stdin`, `kizz-feeder`, and a thread that captures each output
118//! stream, `kizz-stdout` and `kizz-stderr`, or `kizz-output` for merged output,
119//! which start first, before anything of the request runs; then the tracing
120//! thread, `kizz-tracer`; and the watchdog of cancellation, `kizz-watchdog`. When
121//! one still cannot start, no process of the request is left, and the run returns
122//! [`TraceError::Tracer`], whose message names the thread and the system's error.
123//!
124//! The cleanup of last resort is the end of the tracing thread: every process and
125//! thread of the tree is its tracee, with `PTRACE_O_EXITKILL`, so when the thread
126//! ends, for an error, a panic or the end of the tree, Linux kills whatever is left
127//! of the tree, also processes that left its process group or session and threads
128//! in stops that the tracer already collected. The run then collects its first
129//! process through a process descriptor, and its output and input threads end with
130//! the pipes. No step of that reads `/proc` or signals a process or thread ID.
131//! Collecting by descriptor needs Linux 5.4 or later: the descriptor comes from
132//! `pidfd_open`, and `waitid` with `P_PIDFD` collects the process.
133
134#[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
135compile_error!("the kizz tracer supports only Linux on x86_64");
136
137mod capture;
138mod decode;
139mod errors;
140mod filter;
141mod follow;
142mod processes;
143mod spawn;
144mod sys;
145mod untraced;
146
147use std::{
148    collections::BTreeSet,
149    io,
150    os::fd::OwnedFd,
151    path::Path,
152    sync::{
153        OnceLock,
154        mpsc::{self, RecvTimeoutError},
155    },
156    thread,
157    time::Duration,
158};
159
160pub use filter::{
161    KNOWN_SYSTEM_CALLS, TRACKED_SYSTEM_CALLS, TrackedSystemCall, UNTRACEABLE_SYSTEM_CALLS,
162};
163use kizz_threads::ScopedJoinHandle;
164use kizz_trace::{
165    Accesses, Cancellation, EchoSink, ExtendedAttributes, FirstReads, MachineState, OutputStream,
166    RunRequest, RunResult, Signal, TraceError, Tracer,
167};
168use libc::{c_int, pid_t, sock_filter};
169
170use crate::{
171    capture::TracerStdio,
172    follow::{Escalation, LiveProcesses},
173    spawn::{ChildStdio, Program, Started},
174};
175
176/// How often the cancellation watchdog checks the cancellation flag and, until the
177/// request is cancelled, takes and delivers the signals that the caller forwarded.
178const CANCEL_POLL_INTERVAL: Duration = Duration::from_millis(5);
179
180/// How long a cancelled tree may run after its interrupt, the `SIGINT` that every
181/// live process receives once, before the tracer kills whatever remains of it.
182pub const CANCEL_GRACE_PERIOD: Duration = Duration::from_secs(2);
183
184/// Runs commands under `ptrace` with a seccomp-bpf filter in front.
185///
186/// Each call to [`Tracer::run`] starts and traces its own process tree from a new
187/// thread that has no other child, so tracers on several threads of one process run
188/// independently, and no run waits for a child that its caller started.
189#[derive(Debug, Clone, Copy, Default)]
190pub struct LinuxTracer;
191
192impl LinuxTracer {
193    /// A Linux tracer.
194    #[must_use]
195    pub const fn new() -> Self {
196        Self
197    }
198}
199
200/// The error for a failure of the tracer itself.
201fn tracer_error(
202    message: &str,
203    source: io::Error,
204) -> TraceError {
205    TraceError::Tracer {
206        message: message.to_owned(),
207        source: Some(source),
208    }
209}
210
211/// Wait for a helper thread of a run and return its result.
212fn join<T>(
213    handle: ScopedJoinHandle<'_, io::Result<T>>,
214    what: &str,
215) -> Result<T, TraceError> {
216    match handle.join() {
217        Ok(result) => result.map_err(|error| tracer_error(what, error)),
218        Err(_) => {
219            Err(TraceError::Tracer {
220                message: format!("the thread {what} panicked"),
221                source: None,
222            })
223        },
224    }
225}
226
227/// The tracer error for a thread of the run that could not be started, whose
228/// message names the thread and the system's error.
229fn not_started(error: &kizz_threads::StartError) -> TraceError {
230    TraceError::Tracer {
231        message: error.to_string(),
232        source: None,
233    }
234}
235
236/// The name and the description of the thread that captures `stream`.
237const fn reader_thread(stream: OutputStream) -> (&'static str, &'static str) {
238    match stream {
239        OutputStream::Stdout => ("kizz-stdout", "the thread that captures standard output"),
240        OutputStream::Stderr => ("kizz-stderr", "the thread that captures standard error"),
241        OutputStream::Merged => ("kizz-output", "the thread that captures the merged output"),
242    }
243}
244
245/// The signal number of a forwarded [`Signal`].
246const fn signal_number(signal: Signal) -> c_int {
247    match signal {
248        Signal::Hangup => libc::SIGHUP,
249        Signal::Terminate => libc::SIGTERM,
250    }
251}
252
253/// Deliver every signal forwarded through `cancel` since the last call to the tree,
254/// under the rules of [`follow::signal_first`]: to its first process until the loop
255/// has collected that process's end, which the live set knows by identity, and
256/// afterwards to every live process, waiting at most `patience` for the live set.
257///
258/// # Errors
259///
260/// The error of a live set that stays locked, when the signal is not sent.
261fn forward(
262    live: &LiveProcesses,
263    cancel: &Cancellation,
264    patience: Duration,
265) -> io::Result<()> {
266    for signal in cancel.take_forwarded() {
267        follow::signal_first(live, signal_number(signal), patience)?;
268    }
269    Ok(())
270}
271
272/// Forward the signals that the caller forwards through `cancel` to the tree whose
273/// live processes `live` holds until the request is cancelled; then interrupt the
274/// tree, and kill whatever remains of it when the grace period ends, until `done`
275/// is dropped.
276///
277/// Every [`CANCEL_POLL_INTERVAL`] until cancellation, the watchdog takes the
278/// forwarded signals and delivers each once, under the rules of
279/// [`follow::signal_first`]: to the first process until the loop has collected its
280/// end, and afterwards to every live process, also to a later process that Linux
281/// gave the first process's ID. Once the request is cancelled, it forwards nothing
282/// more.
283///
284/// On cancellation the watchdog sends `SIGINT` once to every live process. During
285/// [`CANCEL_GRACE_PERIOD`] the event loop follows the tree as it does without
286/// cancellation, and a tree that exits in that time drops `done`, which ends the
287/// watchdog at once. When the grace period ends first, the watchdog sets
288/// `escalation`, so the event loop kills every thread it sees from then on, and
289/// then sends `SIGKILL` to every live process; it also covers a tree whose threads
290/// are all blocked and report nothing. It signals only the process IDs in the live
291/// set, never the ID of a thread that does not lead its process, which that thread
292/// releases when it runs `exec`.
293///
294/// When the live set stays locked for `patience`, so the watchdog cannot signal its
295/// processes, it asks the tracing thread to end the run, with [`Escalation::end`],
296/// which wakes the thread from its wait, and asks again every
297/// [`CANCEL_POLL_INTERVAL`] until the loop has ended and dropped `done`. The
298/// tracing thread's end then kills the whole tree, escaped and stopped processes
299/// included, with no live set, no process group and no ID.
300///
301/// # Errors
302///
303/// The error of a live set that stays locked; the run then fails with it.
304fn watch(
305    live: &LiveProcesses,
306    cancel: &Cancellation,
307    escalation: &Escalation,
308    done: &mpsc::Receiver<()>,
309    patience: Duration,
310) -> io::Result<()> {
311    // End the run without the live set, for a set that stays locked.
312    let end = |error: io::Error| -> io::Result<()> {
313        loop {
314            // A wake that fails leaves the request noted, and the loop reads it
315            // before its next wait; the next round wakes it again.
316            drop(escalation.end());
317            match done.recv_timeout(CANCEL_POLL_INTERVAL) {
318                Err(RecvTimeoutError::Timeout) => {},
319                Ok(()) | Err(RecvTimeoutError::Disconnected) => return Err(error),
320            }
321        }
322    };
323    while !cancel.is_cancelled() {
324        if let Err(error) = forward(live, cancel, patience) {
325            return end(error);
326        }
327        match done.recv_timeout(CANCEL_POLL_INTERVAL) {
328            Err(RecvTimeoutError::Timeout) => {},
329            Ok(()) | Err(RecvTimeoutError::Disconnected) => return Ok(()),
330        }
331    }
332    if let Err(error) = follow::signal_all(live, libc::SIGINT, patience) {
333        return end(error);
334    }
335    match done.recv_timeout(CANCEL_GRACE_PERIOD) {
336        Err(RecvTimeoutError::Timeout) => {},
337        Ok(()) | Err(RecvTimeoutError::Disconnected) => return Ok(()),
338    }
339    escalation.escalate();
340    follow::signal_all(live, libc::SIGKILL, patience).or_else(end)
341}
342
343/// What the event loop and the helper threads of one run produced.
344struct Supervised {
345    /// The process ID of the child that the tracer forked.
346    pid: pid_t,
347    /// The outcome of the event loop, or `None` when the child exited before it
348    /// came under `ptrace`.
349    followed: io::Result<Option<follow::Outcome>>,
350    /// The captured bytes of each output stream.
351    streams: Result<Vec<(OutputStream, Vec<u8>)>, TraceError>,
352    /// The result of feeding `stdin`.
353    fed: Result<(), TraceError>,
354}
355
356/// What the tracing thread needs to start the traced program.
357struct Launch<'a> {
358    /// The request.
359    request: &'a RunRequest,
360    /// The program, its arguments and its environment, prepared for the child.
361    program: &'a Program,
362    /// The seccomp-bpf filter that the child installs.
363    filter: &'a [sock_filter],
364    /// The child's ends of its standard streams, which kizz closes once the child
365    /// has them, or when the program never starts; `None` for a command that keeps
366    /// the terminal.
367    stdio: Option<ChildStdio>,
368    /// The write end of the failure pipe.
369    report: OwnedFd,
370}
371
372/// What the tracing thread produced: the process ID of the child that it forked,
373/// and the outcome of the event loop, or `None` when the child exited before it
374/// came under `ptrace`.
375type Traced = (pid_t, io::Result<Option<follow::Outcome>>);
376
377/// The loop's result `followed` together with the watchdog's `watched`: when the
378/// watchdog asked the tracing thread to end the run, the loop failed only for that,
379/// and the watchdog's error, the live set that stayed locked, is the run's;
380/// otherwise the loop's error comes first, then the watchdog's.
381fn settle(
382    followed: io::Result<follow::Outcome>,
383    watched: io::Result<()>,
384    escalation: &Escalation,
385) -> io::Result<Option<follow::Outcome>> {
386    match (followed, watched) {
387        (Ok(outcome), Ok(())) => Ok(Some(outcome)),
388        (Err(_), Err(error)) if escalation.is_ended() => Err(error),
389        (Err(error), _) | (Ok(_), Err(error)) => Err(error),
390    }
391}
392
393/// Start the program of `launch` on the calling thread, the tracing thread, and
394/// follow its tree to the end while the watchdog, whose live-set locks wait at most
395/// `patience`, watches `cancel`.
396///
397/// The thread's only child is the program's first process, whose descriptor goes
398/// into `root` at once, before the program runs, so the caller can collect the
399/// process once this thread has ended. When anything fails after the start, the
400/// error is returned at once and nothing here cleans up: this thread then ends, and
401/// its end kills the whole tree ("The cleanup of last resort" of the `follow`
402/// module). That holds for a thread that cannot be prepared to be woken, a first
403/// process that cannot enter the live set, a watchdog that cannot start, and a
404/// loop that fails, the loop that the watchdog ends included.
405///
406/// # Errors
407///
408/// The [`TraceError`] of the start, of preparing this thread to be woken, of the
409/// live set, or of the watchdog's start; the error of the loop is the second value
410/// of the result.
411fn trace(
412    launch: Launch<'_>,
413    cancel: &Cancellation,
414    live: &LiveProcesses,
415    patience: Duration,
416    root: &OnceLock<OwnedFd>,
417) -> Result<Traced, TraceError> {
418    let request = launch.request;
419    let started = spawn::start(
420        request,
421        launch.program,
422        launch.filter,
423        launch.stdio.as_ref(),
424        launch.report,
425    )?;
426    drop(launch.stdio);
427    let (pid, handle) = match started {
428        Started::Running(pid, handle) => (pid, handle),
429        Started::Exited(pid) => return Ok((pid, Ok(None))),
430    };
431    // Only this call sets the cell, once per run, so it cannot be set already.
432    drop(root.set(handle));
433    let escalation = Escalation::new()
434        .map_err(|error| tracer_error("could not prepare the tracing thread to be woken", error))?;
435    // The first process is live before the watchdog starts, so an interrupt for a
436    // request that is already cancelled reaches it.
437    follow::track_root(live, pid)
438        .map_err(|error| tracer_error("could not follow the traced program", error))?;
439    let (done_sender, done) = mpsc::channel::<()>();
440    let escalation = &escalation;
441    thread::scope(|scope| {
442        let watchdog = kizz_threads::spawn_scoped(
443            scope,
444            "kizz-watchdog",
445            "the thread that watches for cancellation",
446            move || watch(live, cancel, escalation, &done, patience),
447        )
448        .map_err(|error| not_started(&error))?;
449        let followed = follow::follow(pid, live, escalation, request.tree.then_some(request));
450        drop(done_sender);
451        // The watchdog only signals processes and wakes this thread; a live set
452        // that it could not lock is the run's error.
453        let watched = watchdog.join().unwrap_or(Ok(()));
454        Ok((pid, settle(followed, watched, escalation)))
455    })
456}
457
458/// Run the program of `launch` on a new thread, the tracing thread, while helper
459/// threads of the calling thread feed its input and capture its output, and collect
460/// its first process once the tracing thread has ended.
461///
462/// The feeder and the readers start first, before anything of the request runs.
463/// When one cannot start, the run returns [`TraceError::Tracer`], whose message
464/// names the thread and the system's error, and those that started end at once,
465/// because the child's ends of the pipes close with `launch`.
466///
467/// The tracing thread starts next, through `kizz_threads`; when it cannot start,
468/// nothing of the request has run, and the error names it. A new thread has no
469/// child until it starts the traced program, so no wait of a run collects, signals
470/// or adopts a child that the calling thread, or any other thread, started. It is
471/// the tracer of the whole tree, and when it ends, for an error, a panic or the end
472/// of the tree, Linux kills whatever is left of the tree (`PTRACE_O_EXITKILL`); the
473/// readers then see their pipes end, and the feeder its pipe close. The first
474/// process, a child of this process whose thread has ended, is then collected
475/// through its descriptor, unless the loop already collected it. No step of that
476/// reads `/proc`, needs the live set, or signals a process or thread ID.
477///
478/// The watchdog waits at most `patience` for `live`, the live set of the tree.
479fn supervise(
480    launch: Launch<'_>,
481    tracer_stdio: TracerStdio,
482    echo: Option<&dyn EchoSink>,
483    cancel: &Cancellation,
484    live: &LiveProcesses,
485    patience: Duration,
486) -> Result<Supervised, TraceError> {
487    let request = launch.request;
488    let root = OnceLock::new();
489    let root = &root;
490    thread::scope(|scope| {
491        let feeder = tracer_stdio
492            .stdin
493            .map(|stdin| {
494                let content = request.stdin.as_deref().unwrap_or_default();
495                kizz_threads::spawn_scoped(
496                    scope,
497                    "kizz-feeder",
498                    "the thread that feeds stdin",
499                    move || capture::feed(stdin, content),
500                )
501            })
502            .transpose()
503            .map_err(|error| not_started(&error))?;
504        let readers = tracer_stdio
505            .outputs
506            .into_iter()
507            .map(|(stream, pipe)| {
508                let (name, what) = reader_thread(stream);
509                kizz_threads::spawn_scoped(scope, name, what, move || {
510                    capture::collect(pipe, stream, echo)
511                })
512                .map(|reader| (stream, reader))
513            })
514            .collect::<Result<Vec<_>, _>>()
515            .map_err(|error| not_started(&error))?;
516        let tracing_thread =
517            kizz_threads::spawn_scoped(scope, "kizz-tracer", "the tracing thread", move || {
518                trace(launch, cancel, live, patience, root)
519            })
520            .map_err(|error| not_started(&error))?;
521        let traced = tracing_thread.join().unwrap_or_else(|_| {
522            Err(TraceError::Tracer {
523                message: "the tracing thread panicked".to_owned(),
524                source: None,
525            })
526        });
527        // The tracing thread has ended, and with it whatever was left of the tree.
528        let reaped = root.get().map_or(Ok(()), sys::reap).map_err(|error| {
529            tracer_error(
530                "could not collect the first process of the traced program",
531                error,
532            )
533        });
534        let streams = readers
535            .into_iter()
536            .map(|(stream, reader)| {
537                join(reader, "that captures output").map(|bytes| (stream, bytes))
538            })
539            .collect();
540        let fed = feeder.map_or(Ok(()), |feeder| join(feeder, "that feeds stdin"));
541        let (pid, followed) = traced?;
542        reaped?;
543        Ok(Supervised {
544            pid,
545            followed,
546            streams,
547            fed,
548        })
549    })
550}
551
552impl Tracer for LinuxTracer {
553    fn run(
554        &self,
555        request: &RunRequest,
556        echo: &dyn EchoSink,
557        cancel: &Cancellation,
558    ) -> Result<RunResult, TraceError> {
559        let program = Program::prepare(request).map_err(|error| {
560            TraceError::StartFailed {
561                program: request.program.clone(),
562                source: io::Error::new(io::ErrorKind::InvalidInput, error),
563                accesses: Accesses::new(),
564                tree: request
565                    .tree
566                    .then(|| processes::failed_start(None, request, None)),
567            }
568        })?;
569        let filter = filter::program().map_err(|error| {
570            tracer_error(
571                "could not build the seccomp-bpf filter",
572                io::Error::new(io::ErrorKind::InvalidData, error),
573            )
574        })?;
575        let (child_stdio, tracer_stdio) = capture::pipes(request)
576            .map_err(|error| tracer_error("could not create the standard streams", error))?;
577        let (report_read, report_write) = sys::pipe()
578            .map_err(|error| tracer_error("could not create the failure pipe", error))?;
579        let live = LiveProcesses::default();
580        let launch = Launch {
581            request,
582            program: &program,
583            filter: &filter,
584            stdio: child_stdio,
585            report: report_write,
586        };
587        let supervised = supervise(
588            launch,
589            tracer_stdio,
590            request.echo.then_some(echo),
591            cancel,
592            &live,
593            kizz_threads::LOCK_PATIENCE,
594        )?;
595        let pid = supervised.pid;
596        let outcome = supervised
597            .followed
598            .map_err(|error| tracer_error("could not follow the traced processes", error))?
599            .unwrap_or_else(|| {
600                follow::Outcome {
601                    termination: None,
602                    accesses: Accesses::new(),
603                    incomplete: None,
604                    first_reads: FirstReads::new(),
605                    unknown_system_calls: BTreeSet::new(),
606                    connections: BTreeSet::new(),
607                    tree: None,
608                }
609            });
610        let streams = supervised.streams?;
611        supervised.fed?;
612        if let Some(failure) = spawn::read_failure(report_read)
613            .map_err(|error| tracer_error("could not read the failure pipe", error))?
614        {
615            let tree = request
616                .tree
617                .then(|| processes::failed_start(outcome.tree, request, Some(pid)));
618            return Err(failure.into_error(request, outcome.accesses, tree));
619        }
620        let Some(termination) = outcome.termination else {
621            return Err(TraceError::Tracer {
622                message: "the traced program ended without an exit status".to_owned(),
623                source: None,
624            });
625        };
626        Ok(RunResult {
627            termination,
628            output: capture::assemble(request.capture, streams),
629            accesses: outcome.accesses,
630            incomplete: outcome.incomplete,
631            first_reads: outcome.first_reads,
632            unknown_system_calls: outcome.unknown_system_calls,
633            connections: outcome.connections,
634            tree: outcome.tree,
635        })
636    }
637
638    fn run_untraced(
639        &self,
640        request: &RunRequest,
641        echo: &dyn EchoSink,
642        cancel: &Cancellation,
643    ) -> Result<RunResult, TraceError> {
644        untraced::run(request, echo, cancel)
645    }
646
647    fn extended_attributes(
648        &self,
649        path: &Path,
650        follow: bool,
651    ) -> io::Result<ExtendedAttributes> {
652        sys::extended_attributes(path, follow)
653    }
654
655    fn machine_state(
656        &self,
657        cwd: &Path,
658    ) -> MachineState {
659        sys::machine_state(cwd)
660    }
661
662    fn error_name(
663        &self,
664        errno: i32,
665    ) -> String {
666        errors::name(i64::from(errno))
667    }
668}