Skip to main content

kizz_core/
execute.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! Running one command for `kizz execute` ("Observing any command with
6//! `kizz execute`"), through the tracer interface and without the cache.
7//!
8//! [`execute`] takes the command's arguments, the caller's whole environment and
9//! working directory ([`ExecuteRequest`]), and the handle through which the caller
10//! forwards signals. It looks the program up with the lookup of `run()`
11//! ([`search_program`]), through the caller's `PATH`, and names the outcome of each
12//! checked location through the tracer's error-name query. When it finds a program,
13//! it runs it through the tracer with the caller's environment and working
14//! directory unchanged, keeping the terminal and asking for the process tree. It
15//! returns how the command ended ([`CommandOutcome`]), the exit status of
16//! `kizz execute` ([`exit_status`]), and the observation [`Report`] of the one
17//! command, in which the lookup's probes are observations of the command's first
18//! program. It never opens the store.
19//!
20//! The outcomes and their statuses:
21//!
22//! * the program exited with a code: `exited`, with that code;
23//! * a signal killed it: `signaled`, with 128 plus the signal's number;
24//! * the lookup found no location, or a name without `/` met an environment without
25//!   `PATH`, or the tracer reported the program missing: `not_found`, with
26//!   [`STATUS_NOT_FOUND`];
27//! * the lookup found only a location that cannot be run, or the tracer reported the
28//!   program not executable: `not_executable`, with [`STATUS_NOT_EXECUTABLE`];
29//! * the tracer could not start the program for another reason: `start_failed`, with
30//!   [`STATUS_NOT_EXECUTABLE`] too, since the program was found but could not be invoked;
31//! * the tracer failed: `failed`, with [`STATUS_FAILED`], and the report says that the
32//!   trace is incomplete and names the failure.
33//!
34//! When the lookup fails, no process starts, and the report's command holds one
35//! placeholder process whose program is the name that kizz looked up, with every
36//! location that the lookup checked.
37//!
38//! The report never claims a complete trace that the tracer reported otherwise: a
39//! reason that the trace is incomplete, an unknown system call or a connection that
40//! the run reports but that no program of its tree lists is put on the first
41//! program of the command's first process, and a tracer that gives no tree gets the
42//! tree of one process with everything the run reports.
43//!
44//! [`not_executed`] gives the outcome, status and report of a command that kizz
45//! could not run because it failed itself before the start, such as when it could
46//! not set up the handling of signals.
47
48use std::{
49    collections::{BTreeMap, BTreeSet},
50    ffi::{OsStr, OsString},
51};
52
53use kizz_trace::{
54    AbsolutePath, Cancellation, CaptureMode, Connection, Observations, Process, ProcessTree,
55    Program, RunRequest, RunResult, StdioEcho, Termination, Tracer,
56};
57
58use crate::{
59    lookup::{PATH_VARIABLE, ProgramSearch, search_program},
60    report::{CommandInput, CommandOutcome, Execution, Report},
61};
62
63/// The exit status when kizz itself fails after it accepted the command line: the
64/// tracer failed, or the report could not be written.
65pub const STATUS_FAILED: u8 = 125;
66
67/// The exit status when the program is found but cannot be run or started.
68pub const STATUS_NOT_EXECUTABLE: u8 = 126;
69
70/// The exit status when the program is not found.
71pub const STATUS_NOT_FOUND: u8 = 127;
72
73/// The base of the exit status of a program that a signal killed: 128 plus the
74/// signal's number.
75const SIGNALED_BASE: u8 = 128;
76
77/// The command that `kizz execute` runs, as its caller gives it.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct ExecuteRequest {
80    /// The program, as given, and its arguments: the argument vector that the
81    /// program receives.
82    pub args: Vec<OsString>,
83    /// The caller's whole environment, which the program gets unchanged.
84    pub env: BTreeMap<OsString, OsString>,
85    /// The caller's working directory, which is the program's.
86    pub cwd: AbsolutePath,
87}
88
89/// What a run of `kizz execute` gave.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Executed {
92    /// How the command ended, or why it did not run.
93    pub outcome: CommandOutcome,
94    /// The exit status of `kizz execute`, as [`exit_status`] gives it.
95    pub status: u8,
96    /// The observation report of the one command.
97    pub report: Report,
98}
99
100/// The exit status of `kizz execute` for a command whose outcome is `outcome`: the
101/// program's exit code, its low eight bits as the system reports them; 128 plus
102/// the number of the signal that killed it; [`STATUS_NOT_FOUND`] when the program
103/// is not found; [`STATUS_NOT_EXECUTABLE`] when it is found but cannot be run or
104/// started; and [`STATUS_FAILED`] when the tracer failed. A signal number that
105/// does not fit gives 255.
106#[must_use]
107pub fn exit_status(outcome: &CommandOutcome) -> u8 {
108    match outcome {
109        CommandOutcome::Exited(code) => u8::try_from(code & 0xFF).unwrap_or(u8::MAX),
110        CommandOutcome::Signaled(signal) => {
111            u8::try_from(*signal)
112                .ok()
113                .and_then(|signal| SIGNALED_BASE.checked_add(signal))
114                .unwrap_or(u8::MAX)
115        },
116        CommandOutcome::NotFound(_) => STATUS_NOT_FOUND,
117        CommandOutcome::NotExecutable(_) | CommandOutcome::StartFailed(_) => STATUS_NOT_EXECUTABLE,
118        CommandOutcome::Failed(_) => STATUS_FAILED,
119    }
120}
121
122/// Run the command of `request` through `tracer`, keeping the terminal and with
123/// the process tree, while `cancel` carries the signals that the caller forwards;
124/// return its outcome, the exit status and the report, as the module's
125/// documentation says.
126pub fn execute(
127    tracer: &dyn Tracer,
128    request: ExecuteRequest,
129    cancel: &Cancellation,
130) -> Executed {
131    let ExecuteRequest { args, env, cwd } = request;
132    let Some(name) = args.first().cloned() else {
133        return finish(
134            args,
135            None,
136            cwd,
137            CommandOutcome::NotFound("no program was given".to_owned()),
138            None,
139            Observations::new(),
140        );
141    };
142    let shown = name.to_string_lossy().into_owned();
143    let search = env.get(OsStr::new(PATH_VARIABLE)).map(OsString::as_os_str);
144    let Some(found) = search_program(&name, search, &cwd, |errno| tracer.error_name(errno)) else {
145        let message = format!(
146            "program `{shown}` was not found: a program name without `/` is looked up in PATH, \
147             and PATH is not set"
148        );
149        return finish(
150            args,
151            None,
152            cwd,
153            CommandOutcome::NotFound(message),
154            None,
155            Observations::new(),
156        );
157    };
158    match found {
159        ProgramSearch::NotFound { checked } => {
160            let message = format!("program `{shown}` was not found in PATH");
161            finish(
162                args,
163                None,
164                cwd,
165                CommandOutcome::NotFound(message),
166                None,
167                checked,
168            )
169        },
170        ProgramSearch::NotExecutable { candidate, checked } => {
171            let message = format!("program `{shown}` is not executable: {candidate}");
172            finish(
173                args,
174                Some(candidate),
175                cwd,
176                CommandOutcome::NotExecutable(message),
177                None,
178                checked,
179            )
180        },
181        ProgramSearch::Found { program, checked } => {
182            let run = RunRequest {
183                program: program.clone(),
184                args: args.clone(),
185                env,
186                cwd: cwd.clone(),
187                stdin: None,
188                capture: CaptureMode::Split,
189                echo: false,
190                tree: true,
191                terminal: true,
192            };
193            let (outcome, tree) = match tracer.run(&run, &StdioEcho, cancel) {
194                Ok(result) => {
195                    (
196                        CommandOutcome::from_termination(result.termination),
197                        Some(run_tree(&run, &result)),
198                    )
199                },
200                Err(error) => (CommandOutcome::from_error(&error), error.tree().cloned()),
201            };
202            finish(args, Some(program), cwd, outcome, tree, checked)
203        },
204    }
205}
206
207/// The outcome, status and report of the command of `request`, which kizz did not
208/// run because it failed itself before the start, as `message` says: `failed`,
209/// with [`STATUS_FAILED`], and a report whose command holds the placeholder
210/// process and says that the trace is incomplete.
211#[must_use]
212pub fn not_executed(
213    request: ExecuteRequest,
214    message: String,
215) -> Executed {
216    finish(
217        request.args,
218        None,
219        request.cwd,
220        CommandOutcome::Failed(message),
221        None,
222        Observations::new(),
223    )
224}
225
226/// The outcome, status and report of the command `argv`, whose program is
227/// `program`, run in `cwd`, which ended as `outcome` says, with the tracer's
228/// `tree` and the lookup's observations `lookup`.
229fn finish(
230    argv: Vec<OsString>,
231    program: Option<AbsolutePath>,
232    cwd: AbsolutePath,
233    outcome: CommandOutcome,
234    tree: Option<ProcessTree>,
235    lookup: Observations,
236) -> Executed {
237    let status = exit_status(&outcome);
238    let report = Report::new(
239        vec![CommandInput {
240            argv,
241            program,
242            cwd,
243            execution: Execution::Ran {
244                outcome: outcome.clone(),
245                tree,
246                lookup,
247            },
248        }],
249        None,
250    );
251    Executed {
252        outcome,
253        status,
254        report,
255    }
256}
257
258/// The process tree of `result`, the run of `request`, with everything that the run
259/// reports: the tracer's tree, or the tree of one process when the tracer gave none,
260/// and on the first program of its first process the run's reason that the trace is
261/// incomplete, its unknown system calls and its connections that no program of the
262/// tree lists. The engine builds the trees of the report of `kizz run --output`
263/// with it too.
264pub(crate) fn run_tree(
265    request: &RunRequest,
266    result: &RunResult,
267) -> ProcessTree {
268    let mut tree = result.tree.clone().unwrap_or_else(|| {
269        ProcessTree::of_request(request, &result.accesses, Some(result.termination))
270    });
271    let unknown: BTreeSet<u32> = result
272        .unknown_system_calls
273        .difference(&tree.unknown_system_calls())
274        .copied()
275        .collect();
276    let connections: BTreeSet<Connection> = result
277        .connections
278        .difference(&tree.connections())
279        .cloned()
280        .collect();
281    let reason = result
282        .incomplete
283        .as_ref()
284        .filter(|reason| {
285            !tree
286                .programs()
287                .any(|(_, program)| program.incomplete.contains(reason))
288        })
289        .cloned();
290    if unknown.is_empty() && connections.is_empty() && reason.is_none() {
291        return tree;
292    }
293    if let Some(first) = first_program(&mut tree, request, result.termination) {
294        first.unknown_system_calls.extend(unknown);
295        first.connections.extend(connections);
296        first.incomplete.extend(reason);
297    }
298    tree
299}
300
301/// The first program of the first process of `tree`, the run of `request` that
302/// ended as `termination` says, adding the process or the program first when the
303/// tree has none.
304fn first_program<'a>(
305    tree: &'a mut ProcessTree,
306    request: &RunRequest,
307    termination: Termination,
308) -> Option<&'a mut Program> {
309    if tree.processes.is_empty() {
310        tree.processes.push(Process {
311            number: 1,
312            pid: None,
313            parent: None,
314            programs: Vec::new(),
315            status: Some(termination),
316        });
317    }
318    let process = tree
319        .processes
320        .iter_mut()
321        .min_by_key(|process| process.number)?;
322    if process.programs.is_empty() {
323        process.programs.push(Program::new(
324            request.program.clone(),
325            request.args.clone(),
326            false,
327        ));
328    }
329    process.programs.first_mut()
330}