panicgraph 0.1.4

Reports which functions can panic, why, and through what call path.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Rendering of analysis results.

use std::fmt::Write as _;

use anyhow::Result;

use crate::{
    Body, Category, CategorySet, FuncId, Graph, Solution, Terminal,
    args::{Args, Format},
    util::Map,
    witness,
};

/// One reported function.
struct Finding {
    /// Every node that renders under this name. A generic function has one
    /// per instantiation, and they share a source location, so reporting
    /// them separately would print the same line several times.
    ids: Vec<FuncId>,
    categories: CategorySet,
}

impl Finding {
    /// The node the report describes the function through.
    fn id(&self) -> FuncId {
        self.ids.first().copied().unwrap_or(FuncId(0))
    }
}

/// Renders the result of an analysis.
///
/// # Errors
///
/// Returns an error if JSON serialisation fails.
pub fn analysis(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
    out: &mut String,
) -> Result<()> {
    let findings = collect(graph, solution, args);
    match args.format {
        Format::Human => human(graph, solution, args, &findings, out),
        Format::Json => json(graph, &findings, out)?,
        Format::Github => github(graph, &findings, out),
        // Handled before the report is built, because it draws the tree
        // rather than the list of findings.
        #[cfg(feature = "svg")]
        Format::Svg => {}
    }
    Ok(())
}

/// Every function worth reporting, with the categories it reports under.
///
/// The report and the gate have to agree about this, since a baseline one
/// writes is what the other measures against, so both read it from here.
pub(crate) fn reportable<'a>(
    graph: &'a Graph,
    solution: &'a Solution,
    args: &'a Args,
) -> impl Iterator<Item = (FuncId, &'a Body, CategorySet)> {
    graph.iter().filter_map(move |(id, body)| {
        if body.opaque || !(args.all_crates || body.local) {
            return None;
        }
        let categories = args.only.map_or_else(
            || solution.enabled(id),
            |only| solution.enabled(id).intersection(only),
        );
        (!categories.is_empty()).then_some((id, body, categories))
    })
}

/// Whether anything at all would be reported under these settings.
///
/// The exit code is what a continuous integration run reads, so it has to
/// agree with what the report prints rather than with the unfiltered
/// solution: a run that names no finding has nothing to report.
#[must_use]
pub fn any_finding(graph: &Graph, solution: &Solution, args: &Args) -> bool {
    reportable(graph, solution, args).next().is_some()
}

/// Selects the functions worth reporting, one entry per name.
fn collect(graph: &Graph, solution: &Solution, args: &Args) -> Vec<Finding> {
    let mut by_name: Vec<(&str, Finding)> = Vec::new();
    let mut index: Map<(&str, &str), usize> = Map::default();
    for (id, body, categories) in reportable(graph, solution, args) {
        let name = (body.krate.as_str(), body.display.as_str());
        if let Some(&at) = index.get(&name) {
            let finding = &mut by_name[at].1;
            finding.ids.push(id);
            finding.categories = finding.categories.union(categories);
        } else {
            index.insert(name, by_name.len());
            by_name.push((
                body.display.as_str(),
                Finding {
                    ids: vec![id],
                    categories,
                },
            ));
        }
    }
    by_name.sort_by(|a, b| a.0.cmp(b.0));
    by_name.into_iter().map(|(_, f)| f).collect()
}

/// Writes the human readable report.
fn human(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
    findings: &[Finding],
    out: &mut String,
) {
    header(graph, args, findings.len(), out);

    if findings.is_empty() {
        out.push_str("\nNo function can panic under this policy.\n");
        return;
    }

    out.push('\n');
    for finding in findings {
        let body = graph.body(finding.id());
        let _ = writeln!(out, "{}", body.display);
        if let Some(loc) = &body.loc {
            let _ = writeln!(out, "    defined at {loc}");
        }
        for category in finding.categories.iter() {
            match direct_site(graph, solution, finding, category) {
                Some(site) => {
                    let _ = write!(out, "    {category:<18} {}", site.0);
                    if let Some(loc) = site.1 {
                        let _ = write!(out, " at {loc}");
                    }
                    out.push('\n');
                }
                None => {
                    let _ = writeln!(
                        out,
                        "    {category:<18} reached through a call"
                    );
                }
            }
        }
        out.push('\n');
    }

    let _ =
        writeln!(out, "Run `panicgraph why <function>` to see a call path.");
}

/// The reason and place of a panic this function raises itself.
///
/// Returns nothing when the category is only reached through a call.
fn direct_site<'a>(
    graph: &'a Graph,
    solution: &Solution,
    finding: &Finding,
    category: Category,
) -> Option<(&'a str, Option<String>)> {
    for &id in &finding.ids {
        let body = graph.body(id);
        let activity = solution.activity(graph, id);
        let hit =
            body.sites.iter().enumerate().find(|(i, site)| {
                site.category == category && activity.site(*i)
            });
        if let Some((_, site)) = hit {
            return Some((
                site.reason.as_str(),
                site.loc.as_ref().map(ToString::to_string),
            ));
        }
    }
    None
}

/// Writes the analysis preamble.
fn header(graph: &Graph, args: &Args, found: usize, out: &mut String) {
    out.push_str("Analysis\n");
    if let Some(config) = graph.config() {
        let _ = writeln!(out, "    rustc              {}", config.rustc);
        let _ = writeln!(
            out,
            "    profile            {} (debug assertions {}, overflow \
             checks {})",
            config.profile,
            on_off(config.debug_assertions),
            on_off(config.overflow_checks),
        );
        let _ =
            writeln!(out, "    standard library   {}", config.std_mode.name());
    }
    let suppressed = if args.suppress.is_empty() {
        "nothing".to_owned()
    } else {
        args.suppress.to_string()
    };
    let _ = writeln!(out, "    suppressed         {suppressed}");
    let _ = writeln!(
        out,
        "    functions          {} analysed, {found} can panic",
        graph.len()
    );
}

/// Writes the machine readable report.
fn json(graph: &Graph, findings: &[Finding], out: &mut String) -> Result<()> {
    let items: Vec<serde_json::Value> = findings
        .iter()
        .map(|f| {
            let body = graph.body(f.id());
            serde_json::json!({
                "function": body.display,
                "crate": body.krate,
                "location": body.loc.as_ref().map(ToString::to_string),
                "categories": f
                    .categories
                    .iter()
                    .map(crate::Category::name)
                    .collect::<Vec<_>>(),
            })
        })
        .collect();
    let doc = serde_json::json!({
        "config": graph.config(),
        "findings": items,
    });
    out.push_str(&serde_json::to_string_pretty(&doc)?);
    out.push('\n');
    Ok(())
}

/// Splits a `file:line:col` location into the fields a workflow command
/// wants, or nothing at all when there is no location to name.
pub(crate) fn workflow_location(loc: Option<&str>) -> String {
    fn split(loc: &str) -> Option<String> {
        let mut parts = loc.rsplitn(3, ':');
        let col = parts.next()?;
        let line = parts.next()?;
        let file = parts.next()?;
        Some(format!("file={file},line={line},col={col},"))
    }
    loc.and_then(split).unwrap_or_default()
}

/// Writes one workflow command per finding, which a continuous integration
/// log turns into an annotation against the source.
fn github(graph: &Graph, findings: &[Finding], out: &mut String) {
    for finding in findings {
        let body = graph.body(finding.id());
        let loc = body.loc.as_ref().map(ToString::to_string);
        let where_at = workflow_location(loc.as_deref());
        let _ = writeln!(
            out,
            "::warning {where_at}title=Function can panic::{} can panic \
             with {}",
            body.display,
            finding
                .categories
                .iter()
                .map(Category::name)
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
}

/// Explains how one function reaches a panic.
pub fn why(graph: &Graph, solution: &Solution, name: &str, out: &mut String) {
    let matches = graph.find_by_display(name);
    let Some(&id) = matches.first() else {
        let _ = writeln!(out, "No function matching `{name}` was analysed.");
        return;
    };
    let body = graph.body(id);
    if matches.len() > 1 {
        let same = matches
            .iter()
            .filter(|&&other| graph.body(other).display == body.display)
            .count();
        if same == matches.len() {
            let _ = writeln!(
                out,
                "`{name}` names {same} instantiations of the same function; \
                 explaining one.\n"
            );
        } else {
            let _ = writeln!(
                out,
                "`{name}` matched {} functions; explaining `{}`.\n",
                matches.len(),
                body.display
            );
        }
    }

    let categories = solution.enabled(id);
    if categories.is_empty() {
        let _ =
            writeln!(out, "{} cannot panic under this policy.", body.display);
        return;
    }

    for category in categories.iter() {
        let Some(path) = witness::find(graph, solution, id, category) else {
            continue;
        };
        let _ =
            writeln!(out, "{} can panic with `{category}`:\n", body.display);
        let _ = writeln!(out, "  {}", body.display);
        for hop in &path.hops {
            if let Some(loc) = &hop.loc {
                let _ = writeln!(out, "      at {loc}  [{}]", hop.kind.name());
            }
            let _ = writeln!(out, "  -> {}", graph.body(hop.callee).display);
        }
        describe_terminal(graph, &path, out);
        out.push('\n');
    }
}

/// Writes the last line of a witness path.
fn describe_terminal(graph: &Graph, path: &witness::Witness, out: &mut String) {
    let body = graph.body(path.func);
    match path.terminal {
        Terminal::Site(i) => {
            let Some(site) = body.sites.get(i) else {
                return;
            };
            let _ = write!(out, "      {}", site.reason);
            if let Some(loc) = &site.loc {
                let _ = write!(out, " at {loc}");
            }
            out.push('\n');
        }
        Terminal::Opaque if body.foreign => {
            let _ = writeln!(
                out,
                "      foreign code, which has no Rust body to read"
            );
        }
        Terminal::Opaque => {
            let _ = writeln!(
                out,
                "      no MIR available for this function, so its panics \
                 are unknown"
            );
            let _ = writeln!(
                out,
                "      re-run with `--std full` to see inside the standard \
                 library"
            );
        }
        Terminal::Unresolved(i) => {
            let Some(call) = body.calls.get(i) else {
                return;
            };
            let _ = write!(
                out,
                "      calls {} through a {} edge, target unknown",
                call.callee_display,
                call.kind.name()
            );
            if let Some(loc) = &call.loc {
                let _ = write!(out, " at {loc}");
            }
            out.push('\n');
        }
    }
}

/// Lists the categories and what each means.
pub fn kinds(out: &mut String) {
    out.push_str("Panic categories\n\n");
    for category in crate::category::ALL {
        let _ =
            writeln!(out, "  {:<18} {}", category.name(), category.describe());
    }
    out.push_str(
        "\nGroup aliases: `oom` covers capacity-overflow and alloc-failure, \
         `default` adds ub-check, `all` covers everything.\n",
    );
}

/// Renders a flag as text.
const fn on_off(value: bool) -> &'static str {
    if value { "on" } else { "off" }
}

/// Suppressed categories that were nonetheless observed, for the hint line.
///
/// # Errors
///
/// Returns an error if the graph cannot be solved without the suppression,
/// which is what the count is measured against.
pub fn suppressed_hint(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
) -> Result<Option<String>> {
    if args.suppress.is_empty() {
        return Ok(None);
    }
    let hidden = solution.cleared_by_suppression(graph)?;
    Ok((hidden > 0).then(|| {
        format!(
            "{hidden} local functions panic only through suppressed \
             categories ({}).",
            args.suppress
        )
    }))
}