Skip to main content

kizz_core/
report.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! Observation reports ("Observation reports"): what the commands of
6//! `kizz execute` or `kizz run` touched, organized by process, for people and for
7//! programs.
8//!
9//! A [`Report`] is built once from [`CommandInput`]s, in the order the commands
10//! ran, and an optional [`TaskProgramInput`]. Each command that ran brings the
11//! [`ProcessTree`] of the tracer, the [`CommandOutcome`] and the observations of
12//! its program lookup; a command that came from the cache brings only its outcome.
13//! The model then:
14//!
15//! * numbers the processes of every command from 1, across the commands, so a number is
16//!   unique in the report, and maps each parent to its new number;
17//! * puts the lookup's observations into the first program of the command's first
18//!   process, or, when kizz started no process, into a placeholder process without a
19//!   process ID or status, whose program is the name that kizz looked up;
20//! * lists every reason that a command was traced incompletely, with its process: each
21//!   reason of a program, each unknown system call, and a tracer failure;
22//! * combines every observation and connection of the report, the task program's
23//!   included, and counts the [`Totals`].
24//!
25//! Processes keep their start order, sorted by the tracer's numbers, programs
26//! their order, reasons are sorted, and observations and connections are sets, so
27//! the renderings do not depend on the order in which the model receives them.
28//!
29//! [`Report::render`] writes the report as text or JSON ([`ReportFormat`]), each
30//! hierarchical or compact ([`ReportMode`]), from the same model. [`JSON_FIELDS`]
31//! lists every field of the JSON format by its path, with the modes that hold it.
32//! Paths and arguments that are not valid UTF-8 appear with each invalid sequence
33//! replaced by U+FFFD, in both formats. Text then escapes each backslash and
34//! control character of every string that it shows ([`escape_text`]), so no string
35//! breaks its line and two different strings never read alike; JSON keeps its
36//! standard escaping.
37
38use std::{
39    collections::{BTreeMap, BTreeSet},
40    ffi::{OsStr, OsString},
41    path::{Path, PathBuf},
42};
43
44use kizz_trace::{
45    AbsolutePath, AccessKind, Connection, IncompleteReason, Observations, Outcome, ProcessTree,
46    Program, Termination, TraceError,
47};
48
49/// The name of the JSON format, its `format` field.
50pub const FORMAT: &str = "kizz-execute";
51
52/// The version of the JSON format, its `version` field.
53///
54/// A new field may appear without a new version; a field that changes its meaning
55/// or disappears raises it.
56pub const VERSION: u32 = 1;
57
58/// Whether a report is written for people or for programs.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum ReportFormat {
61    /// Readable text, the default.
62    Text,
63    /// JSON, indented by two spaces and ending with a newline (`--json`).
64    Json,
65}
66
67/// Whether a report keeps the process hierarchy or combines it.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum ReportMode {
70    /// Each command's processes, each with its programs and their observations, the
71    /// default.
72    Hierarchical,
73    /// Every observation and connection of the report, combined into one set
74    /// (`--compact`).
75    Compact,
76}
77
78impl ReportMode {
79    /// The mode as the report names it: `hierarchical` or `compact`.
80    #[must_use]
81    pub const fn name(self) -> &'static str {
82        match self {
83            Self::Hierarchical => "hierarchical",
84            Self::Compact => "compact",
85        }
86    }
87
88    /// The paths of the JSON fields of a report in this mode, in the order of
89    /// [`JSON_FIELDS`].
90    pub fn json_fields(self) -> impl Iterator<Item = &'static str> {
91        JSON_FIELDS
92            .iter()
93            .filter(move |field| field.is_in(self))
94            .map(|field| field.path)
95    }
96}
97
98/// One field of the JSON format, by its path, with the modes that hold it.
99///
100/// A path names the members from the top-level object, separated by `.`, with
101/// `[]` after the name of an array for its elements, such as
102/// `commands[].outcome.kind`.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub struct JsonField {
105    /// The path of the field.
106    pub path: &'static str,
107    /// Whether a hierarchical report holds the field.
108    pub hierarchical: bool,
109    /// Whether a compact report holds the field.
110    pub compact: bool,
111}
112
113impl JsonField {
114    /// A field of both modes.
115    const fn both(path: &'static str) -> Self {
116        Self {
117            path,
118            hierarchical: true,
119            compact: true,
120        }
121    }
122
123    /// A field of hierarchical reports only.
124    const fn hierarchical(path: &'static str) -> Self {
125        Self {
126            path,
127            hierarchical: true,
128            compact: false,
129        }
130    }
131
132    /// A field of compact reports only.
133    const fn compact(path: &'static str) -> Self {
134        Self {
135            path,
136            hierarchical: false,
137            compact: true,
138        }
139    }
140
141    /// Whether a report in `mode` holds the field.
142    #[must_use]
143    pub const fn is_in(
144        self,
145        mode: ReportMode,
146    ) -> bool {
147        match mode {
148            ReportMode::Hierarchical => self.hierarchical,
149            ReportMode::Compact => self.compact,
150        }
151    }
152}
153
154/// Every field of the JSON format, by its path, in the order the report writes
155/// the members of each object ("Observation report fields").
156///
157/// An object holds only some of its fields when its kind says so: an outcome has
158/// `code`, `signal` or `error`, a process's `exit` has `code` or `signal`, and a
159/// connection has `address`, `path` or `name`. Every other field is always
160/// present, `null` when it has no value.
161pub const JSON_FIELDS: &[JsonField] = &[
162    JsonField::both("format"),
163    JsonField::both("version"),
164    JsonField::both("mode"),
165    JsonField::both("complete"),
166    JsonField::both("totals"),
167    JsonField::both("totals.commands"),
168    JsonField::both("totals.cached"),
169    JsonField::both("totals.processes"),
170    JsonField::both("totals.programs"),
171    JsonField::both("totals.paths"),
172    JsonField::both("totals.connections"),
173    JsonField::both("totals.kinds"),
174    JsonField::both("totals.kinds.read"),
175    JsonField::both("totals.kinds.probe"),
176    JsonField::both("totals.kinds.list"),
177    JsonField::both("totals.kinds.write"),
178    JsonField::both("totals.kinds.exec"),
179    JsonField::both("totals.kinds.xattr"),
180    JsonField::both("commands"),
181    JsonField::both("commands[].argv"),
182    JsonField::both("commands[].program"),
183    JsonField::both("commands[].cwd"),
184    JsonField::both("commands[].cached"),
185    JsonField::both("commands[].outcome"),
186    JsonField::both("commands[].outcome.kind"),
187    JsonField::both("commands[].outcome.code"),
188    JsonField::both("commands[].outcome.signal"),
189    JsonField::both("commands[].outcome.error"),
190    JsonField::both("commands[].complete"),
191    JsonField::both("commands[].incomplete"),
192    JsonField::both("commands[].incomplete[].kind"),
193    JsonField::both("commands[].incomplete[].detail"),
194    JsonField::both("commands[].incomplete[].number"),
195    JsonField::hierarchical("commands[].incomplete[].process"),
196    JsonField::hierarchical("commands[].processes"),
197    JsonField::hierarchical("commands[].processes[].id"),
198    JsonField::hierarchical("commands[].processes[].pid"),
199    JsonField::hierarchical("commands[].processes[].parent"),
200    JsonField::hierarchical("commands[].processes[].exit"),
201    JsonField::hierarchical("commands[].processes[].exit.kind"),
202    JsonField::hierarchical("commands[].processes[].exit.code"),
203    JsonField::hierarchical("commands[].processes[].exit.signal"),
204    JsonField::hierarchical("commands[].processes[].programs"),
205    JsonField::hierarchical("commands[].processes[].programs[].path"),
206    JsonField::hierarchical("commands[].processes[].programs[].args"),
207    JsonField::hierarchical("commands[].processes[].programs[].inherited"),
208    JsonField::hierarchical("commands[].processes[].programs[].observations"),
209    JsonField::hierarchical("commands[].processes[].programs[].observations[].path"),
210    JsonField::hierarchical("commands[].processes[].programs[].observations[].access"),
211    JsonField::hierarchical("commands[].processes[].programs[].observations[].access.read"),
212    JsonField::hierarchical("commands[].processes[].programs[].observations[].access.probe"),
213    JsonField::hierarchical("commands[].processes[].programs[].observations[].access.list"),
214    JsonField::hierarchical("commands[].processes[].programs[].observations[].access.write"),
215    JsonField::hierarchical("commands[].processes[].programs[].observations[].access.exec"),
216    JsonField::hierarchical("commands[].processes[].programs[].observations[].access.xattr"),
217    JsonField::hierarchical("commands[].processes[].programs[].connections"),
218    JsonField::hierarchical("commands[].processes[].programs[].connections[].kind"),
219    JsonField::hierarchical("commands[].processes[].programs[].connections[].address"),
220    JsonField::hierarchical("commands[].processes[].programs[].connections[].path"),
221    JsonField::hierarchical("commands[].processes[].programs[].connections[].name"),
222    JsonField::both("task_program"),
223    JsonField::both("task_program.task"),
224    JsonField::hierarchical("task_program.observations"),
225    JsonField::hierarchical("task_program.observations[].path"),
226    JsonField::hierarchical("task_program.observations[].access"),
227    JsonField::hierarchical("task_program.observations[].access.read"),
228    JsonField::hierarchical("task_program.observations[].access.probe"),
229    JsonField::hierarchical("task_program.observations[].access.list"),
230    JsonField::hierarchical("task_program.observations[].access.write"),
231    JsonField::hierarchical("task_program.observations[].access.exec"),
232    JsonField::hierarchical("task_program.observations[].access.xattr"),
233    JsonField::compact("observations"),
234    JsonField::compact("observations[].path"),
235    JsonField::compact("observations[].access"),
236    JsonField::compact("observations[].access.read"),
237    JsonField::compact("observations[].access.probe"),
238    JsonField::compact("observations[].access.list"),
239    JsonField::compact("observations[].access.write"),
240    JsonField::compact("observations[].access.exec"),
241    JsonField::compact("observations[].access.xattr"),
242    JsonField::compact("connections"),
243    JsonField::compact("connections[].kind"),
244    JsonField::compact("connections[].address"),
245    JsonField::compact("connections[].path"),
246    JsonField::compact("connections[].name"),
247];
248
249/// How a command ended, or why it did not run.
250#[derive(Debug, Clone, PartialEq, Eq, Hash)]
251pub enum CommandOutcome {
252    /// The command exited with this exit code: `exited`, with `code`.
253    Exited(i32),
254    /// A signal with this number killed the command: `signaled`, with `signal`.
255    Signaled(i32),
256    /// The program was not found: `not_found`, with `error`.
257    NotFound(String),
258    /// The program was found but cannot be run: `not_executable`, with `error`.
259    NotExecutable(String),
260    /// The program could not be started for another reason: `start_failed`, with
261    /// `error`.
262    StartFailed(String),
263    /// Kizz or its tracer failed: `failed`, with `error`. The command's trace is
264    /// then incomplete, with a `tracer_failed` reason.
265    Failed(String),
266}
267
268impl CommandOutcome {
269    /// The outcome of a command that ended as `termination` says.
270    #[must_use]
271    pub const fn from_termination(termination: Termination) -> Self {
272        match termination {
273            Termination::Exited(code) => Self::Exited(code),
274            Termination::Signaled(signal) => Self::Signaled(signal),
275        }
276    }
277
278    /// The outcome of a request that failed with `error`, whose message it keeps.
279    #[must_use]
280    pub fn from_error(error: &TraceError) -> Self {
281        let message = error.to_string();
282        match error {
283            TraceError::ProgramNotFound { .. } => Self::NotFound(message),
284            TraceError::ProgramNotExecutable { .. } => Self::NotExecutable(message),
285            TraceError::StartFailed { .. } => Self::StartFailed(message),
286            TraceError::Tracer { .. } => Self::Failed(message),
287        }
288    }
289
290    /// The outcome's `kind`, as JSON names it, such as `not_found`.
291    #[must_use]
292    pub const fn kind(&self) -> &'static str {
293        match self {
294            Self::Exited(_) => "exited",
295            Self::Signaled(_) => "signaled",
296            Self::NotFound(_) => "not_found",
297            Self::NotExecutable(_) => "not_executable",
298            Self::StartFailed(_) => "start_failed",
299            Self::Failed(_) => "failed",
300        }
301    }
302
303    /// The outcome as text shows it, such as `exited with 0` or
304    /// `not found: MESSAGE`, with the message escaped as [`escape_text`] escapes
305    /// it.
306    #[must_use]
307    pub fn text(&self) -> String {
308        match self {
309            Self::Exited(code) => format!("exited with {code}"),
310            Self::Signaled(signal) => format!("signaled with {signal}"),
311            Self::NotFound(error) => format!("not found: {}", escape_text(error)),
312            Self::NotExecutable(error) => format!("not executable: {}", escape_text(error)),
313            Self::StartFailed(error) => format!("start failed: {}", escape_text(error)),
314            Self::Failed(error) => format!("failed: {}", escape_text(error)),
315        }
316    }
317}
318
319/// What happened to one command of a report.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum Execution {
322    /// The result came from the cache, so nothing was traced.
323    Cached {
324        /// How the cached run ended.
325        outcome: CommandOutcome,
326    },
327    /// The command ran, or kizz tried to run it.
328    Ran {
329        /// How it ended, or why it did not run.
330        outcome: CommandOutcome,
331        /// The tracer's process tree, or `None` when kizz started no process, as
332        /// when the lookup found no program or the tracer failed before the start.
333        tree: Option<ProcessTree>,
334        /// Every location that the program lookup checked, with its outcome.
335        lookup: Observations,
336    },
337}
338
339/// One command, as the report receives it.
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct CommandInput {
342    /// The arguments, starting with the program as given.
343    pub argv: Vec<OsString>,
344    /// The absolute path of the program, or `None` when the lookup found none.
345    pub program: Option<AbsolutePath>,
346    /// The working directory.
347    pub cwd: AbsolutePath,
348    /// What happened to the command.
349    pub execution: Execution,
350}
351
352/// The task program's own accesses, as the report of `kizz run` receives them.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct TaskProgramInput {
355    /// The task, as output names it.
356    pub task: String,
357    /// The paths that the task program touched, with their kinds and outcomes.
358    pub observations: Observations,
359}
360
361/// The kind of a reason that a command was traced incompletely, in the order
362/// the report sorts them.
363#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
364pub enum ReasonKind {
365    /// A system call through a non-native interface.
366    NonNativeSystemCall,
367    /// A system call that kizz cannot trace.
368    UntraceableSystemCall,
369    /// A system call that the tracer does not know.
370    UnknownSystemCall,
371    /// The tracer itself failed.
372    TracerFailed,
373    /// Any other reason that the tracer reported.
374    Other,
375}
376
377impl ReasonKind {
378    /// The kind as JSON names it, such as `unknown_system_call`.
379    #[must_use]
380    pub const fn name(self) -> &'static str {
381        match self {
382            Self::NonNativeSystemCall => "non_native_system_call",
383            Self::UntraceableSystemCall => "untraceable_system_call",
384            Self::UnknownSystemCall => "unknown_system_call",
385            Self::TracerFailed => "tracer_failed",
386            Self::Other => "other",
387        }
388    }
389
390    /// The kind as text shows it, such as `unknown system call`.
391    #[must_use]
392    pub const fn text(self) -> &'static str {
393        match self {
394            Self::NonNativeSystemCall => "non-native system call",
395            Self::UntraceableSystemCall => "untraceable system call",
396            Self::UnknownSystemCall => "unknown system call",
397            Self::TracerFailed => "tracer failed",
398            Self::Other => "other",
399        }
400    }
401}
402
403/// One reason that a command was traced incompletely.
404///
405/// Reasons sort by their process, then kind, number and detail.
406#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
407pub struct Reason {
408    /// The process that caused it, by its number in the report.
409    pub process: Option<u32>,
410    /// What kind of reason it is.
411    pub kind: ReasonKind,
412    /// The number of an unknown system call, and `None` for other kinds.
413    pub number: Option<u32>,
414    /// What the reason is about.
415    pub detail: String,
416}
417
418impl Reason {
419    /// The reason of `reason`, which the tracer reported for `process`.
420    fn of_tracer(
421        reason: IncompleteReason,
422        process: u32,
423    ) -> Self {
424        let (kind, detail) = match reason {
425            IncompleteReason::NonNativeSystemCall { detail } => {
426                (ReasonKind::NonNativeSystemCall, detail)
427            },
428            IncompleteReason::UntraceableSystemCall { detail } => {
429                (ReasonKind::UntraceableSystemCall, detail)
430            },
431            IncompleteReason::Other { detail } => (ReasonKind::Other, detail),
432        };
433        Self {
434            process: Some(process),
435            kind,
436            number: None,
437            detail,
438        }
439    }
440
441    /// The reason for the unknown system call `number` of `process`.
442    fn unknown(
443        number: u32,
444        process: u32,
445    ) -> Self {
446        Self {
447            process: Some(process),
448            kind: ReasonKind::UnknownSystemCall,
449            number: Some(number),
450            detail: format!("the tracer does not know system call {number}"),
451        }
452    }
453}
454
455/// One program of a process in the report.
456#[derive(Debug, Clone, PartialEq, Eq)]
457pub struct ReportProgram {
458    /// The path of the program, or for a placeholder process the name that kizz
459    /// looked up.
460    pub path: PathBuf,
461    /// The arguments that the program received, starting with its `argv[0]`.
462    pub args: Vec<OsString>,
463    /// Whether the process runs the program because its creator ran it.
464    pub inherited: bool,
465    /// The paths that the program touched, with their kinds and outcomes.
466    pub observations: Observations,
467    /// The connections that the program made.
468    pub connections: BTreeSet<Connection>,
469}
470
471impl ReportProgram {
472    /// The program named `path` with `args`, to which nothing is attributed.
473    fn named(
474        path: PathBuf,
475        args: Vec<OsString>,
476    ) -> Self {
477        Self {
478            path,
479            args,
480            inherited: false,
481            observations: Observations::new(),
482            connections: BTreeSet::new(),
483        }
484    }
485
486    /// The placeholder program of a command that started no process: the name
487    /// that kizz looked up, `argv[0]`, with the arguments.
488    fn looked_up(argv: &[OsString]) -> Self {
489        let name = argv.first().map_or_default(PathBuf::from);
490        Self::named(name, argv.to_vec())
491    }
492}
493
494/// One process of a command in the report.
495#[derive(Debug, Clone, PartialEq, Eq)]
496pub struct ReportProcess {
497    /// Its number, unique in the report, counting from 1 across every command.
498    pub id: u32,
499    /// Its process ID, or `None` when kizz started no process or none is known.
500    pub pid: Option<u32>,
501    /// The number of the process that created it, or `None`.
502    pub parent: Option<u32>,
503    /// How it ended, or `None` when the tracer did not see it end.
504    pub exit: Option<Termination>,
505    /// Its programs, in order.
506    pub programs: Vec<ReportProgram>,
507}
508
509/// One command of the report.
510#[derive(Debug, Clone, PartialEq, Eq)]
511pub struct ReportCommand {
512    /// The arguments, starting with the program as given.
513    pub argv: Vec<OsString>,
514    /// The absolute path of the program, or `None` when the lookup found none.
515    pub program: Option<AbsolutePath>,
516    /// The working directory.
517    pub cwd: AbsolutePath,
518    /// Whether the result came from the cache.
519    pub cached: bool,
520    /// How it ended, or why it did not run.
521    pub outcome: CommandOutcome,
522    /// Every reason that it was traced incompletely, sorted, each once.
523    pub incomplete: Vec<Reason>,
524    /// Its processes, in the order they started; none for a cached command.
525    pub processes: Vec<ReportProcess>,
526}
527
528impl ReportCommand {
529    /// Whether the command was traced completely, or `None` when it came from the
530    /// cache.
531    #[must_use]
532    pub const fn complete(&self) -> Option<bool> {
533        if self.cached {
534            None
535        } else {
536            Some(self.incomplete.is_empty())
537        }
538    }
539
540    /// The command of `input`, whose processes are numbered from `next_id`, which
541    /// moves past them.
542    fn build(
543        input: CommandInput,
544        next_id: &mut u32,
545    ) -> Self {
546        let CommandInput {
547            argv,
548            program,
549            cwd,
550            execution,
551        } = input;
552        let (outcome, tree, lookup) = match execution {
553            Execution::Cached { outcome } => {
554                return Self {
555                    argv,
556                    program,
557                    cwd,
558                    cached: true,
559                    outcome,
560                    incomplete: Vec::new(),
561                    processes: Vec::new(),
562                };
563            },
564            Execution::Ran {
565                outcome,
566                tree,
567                lookup,
568            } => (outcome, tree, lookup),
569        };
570        let (mut processes, mut incomplete) = renumber(tree.unwrap_or_default(), next_id);
571        if processes.is_empty() {
572            processes.push(ReportProcess {
573                id: take_id(next_id),
574                pid: None,
575                parent: None,
576                exit: None,
577                programs: Vec::new(),
578            });
579        }
580        let first_id = processes.first().map(|process| process.id);
581        if let Some(first) = processes.first_mut() {
582            if first.programs.is_empty() {
583                first.programs.push(ReportProgram::looked_up(&argv));
584            }
585            if let Some(program) = first.programs.first_mut() {
586                program.observations.merge(&lookup);
587            }
588        }
589        if let CommandOutcome::Failed(message) = &outcome {
590            incomplete.push(Reason {
591                process: first_id,
592                kind: ReasonKind::TracerFailed,
593                number: None,
594                detail: message.clone(),
595            });
596        }
597        incomplete.sort();
598        incomplete.dedup();
599        Self {
600            argv,
601            program,
602            cwd,
603            cached: false,
604            outcome,
605            incomplete,
606            processes,
607        }
608    }
609}
610
611/// The next process number of the report, moving `next_id` past it.
612fn take_id(next_id: &mut u32) -> u32 {
613    let id = *next_id;
614    *next_id = next_id.saturating_add(1);
615    id
616}
617
618/// The processes of `tree` in their start order, the order of the tracer's
619/// numbers, numbered from `next_id`, with their parents renumbered, and every
620/// reason that their programs made the trace incomplete.
621fn renumber(
622    tree: ProcessTree,
623    next_id: &mut u32,
624) -> (Vec<ReportProcess>, Vec<Reason>) {
625    let mut processes = tree.processes;
626    processes.sort_by_key(|process| process.number);
627    let mut ids = BTreeMap::new();
628    let numbered: Vec<_> = processes
629        .into_iter()
630        .map(|process| {
631            let id = take_id(next_id);
632            ids.entry(process.number).or_insert(id);
633            (id, process)
634        })
635        .collect();
636    let mut reasons = Vec::new();
637    let renumbered = numbered
638        .into_iter()
639        .map(|(id, process)| {
640            let programs = process
641                .programs
642                .into_iter()
643                .map(|program| report_program(program, id, &mut reasons))
644                .collect();
645            ReportProcess {
646                id,
647                pid: process.pid,
648                parent: process.parent.and_then(|parent| ids.get(&parent).copied()),
649                exit: process.status,
650                programs,
651            }
652        })
653        .collect();
654    (renumbered, reasons)
655}
656
657/// The report's program of `program`, which the process numbered `process` ran,
658/// adding each reason that it made the trace incomplete to `reasons`.
659fn report_program(
660    program: Program,
661    process: u32,
662    reasons: &mut Vec<Reason>,
663) -> ReportProgram {
664    let Program {
665        path,
666        args,
667        inherited,
668        observations,
669        connections,
670        unknown_system_calls,
671        incomplete,
672    } = program;
673    reasons.extend(
674        incomplete
675            .into_iter()
676            .map(|reason| Reason::of_tracer(reason, process)),
677    );
678    reasons.extend(
679        unknown_system_calls
680            .into_iter()
681            .map(|number| Reason::unknown(number, process)),
682    );
683    ReportProgram {
684        path: path.into_path_buf(),
685        args,
686        inherited,
687        observations,
688        connections,
689    }
690}
691
692/// The task program of a report.
693#[derive(Debug, Clone, PartialEq, Eq)]
694pub struct ReportTaskProgram {
695    /// The task, as output names it.
696    pub task: String,
697    /// The paths that the task program touched, with their kinds and outcomes.
698    pub observations: Observations,
699}
700
701/// The totals of a report.
702#[derive(Debug, Clone, PartialEq, Eq)]
703pub struct Totals {
704    /// The commands.
705    pub commands: usize,
706    /// The commands that came from the cache.
707    pub cached: usize,
708    /// The processes of every command, placeholder processes included.
709    pub processes: usize,
710    /// The programs of every process that are not inherited.
711    pub programs: usize,
712    /// The paths of the report, each once.
713    pub paths: usize,
714    /// The connections of the report, each once.
715    pub connections: usize,
716    /// The paths of each access kind, every kind listed.
717    pub kinds: BTreeMap<AccessKind, usize>,
718}
719
720impl Totals {
721    /// The totals of `commands`, whose combined observations and connections,
722    /// with the task program's, are `observations` and `connections`.
723    fn count(
724        commands: &[ReportCommand],
725        observations: &Observations,
726        connections: &BTreeSet<Connection>,
727    ) -> Self {
728        let mut totals = Self {
729            commands: commands.len(),
730            cached: 0,
731            processes: 0,
732            programs: 0,
733            paths: observations.len(),
734            connections: connections.len(),
735            kinds: AccessKind::ALL.iter().map(|kind| (*kind, 0)).collect(),
736        };
737        for command in commands {
738            if command.cached {
739                totals.cached = totals.cached.saturating_add(1);
740            }
741            for process in &command.processes {
742                totals.processes = totals.processes.saturating_add(1);
743                for program in &process.programs {
744                    if !program.inherited {
745                        totals.programs = totals.programs.saturating_add(1);
746                    }
747                }
748            }
749        }
750        for (_, kinds) in observations {
751            for kind in kinds.keys() {
752                let count = totals.kinds.entry(*kind).or_default();
753                *count = count.saturating_add(1);
754            }
755        }
756        totals
757    }
758
759    /// The number of paths of `kind`.
760    #[must_use]
761    pub fn kind(
762        &self,
763        kind: AccessKind,
764    ) -> usize {
765        self.kinds.get(&kind).copied().unwrap_or_default()
766    }
767}
768
769/// An observation report: its commands in the order they ran, the task program,
770/// every observation and connection combined, and the totals.
771#[derive(Debug, Clone, PartialEq, Eq)]
772pub struct Report {
773    /// The commands, in the order they ran.
774    pub commands: Vec<ReportCommand>,
775    /// The task program's own accesses, for `kizz run`.
776    pub task_program: Option<ReportTaskProgram>,
777    /// Every observation of every program of every command and of the task
778    /// program, combined.
779    pub observations: Observations,
780    /// Every connection of every program, combined.
781    pub connections: BTreeSet<Connection>,
782    /// The totals.
783    pub totals: Totals,
784}
785
786impl Report {
787    /// The report of `commands`, in the order they ran, and of the task program's
788    /// own accesses, if any.
789    #[must_use]
790    pub fn new(
791        commands: Vec<CommandInput>,
792        task_program: Option<TaskProgramInput>,
793    ) -> Self {
794        let mut next_id = 1;
795        let commands: Vec<ReportCommand> = commands
796            .into_iter()
797            .map(|command| ReportCommand::build(command, &mut next_id))
798            .collect();
799        let task_program = task_program.map(|input| {
800            ReportTaskProgram {
801                task: input.task,
802                observations: input.observations,
803            }
804        });
805        let mut observations = Observations::new();
806        let mut connections = BTreeSet::new();
807        for command in &commands {
808            for process in &command.processes {
809                for program in &process.programs {
810                    observations.merge(&program.observations);
811                    connections.extend(program.connections.iter().cloned());
812                }
813            }
814        }
815        if let Some(task_program) = &task_program {
816            observations.merge(&task_program.observations);
817        }
818        let totals = Totals::count(&commands, &observations, &connections);
819        Self {
820            commands,
821            task_program,
822            observations,
823            connections,
824            totals,
825        }
826    }
827
828    /// Whether every command that ran was traced completely; cached commands do
829    /// not count.
830    #[must_use]
831    pub fn complete(&self) -> bool {
832        self.commands
833            .iter()
834            .all(|command| command.complete() != Some(false))
835    }
836
837    /// The report in `format` and `mode`.
838    #[must_use]
839    pub fn render(
840        &self,
841        format: ReportFormat,
842        mode: ReportMode,
843    ) -> String {
844        match format {
845            ReportFormat::Text => self.text(mode),
846            ReportFormat::Json => self.json(mode),
847        }
848    }
849
850    /// The report as text, in `mode`: a header with the completeness and the
851    /// totals, each command with its processes in a hierarchical report, the task
852    /// program, and in a compact report every observation and connection once.
853    #[must_use]
854    pub fn text(
855        &self,
856        mode: ReportMode,
857    ) -> String {
858        let mut blocks = vec![self.text_header(mode)];
859        for (index, command) in self.commands.iter().enumerate() {
860            blocks.push(text_command(index.saturating_add(1), command, mode));
861        }
862        if let Some(task_program) = &self.task_program {
863            let mut block = format!("task program: {}\n", escape_text(&task_program.task));
864            if mode == ReportMode::Hierarchical {
865                text_groups(&mut block, &task_program.observations, None, 1);
866            }
867            blocks.push(block);
868        }
869        if mode == ReportMode::Compact {
870            let mut block = String::new();
871            text_groups(&mut block, &self.observations, Some(&self.connections), 0);
872            if !block.is_empty() {
873                blocks.push(block);
874            }
875        }
876        blocks.join("\n")
877    }
878
879    /// The header of the text report.
880    fn text_header(
881        &self,
882        mode: ReportMode,
883    ) -> String {
884        let totals = &self.totals;
885        let kinds: Vec<String> = AccessKind::ALL
886            .iter()
887            .map(|kind| format!("{} {}", kind.name(), totals.kind(*kind)))
888            .collect();
889        format!(
890            "kizz observation report, version {VERSION}, {}\ntrace: {}\ntotals: commands {}, cached \
891             {}, processes {}, programs {}, paths {}, connections {}\npaths by access: {}\n",
892            mode.name(),
893            if self.complete() {
894                "complete"
895            } else {
896                "incomplete"
897            },
898            totals.commands,
899            totals.cached,
900            totals.processes,
901            totals.programs,
902            totals.paths,
903            totals.connections,
904            kinds.join(", ")
905        )
906    }
907
908    /// The report as JSON, in `mode`, indented by two spaces and ending with a
909    /// newline.
910    #[must_use]
911    pub fn json(
912        &self,
913        mode: ReportMode,
914    ) -> String {
915        let totals = &self.totals;
916        let kinds = AccessKind::ALL
917            .iter()
918            .map(|kind| (kind.name(), Json::count(totals.kind(*kind))))
919            .collect();
920        let mut members = vec![
921            ("format", Json::text(FORMAT)),
922            ("version", Json::Number(VERSION.to_string())),
923            ("mode", Json::text(mode.name())),
924            ("complete", Json::Bool(self.complete())),
925            (
926                "totals",
927                Json::Object(vec![
928                    ("commands", Json::count(totals.commands)),
929                    ("cached", Json::count(totals.cached)),
930                    ("processes", Json::count(totals.processes)),
931                    ("programs", Json::count(totals.programs)),
932                    ("paths", Json::count(totals.paths)),
933                    ("connections", Json::count(totals.connections)),
934                    ("kinds", Json::Object(kinds)),
935                ]),
936            ),
937            (
938                "commands",
939                Json::Array(
940                    self.commands
941                        .iter()
942                        .map(|command| json_command(command, mode))
943                        .collect(),
944                ),
945            ),
946            (
947                "task_program",
948                self.task_program
949                    .as_ref()
950                    .map_or(Json::Null, |task_program| {
951                        let mut members = vec![("task", Json::text(&task_program.task))];
952                        if mode == ReportMode::Hierarchical {
953                            members.push((
954                                "observations",
955                                json_observations(&task_program.observations),
956                            ));
957                        }
958                        Json::Object(members)
959                    }),
960            ),
961        ];
962        if mode == ReportMode::Compact {
963            members.push(("observations", json_observations(&self.observations)));
964            members.push(("connections", json_connections(&self.connections)));
965        }
966        let mut text = String::new();
967        Json::Object(members).write(&mut text, 0);
968        text.push('\n');
969        text
970    }
971}
972
973/// `text` as it appears in a report: each sequence that is not valid UTF-8
974/// replaced by U+FFFD.
975fn lossy(text: &OsStr) -> String {
976    text.to_string_lossy().into_owned()
977}
978
979/// `path` as it appears in a report, as [`lossy`] makes it.
980fn lossy_path(path: &Path) -> String {
981    lossy(path.as_os_str())
982}
983
984/// `text` as a text report shows it: a backslash as `\\`, a newline as `\n`, a tab
985/// as `\t`, a carriage return as `\r`, every other control character, U+0000
986/// through U+001F and U+007F through U+009F, and the separators U+2028 and U+2029
987/// as `\u{`, the code in lowercase hexadecimal without leading zeros, and `}`, as
988/// [`char::escape_unicode`] writes it, and every other character as it is.
989///
990/// So no string breaks its line, and since the backslash is escaped too, each
991/// escape reads one way and two different strings never give the same text.
992#[must_use]
993pub fn escape_text(text: &str) -> String {
994    let mut escaped = String::with_capacity(text.len());
995    for character in text.chars() {
996        match character {
997            '\\' => escaped.push_str("\\\\"),
998            '\n' => escaped.push_str("\\n"),
999            '\t' => escaped.push_str("\\t"),
1000            '\r' => escaped.push_str("\\r"),
1001            other if other.is_control() || matches!(other, '\u{2028}' | '\u{2029}') => {
1002                escaped.extend(other.escape_unicode());
1003            },
1004            other => escaped.push(other),
1005        }
1006    }
1007    escaped
1008}
1009
1010/// `path` as a text report shows it: as [`lossy`] makes it, then escaped as
1011/// [`escape_text`] escapes it.
1012fn text_path(path: &Path) -> String {
1013    escape_text(&lossy_path(path))
1014}
1015
1016/// Whether `word` reads the same to a POSIX shell without quotes: it is not empty
1017/// and holds only letters, digits and `-_./=:,+@%^`.
1018fn is_plain_word(word: &str) -> bool {
1019    !word.is_empty()
1020        && word
1021            .chars()
1022            .all(|character| character.is_ascii_alphanumeric() || "-_./=:,+@%^".contains(character))
1023}
1024
1025/// `args` as text shows them: separated by spaces, each escaped as
1026/// [`escape_text`] escapes it, then quoted for a POSIX shell when it is empty or
1027/// holds another character than [`is_plain_word`] allows, so an argument with an
1028/// escape is always quoted.
1029fn shell_words(args: &[OsString]) -> String {
1030    let words: Vec<String> = args
1031        .iter()
1032        .map(|arg| {
1033            let word = escape_text(&lossy(arg));
1034            if is_plain_word(&word) {
1035                word
1036            } else {
1037                format!("'{}'", word.replace('\'', "'\\''"))
1038            }
1039        })
1040        .collect();
1041    words.join(" ")
1042}
1043
1044/// `head`, followed by `: ` and the arguments when there are any.
1045fn with_args(
1046    head: String,
1047    args: &[OsString],
1048) -> String {
1049    if args.is_empty() {
1050        head
1051    } else {
1052        format!("{head}: {}", shell_words(args))
1053    }
1054}
1055
1056/// Append `depth` levels of two-space indentation to `text`.
1057fn indent(
1058    text: &mut String,
1059    depth: usize,
1060) {
1061    for _ in 0..depth {
1062        text.push_str("  ");
1063    }
1064}
1065
1066/// Append `content`, indented `depth` levels, and a newline to `text`.
1067fn line(
1068    text: &mut String,
1069    depth: usize,
1070    content: &str,
1071) {
1072    indent(text, depth);
1073    text.push_str(content);
1074    text.push('\n');
1075}
1076
1077/// `outcomes`, separated by `, `, in their order, each escaped as [`escape_text`]
1078/// escapes it.
1079fn outcome_list<'a>(outcomes: impl Iterator<Item = &'a Outcome>) -> String {
1080    let outcomes: Vec<String> = outcomes
1081        .map(|outcome| escape_text(&outcome.to_string()))
1082        .collect();
1083    outcomes.join(", ")
1084}
1085
1086/// A connection as text shows it: `ip ADDRESS`, `unix PATH` or `abstract NAME`,
1087/// with the path and the name as [`lossy`] makes them, escaped as [`escape_text`]
1088/// escapes them.
1089fn connection_text(connection: &Connection) -> String {
1090    match connection {
1091        Connection::Ip(address) => format!("ip {address}"),
1092        Connection::UnixPath(path) => format!("unix {}", text_path(path.as_path())),
1093        Connection::UnixAbstract(name) => {
1094            format!("abstract {}", escape_text(&String::from_utf8_lossy(name)))
1095        },
1096    }
1097}
1098
1099/// Append to `text`, at `depth`, each access kind of `observations` that has
1100/// paths, with its paths as `PATH: OUTCOMES`, then the `connections` group when
1101/// `connections` has any.
1102fn text_groups(
1103    text: &mut String,
1104    observations: &Observations,
1105    connections: Option<&BTreeSet<Connection>>,
1106    depth: usize,
1107) {
1108    let inner = depth.saturating_add(1);
1109    for kind in AccessKind::ALL {
1110        let paths: Vec<_> = observations
1111            .iter()
1112            .filter_map(|(path, kinds)| kinds.get(&kind).map(|outcomes| (path, outcomes)))
1113            .collect();
1114        if paths.is_empty() {
1115            continue;
1116        }
1117        line(text, depth, &format!("{}:", kind.name()));
1118        for (path, outcomes) in paths {
1119            line(
1120                text,
1121                inner,
1122                &format!(
1123                    "{}: {}",
1124                    text_path(path.as_path()),
1125                    outcome_list(outcomes.iter())
1126                ),
1127            );
1128        }
1129    }
1130    if let Some(connections) = connections.filter(|connections| !connections.is_empty()) {
1131        line(text, depth, "connections:");
1132        for connection in connections {
1133            line(text, inner, &connection_text(connection));
1134        }
1135    }
1136}
1137
1138/// How a process ended, as text shows it: `exited with C` or `signaled with S`.
1139fn exit_text(exit: Termination) -> String {
1140    match exit {
1141        Termination::Exited(code) => format!("exited with {code}"),
1142        Termination::Signaled(signal) => format!("signaled with {signal}"),
1143    }
1144}
1145
1146/// The line of `process`: `process N`, then `pid P` or `no pid`, `child of
1147/// process M` when it has a parent, and how it ended; a process without a process
1148/// ID or status is `not started`.
1149fn process_line(process: &ReportProcess) -> String {
1150    if process.pid.is_none() && process.exit.is_none() {
1151        return format!("process {}, not started", process.id);
1152    }
1153    let mut parts = vec![format!("process {}", process.id)];
1154    parts.push(
1155        process
1156            .pid
1157            .map_or_else(|| "no pid".to_owned(), |pid| format!("pid {pid}")),
1158    );
1159    if let Some(parent) = process.parent {
1160        parts.push(format!("child of process {parent}"));
1161    }
1162    parts.push(
1163        process
1164            .exit
1165            .map_or_else(|| "end not seen".to_owned(), exit_text),
1166    );
1167    parts.join(", ")
1168}
1169
1170/// The line of `reason`, with its process in a hierarchical report.
1171fn reason_line(
1172    reason: &Reason,
1173    mode: ReportMode,
1174) -> String {
1175    match (mode, reason.process) {
1176        (ReportMode::Hierarchical, Some(process)) => {
1177            format!(
1178                "{}, process {process}: {}",
1179                reason.kind.text(),
1180                escape_text(&reason.detail)
1181            )
1182        },
1183        _ => format!("{}: {}", reason.kind.text(), escape_text(&reason.detail)),
1184    }
1185}
1186
1187/// The text block of the command numbered `number`.
1188fn text_command(
1189    number: usize,
1190    command: &ReportCommand,
1191    mode: ReportMode,
1192) -> String {
1193    let mut text = String::new();
1194    line(
1195        &mut text,
1196        0,
1197        &with_args(format!("command {number}"), &command.argv),
1198    );
1199    let program = command.program.as_ref().map_or_else(
1200        || "not found".to_owned(),
1201        |program| text_path(program.as_path()),
1202    );
1203    line(&mut text, 1, &format!("program: {program}"));
1204    line(
1205        &mut text,
1206        1,
1207        &format!("directory: {}", text_path(command.cwd.as_path())),
1208    );
1209    line(
1210        &mut text,
1211        1,
1212        &format!("outcome: {}", command.outcome.text()),
1213    );
1214    let trace = match command.complete() {
1215        None => "cached, not traced",
1216        Some(true) => "complete",
1217        Some(false) => "incomplete",
1218    };
1219    line(&mut text, 1, &format!("trace: {trace}"));
1220    for reason in &command.incomplete {
1221        line(&mut text, 2, &reason_line(reason, mode));
1222    }
1223    if mode == ReportMode::Hierarchical {
1224        text_processes(&mut text, &command.processes);
1225    }
1226    text
1227}
1228
1229/// Append the processes of one command to `text`, each nested under the process
1230/// that created it, in the order they started.
1231///
1232/// A process is nested under its parent only when the parent started before it,
1233/// so every process appears once, whatever the parents say.
1234fn text_processes(
1235    text: &mut String,
1236    processes: &[ReportProcess],
1237) {
1238    let positions: BTreeMap<u32, usize> = processes
1239        .iter()
1240        .enumerate()
1241        .rev()
1242        .map(|(position, process)| (process.id, position))
1243        .collect();
1244    let mut children: Vec<Vec<&ReportProcess>> = processes.iter().map(|_| Vec::new()).collect();
1245    let mut roots = Vec::new();
1246    for (position, process) in processes.iter().enumerate() {
1247        let parent = process
1248            .parent
1249            .and_then(|parent| positions.get(&parent).copied())
1250            .filter(|parent| *parent < position);
1251        match parent.and_then(|parent| children.get_mut(parent)) {
1252            Some(siblings) => siblings.push(process),
1253            None => roots.push(process),
1254        }
1255    }
1256    let mut stack: Vec<(&ReportProcess, usize)> = roots
1257        .into_iter()
1258        .rev()
1259        .map(|process| (process, 1))
1260        .collect();
1261    while let Some((process, depth)) = stack.pop() {
1262        line(text, depth, &process_line(process));
1263        let inner = depth.saturating_add(1);
1264        for program in &process.programs {
1265            let head = if program.inherited {
1266                format!("program {}, inherited", text_path(&program.path))
1267            } else {
1268                format!("program {}", text_path(&program.path))
1269            };
1270            line(text, inner, &with_args(head, &program.args));
1271            text_groups(
1272                text,
1273                &program.observations,
1274                Some(&program.connections),
1275                inner.saturating_add(1),
1276            );
1277        }
1278        let own = positions
1279            .get(&process.id)
1280            .and_then(|position| children.get(*position));
1281        for child in own.into_iter().flatten().rev() {
1282            stack.push((*child, inner));
1283        }
1284    }
1285}
1286
1287/// A JSON value of the report, whose objects keep their members in order.
1288#[derive(Debug, Clone, PartialEq, Eq)]
1289enum Json {
1290    /// `null`.
1291    Null,
1292    /// `true` or `false`.
1293    Bool(bool),
1294    /// A number, already written in decimal.
1295    Number(String),
1296    /// A string.
1297    String(String),
1298    /// An array.
1299    Array(Vec<Self>),
1300    /// An object, with its members in order.
1301    Object(Vec<(&'static str, Self)>),
1302}
1303
1304impl Json {
1305    /// The string `text`.
1306    fn text(text: &str) -> Self {
1307        Self::String(text.to_owned())
1308    }
1309
1310    /// The number `count`.
1311    fn count(count: usize) -> Self {
1312        Self::Number(count.to_string())
1313    }
1314
1315    /// `value` as a number, or `null` when it is `None`.
1316    fn optional<T: ToString>(value: Option<T>) -> Self {
1317        value.map_or(Self::Null, |value| Self::Number(value.to_string()))
1318    }
1319
1320    /// Append the value, nested `level` deep, to `text`: each element and member
1321    /// on a line of its own, indented by two spaces per level, with `": "` after
1322    /// each key, and empty arrays and objects as `[]` and `{}`.
1323    fn write(
1324        &self,
1325        text: &mut String,
1326        level: usize,
1327    ) {
1328        let inner = level.saturating_add(1);
1329        match self {
1330            Self::Null => text.push_str("null"),
1331            Self::Bool(value) => text.push_str(if *value { "true" } else { "false" }),
1332            Self::Number(number) => text.push_str(number),
1333            Self::String(value) => write_json_string(text, value),
1334            Self::Array(items) if items.is_empty() => text.push_str("[]"),
1335            Self::Object(members) if members.is_empty() => text.push_str("{}"),
1336            Self::Array(items) => {
1337                text.push('[');
1338                for (index, item) in items.iter().enumerate() {
1339                    text.push_str(if index == 0 { "\n" } else { ",\n" });
1340                    indent(text, inner);
1341                    item.write(text, inner);
1342                }
1343                text.push('\n');
1344                indent(text, level);
1345                text.push(']');
1346            },
1347            Self::Object(members) => {
1348                text.push('{');
1349                for (index, (key, member)) in members.iter().enumerate() {
1350                    text.push_str(if index == 0 { "\n" } else { ",\n" });
1351                    indent(text, inner);
1352                    write_json_string(text, key);
1353                    text.push_str(": ");
1354                    member.write(text, inner);
1355                }
1356                text.push('\n');
1357                indent(text, level);
1358                text.push('}');
1359            },
1360        }
1361    }
1362}
1363
1364/// Append `value` to `text` as a JSON string, escaped as `serde_json` escapes it:
1365/// `"` and `\` with a backslash, the control characters with a short escape where
1366/// JSON has one and `\u00XX` otherwise, and everything else as it is.
1367fn write_json_string(
1368    text: &mut String,
1369    value: &str,
1370) {
1371    text.push('"');
1372    for character in value.chars() {
1373        match character {
1374            '"' => text.push_str("\\\""),
1375            '\\' => text.push_str("\\\\"),
1376            '\n' => text.push_str("\\n"),
1377            '\r' => text.push_str("\\r"),
1378            '\t' => text.push_str("\\t"),
1379            '\u{08}' => text.push_str("\\b"),
1380            '\u{0c}' => text.push_str("\\f"),
1381            control if control < ' ' => {
1382                // Below U+0020, the code is `0x1N` or `0x0N`: its high digit is
1383                // the bit 0x10, and its low digit the bits 0x0F.
1384                let code = u32::from(control);
1385                text.push_str(if code & 0x10 == 0 { "\\u000" } else { "\\u001" });
1386                let low = usize::try_from(code & 0x0F).unwrap_or_default();
1387                text.push(char::from(
1388                    b"0123456789abcdef".get(low).copied().unwrap_or(b'0'),
1389                ));
1390            },
1391            other => text.push(other),
1392        }
1393    }
1394    text.push('"');
1395}
1396
1397/// The strings of `args`, as [`lossy`] makes them.
1398fn json_args(args: &[OsString]) -> Json {
1399    Json::Array(args.iter().map(|arg| Json::String(lossy(arg))).collect())
1400}
1401
1402/// The JSON of `outcome`: its `kind`, with `code`, `signal` or `error`.
1403fn json_outcome(outcome: &CommandOutcome) -> Json {
1404    let detail = match outcome {
1405        CommandOutcome::Exited(code) => ("code", Json::Number(code.to_string())),
1406        CommandOutcome::Signaled(signal) => ("signal", Json::Number(signal.to_string())),
1407        CommandOutcome::NotFound(error)
1408        | CommandOutcome::NotExecutable(error)
1409        | CommandOutcome::StartFailed(error)
1410        | CommandOutcome::Failed(error) => ("error", Json::text(error)),
1411    };
1412    Json::Object(vec![("kind", Json::text(outcome.kind())), detail])
1413}
1414
1415/// The JSON of how a process ended: `exited`, with `code`, or `signaled`, with
1416/// `signal`.
1417fn json_exit(exit: Termination) -> Json {
1418    match exit {
1419        Termination::Exited(code) => {
1420            Json::Object(vec![
1421                ("kind", Json::text("exited")),
1422                ("code", Json::Number(code.to_string())),
1423            ])
1424        },
1425        Termination::Signaled(signal) => {
1426            Json::Object(vec![
1427                ("kind", Json::text("signaled")),
1428                ("signal", Json::Number(signal.to_string())),
1429            ])
1430        },
1431    }
1432}
1433
1434/// The JSON of `reason`, with its process in a hierarchical report.
1435fn json_reason(
1436    reason: &Reason,
1437    mode: ReportMode,
1438) -> Json {
1439    let mut members = vec![
1440        ("kind", Json::text(reason.kind.name())),
1441        ("detail", Json::text(&reason.detail)),
1442        ("number", Json::optional(reason.number)),
1443    ];
1444    if mode == ReportMode::Hierarchical {
1445        members.push(("process", Json::optional(reason.process)));
1446    }
1447    Json::Object(members)
1448}
1449
1450/// The JSON of `observations`: each path with its `access` object, which maps each
1451/// access kind of the path to its outcomes.
1452fn json_observations(observations: &Observations) -> Json {
1453    Json::Array(
1454        observations
1455            .iter()
1456            .map(|(path, kinds)| {
1457                let access = kinds
1458                    .iter()
1459                    .map(|(kind, outcomes)| {
1460                        (
1461                            kind.name(),
1462                            Json::Array(
1463                                outcomes
1464                                    .iter()
1465                                    .map(|outcome| Json::String(outcome.to_string()))
1466                                    .collect(),
1467                            ),
1468                        )
1469                    })
1470                    .collect();
1471                Json::Object(vec![
1472                    ("path", Json::String(lossy_path(path.as_path()))),
1473                    ("access", Json::Object(access)),
1474                ])
1475            })
1476            .collect(),
1477    )
1478}
1479
1480/// The JSON of `connections`: each with its `kind`, `ip`, `unix` or `abstract`,
1481/// and its `address`, `path` or `name`.
1482fn json_connections(connections: &BTreeSet<Connection>) -> Json {
1483    Json::Array(
1484        connections
1485            .iter()
1486            .map(|connection| {
1487                let (kind, member) = match connection {
1488                    Connection::Ip(address) => {
1489                        ("ip", ("address", Json::String(address.to_string())))
1490                    },
1491                    Connection::UnixPath(path) => {
1492                        ("unix", ("path", Json::String(lossy_path(path.as_path()))))
1493                    },
1494                    Connection::UnixAbstract(name) => {
1495                        (
1496                            "abstract",
1497                            (
1498                                "name",
1499                                Json::String(String::from_utf8_lossy(name).into_owned()),
1500                            ),
1501                        )
1502                    },
1503                };
1504                Json::Object(vec![("kind", Json::text(kind)), member])
1505            })
1506            .collect(),
1507    )
1508}
1509
1510/// The JSON of `program`.
1511fn json_program(program: &ReportProgram) -> Json {
1512    Json::Object(vec![
1513        ("path", Json::String(lossy_path(&program.path))),
1514        ("args", json_args(&program.args)),
1515        ("inherited", Json::Bool(program.inherited)),
1516        ("observations", json_observations(&program.observations)),
1517        ("connections", json_connections(&program.connections)),
1518    ])
1519}
1520
1521/// The JSON of `process`.
1522fn json_process(process: &ReportProcess) -> Json {
1523    Json::Object(vec![
1524        ("id", Json::Number(process.id.to_string())),
1525        ("pid", Json::optional(process.pid)),
1526        ("parent", Json::optional(process.parent)),
1527        ("exit", process.exit.map_or(Json::Null, json_exit)),
1528        (
1529            "programs",
1530            Json::Array(process.programs.iter().map(json_program).collect()),
1531        ),
1532    ])
1533}
1534
1535/// The JSON of `command`, with its processes in a hierarchical report.
1536fn json_command(
1537    command: &ReportCommand,
1538    mode: ReportMode,
1539) -> Json {
1540    let mut members = vec![
1541        ("argv", json_args(&command.argv)),
1542        (
1543            "program",
1544            command.program.as_ref().map_or(Json::Null, |program| {
1545                Json::String(lossy_path(program.as_path()))
1546            }),
1547        ),
1548        ("cwd", Json::String(lossy_path(command.cwd.as_path()))),
1549        ("cached", Json::Bool(command.cached)),
1550        ("outcome", json_outcome(&command.outcome)),
1551        (
1552            "complete",
1553            command.complete().map_or(Json::Null, Json::Bool),
1554        ),
1555        (
1556            "incomplete",
1557            Json::Array(
1558                command
1559                    .incomplete
1560                    .iter()
1561                    .map(|reason| json_reason(reason, mode))
1562                    .collect(),
1563            ),
1564        ),
1565    ];
1566    if mode == ReportMode::Hierarchical {
1567        members.push((
1568            "processes",
1569            Json::Array(command.processes.iter().map(json_process).collect()),
1570        ));
1571    }
1572    Json::Object(members)
1573}
1574
1575/// Unit tests of the report's private helpers.
1576#[cfg(test)]
1577#[allow(clippy::disallowed_macros, reason = "test code: the tests assert")]
1578mod tests {
1579    use std::ffi::OsString;
1580
1581    use super::{Json, escape_text, is_plain_word, shell_words, write_json_string};
1582
1583    /// Strings are escaped as `serde_json` escapes them, so it reads them back.
1584    #[test]
1585    fn strings_escape_as_serde_json_does() -> Result<(), serde_json::Error> {
1586        let value = format!(
1587            "quote \" backslash \\ newline \n tab \t bell \u{07} back \u{08} feed \u{0c} return \
1588             \r unit \u{1f} delete \u{7f} replacement {}",
1589            char::REPLACEMENT_CHARACTER
1590        );
1591        let mut text = String::new();
1592        write_json_string(&mut text, &value);
1593        assert_eq!(text, serde_json::to_string(&value)?);
1594        assert_eq!(serde_json::from_str::<String>(&text)?, value);
1595        Ok(())
1596    }
1597
1598    /// Empty arrays and objects are written as `[]` and `{}`, and members keep
1599    /// their order.
1600    #[test]
1601    fn values_write_in_order() {
1602        let mut text = String::new();
1603        Json::Object(vec![
1604            ("b", Json::Array(Vec::new())),
1605            ("a", Json::Object(Vec::new())),
1606            ("c", Json::Array(vec![Json::Null, Json::Bool(false)])),
1607        ])
1608        .write(&mut text, 0);
1609        assert_eq!(
1610            text,
1611            "{\n  \"b\": [],\n  \"a\": {},\n  \"c\": [\n    null,\n    false\n  ]\n}"
1612        );
1613    }
1614
1615    /// A word is quoted when it is empty or holds a character outside the plain
1616    /// set, and a single quote in it is written as `'\''`.
1617    #[test]
1618    fn words_are_quoted_for_a_shell() {
1619        assert!(is_plain_word("a-Z_0./=:,+@%^"));
1620        assert!(!is_plain_word(""));
1621        assert!(!is_plain_word("a b"));
1622        assert!(!is_plain_word("caf\u{e9}"));
1623        let args: Vec<OsString> = ["cc", "", "it's", "$HOME", "a*b"]
1624            .into_iter()
1625            .map(OsString::from)
1626            .collect();
1627        assert_eq!(shell_words(&args), "cc '' 'it'\\''s' '$HOME' 'a*b'");
1628    }
1629
1630    /// Each escape of text: a backslash, a newline, a tab and a carriage return
1631    /// with their short escapes, every other control character and the two
1632    /// separators as `\u{...}` in lowercase hexadecimal without leading zeros.
1633    #[test]
1634    fn text_escapes_backslashes_and_control_characters() {
1635        let cases = [
1636            ("\\", "\\\\"),
1637            ("\n", "\\n"),
1638            ("\t", "\\t"),
1639            ("\r", "\\r"),
1640            ("\u{0}", "\\u{0}"),
1641            ("\u{1}", "\\u{1}"),
1642            ("\u{1b}", "\\u{1b}"),
1643            ("\u{1f}", "\\u{1f}"),
1644            ("\u{7f}", "\\u{7f}"),
1645            ("\u{85}", "\\u{85}"),
1646            ("\u{9f}", "\\u{9f}"),
1647            ("\u{2028}", "\\u{2028}"),
1648            ("\u{2029}", "\\u{2029}"),
1649            ("a\nb\\c", "a\\nb\\\\c"),
1650        ];
1651        for (text, escaped) in cases {
1652            assert_eq!(escape_text(text), escaped, "{text:?}");
1653        }
1654    }
1655
1656    /// Every other character stays as it is, such as letters, quotes, `é`, U+FFFD,
1657    /// U+00A0 and U+200B, so a string without a backslash or a control character
1658    /// reads as before.
1659    #[test]
1660    fn text_keeps_every_other_character() {
1661        for text in [
1662            "plain /work/main.c",
1663            "it's \"quoted\" $HOME",
1664            "caf\u{e9}",
1665            "�",
1666            "\u{a0}",
1667            "\u{200b}",
1668            "\u{1f600}",
1669            "",
1670        ] {
1671            assert_eq!(escape_text(text), text, "{text:?}");
1672        }
1673    }
1674
1675    /// Two strings that would read alike without the backslash's escape read
1676    /// differently, such as a newline and a backslash followed by `n`.
1677    #[test]
1678    fn escapes_keep_different_strings_apart() {
1679        let pairs = [
1680            ("\n", "\\n"),
1681            ("\t", "\\t"),
1682            ("\r", "\\r"),
1683            ("\u{1b}", "\\u{1b}"),
1684            ("\u{0}", "\\u{0}"),
1685            ("\u{2028}", "\\u{2028}"),
1686            ("a\\", "a\\\\"),
1687        ];
1688        for (first, second) in pairs {
1689            assert_ne!(first, second);
1690            assert_ne!(
1691                escape_text(first),
1692                escape_text(second),
1693                "{first:?} {second:?}"
1694            );
1695        }
1696    }
1697
1698    /// An argument is escaped before it is quoted, so an argument with an escape is
1699    /// always quoted, and the escape of a single quote stays as it is.
1700    #[test]
1701    fn arguments_are_escaped_before_they_are_quoted() {
1702        let args: Vec<OsString> = ["a\nb", "back\\slash", "it's\t"]
1703            .into_iter()
1704            .map(OsString::from)
1705            .collect();
1706        assert_eq!(shell_words(&args), "'a\\nb' 'back\\\\slash' 'it'\\''s\\t'");
1707    }
1708}