panicgraph 0.1.2

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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Walks MIR and records what each function can panic with, and who it calls.

use panicgraph::{
    Body, CallSite, Category, EdgeKind, FuncKey, Guard, Loc, PanicSite,
    Termination, UnwindOrigin,
};
use rustc_middle::{
    middle::codegen_fn_attrs::CodegenFnAttrFlags,
    mir::{self, AssertKind, BasicBlock, TerminatorKind, UnwindAction},
    ty::{self, Instance, TyCtxt, TypeVisitableExt, TypingEnv},
};

use crate::{
    fold,
    sinks::SinkTable,
    util::{Map, Set},
};

/// One function to analyse, together with the environment its generic
/// arguments belong to.
///
/// A callee resolved from a generic caller carries that caller's parameters,
/// so the two travel together: normalizing the callee's types demands the
/// environment those parameters were declared in.
#[derive(Clone, Copy)]
struct Work<'tcx> {
    inst: Instance<'tcx>,
    env: TypingEnv<'tcx>,
}

/// Entries collected from one body before reachability guards are attached.
struct Raw<'tcx> {
    sites: Vec<PanicSite>,
    site_blocks: Vec<BasicBlock>,
    calls: Vec<CallSite>,
    call_blocks: Vec<BasicBlock>,
    unwind_edges: Vec<(UnwindOrigin, BasicBlock)>,
    successors: Vec<Work<'tcx>>,
}

impl Raw<'_> {
    const fn new() -> Self {
        Self {
            sites: Vec::new(),
            site_blocks: Vec::new(),
            calls: Vec::new(),
            call_blocks: Vec::new(),
            unwind_edges: Vec::new(),
            successors: Vec::new(),
        }
    }
}

/// Collects panic facts for every function reachable from a crate's roots.
pub struct Extractor<'tcx> {
    tcx: TyCtxt<'tcx>,
    sinks: SinkTable,
    bodies: Vec<Body>,
    seen: Set<String>,
}

impl<'tcx> Extractor<'tcx> {
    /// Prepares an extractor for one compilation.
    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
        Self {
            tcx,
            sinks: SinkTable::new(),
            bodies: Vec::new(),
            seen: Set::default(),
        }
    }

    /// Walks the whole reachable call graph and returns the bodies found.
    pub fn run(mut self) -> Vec<Body> {
        let mut queue: Vec<Work<'tcx>> = self.roots();
        // Every instance is recorded in `seen` before its callees are
        // queued, so each function is expanded at most once and the walk
        // terminates once the reachable set is exhausted.
        while let Some(work) = queue.pop() {
            let Some(key) = self.symbol_of(work.inst) else {
                continue;
            };
            if !self.seen.insert(key.clone()) {
                continue;
            }
            queue.extend(self.build(work, FuncKey(key)));
        }
        self.bodies
    }

    /// Every function defined in the crate under compilation.
    fn roots(&self) -> Vec<Work<'tcx>> {
        let mut out = Vec::new();
        for local in self.tcx.mir_keys(()) {
            let did = local.to_def_id();
            if !self.tcx.is_mir_available(did) {
                continue;
            }
            if !matches!(
                self.tcx.def_kind(did),
                rustc_hir::def::DefKind::Fn
                    | rustc_hir::def::DefKind::AssocFn
                    | rustc_hir::def::DefKind::Closure
            ) {
                continue;
            }
            // Generic items are analysed as written. Their callees often
            // cannot be resolved without concrete arguments, which is
            // recorded honestly as an unresolved edge rather than silently
            // dropping the function from the report.
            let args = ty::GenericArgs::identity_for_item(self.tcx, did);
            out.push(Work {
                inst: Instance::new_raw(did, args),
                env: TypingEnv::post_analysis(self.tcx, did),
            });
        }
        out
    }

    /// Records one function and returns the callees worth expanding.
    fn build(&mut self, work: Work<'tcx>, key: FuncKey) -> Vec<Work<'tcx>> {
        let inst = work.inst;
        if !Self::has_mir_body(self.tcx, inst) {
            let did = inst.def_id();
            let display = self.tcx.def_path_str(did);
            let krate = self.tcx.crate_name(did.krate).to_string();
            let mut body = Body::opaque(key, display, krate);
            if self.never_unwinds(did) {
                // The compiler guarantees this function does not unwind, so
                // it raises no panic even though its body is unavailable.
                // Allocator shims are the common case.
                body.opaque = false;
            }
            self.bodies.push(body);
            return Vec::new();
        }

        let mir = self.tcx.instance_mir(inst.def);
        let raw = self.scan(work, mir);
        let origins = Self::propagate_origins(mir, &raw.unwind_edges);

        let mut sites = raw.sites;
        for (site, bb) in sites.iter_mut().zip(&raw.site_blocks) {
            site.guard = Self::guard_for(mir, &origins, *bb);
        }
        let mut calls = raw.calls;
        for (call, bb) in calls.iter_mut().zip(&raw.call_blocks) {
            call.guard = Self::guard_for(mir, &origins, *bb);
        }

        let did = inst.def_id();
        self.bodies.push(Body {
            key,
            display: self.tcx.def_path_str(did),
            krate: self.tcx.crate_name(did.krate).to_string(),
            loc: self.loc_of(self.tcx.def_span(did)),
            sites,
            calls,
            opaque: false,
            local: did.is_local(),
        });
        raw.successors
    }

    /// The environment types in this body must be normalized against.
    ///
    /// A body still carrying generic parameters has to be read in the
    /// environment those parameters were declared in, which is the caller's,
    /// not the callee's: a trait method resolved from a generic caller knows
    /// only its own `Self`, so normalizing the caller's parameters there asks
    /// the compiler about parameters it has never heard of.
    fn env_for(work: Work<'tcx>) -> TypingEnv<'tcx> {
        if work.inst.args.has_param() {
            work.env
        } else {
            TypingEnv::fully_monomorphized()
        }
    }

    /// Reads every terminator of a body into raw entries.
    fn scan(&mut self, work: Work<'tcx>, mir: &mir::Body<'tcx>) -> Raw<'tcx> {
        let inst = work.inst;
        let env = Self::env_for(work);
        let reach = fold::reachable(self.tcx, inst, env, mir);
        let mut raw = Raw::new();
        for (bb, data) in mir.basic_blocks.iter_enumerated() {
            let Some(term) = &data.terminator else {
                continue;
            };
            if !reach.is_live(bb) {
                continue;
            }
            match &term.kind {
                TerminatorKind::Assert { msg, unwind, .. } => {
                    if reach.is_settled(bb) {
                        // The condition holds for these generic arguments,
                        // so the compiler emits no check at all.
                        continue;
                    }
                    self.push_assert(
                        &mut raw,
                        bb,
                        msg,
                        *unwind,
                        term.source_info.span,
                    );
                }
                TerminatorKind::Call {
                    func,
                    unwind,
                    fn_span,
                    ..
                } => {
                    let ty = func.ty(&mir.local_decls, self.tcx);
                    self.push_call(
                        &mut raw, inst, env, bb, ty, *unwind, *fn_span,
                    );
                }
                TerminatorKind::Drop { place, unwind, .. } => {
                    let ty = place.ty(&mir.local_decls, self.tcx).ty;
                    self.push_drop(
                        &mut raw,
                        inst,
                        env,
                        bb,
                        ty,
                        *unwind,
                        term.source_info.span,
                    );
                }
                _ => {}
            }
        }
        raw
    }

    /// Records a compiler inserted check as a panic site.
    fn push_assert<O>(
        &self,
        raw: &mut Raw<'tcx>,
        bb: BasicBlock,
        msg: &AssertKind<O>,
        unwind: UnwindAction,
        span: rustc_span::Span,
    ) {
        if !self.tcx.sess.overflow_checks() && msg.is_optional_overflow_check()
        {
            // Codegen drops these outright in a build without overflow
            // checks: the arithmetic wraps instead. They survive in the MIR
            // only because a function marked to inherit the setting is built
            // once and used by crates that disagree about it.
            return;
        }
        let (category, termination, reason) = classify_assert(msg);
        let index = u32::try_from(raw.sites.len()).unwrap_or(u32::MAX);
        raw.sites.push(PanicSite {
            category,
            termination,
            reason: reason.to_owned(),
            sink: None,
            loc: self.loc_of(span),
            guard: Guard::default(),
        });
        raw.site_blocks.push(bb);
        Self::record_unwind(raw, UnwindOrigin::Site(index), unwind);
    }

    /// Records a call, either as a panic site or as a graph edge.
    #[allow(clippy::too_many_arguments)]
    fn push_call(
        &mut self,
        raw: &mut Raw<'tcx>,
        inst: Instance<'tcx>,
        env: TypingEnv<'tcx>,
        bb: BasicBlock,
        ty: ty::Ty<'tcx>,
        unwind: UnwindAction,
        span: rustc_span::Span,
    ) {
        let Ok(ty) = inst.try_instantiate_mir_and_normalize_erasing_regions(
            self.tcx,
            env,
            ty::EarlyBinder::bind(self.tcx, ty),
        ) else {
            self.push_edge(
                raw,
                bb,
                None,
                "<unresolved>".to_owned(),
                EdgeKind::Unresolved,
                unwind,
                span,
            );
            return;
        };
        let ty::FnDef(did, args) = *ty.kind() else {
            // A call through a function pointer. The target set is unknown.
            self.push_edge(
                raw,
                bb,
                None,
                "<fn pointer>".to_owned(),
                EdgeKind::FnPtr,
                unwind,
                span,
            );
            return;
        };
        let Some(args) = args.no_bound_vars() else {
            self.push_edge(
                raw,
                bb,
                None,
                self.tcx.def_path_str(did),
                EdgeKind::Unresolved,
                unwind,
                span,
            );
            return;
        };
        let resolved = Instance::try_resolve(self.tcx, env, did, args);
        let Ok(Some(callee)) = resolved else {
            self.push_edge(
                raw,
                bb,
                None,
                self.tcx.def_path_str(did),
                EdgeKind::Unresolved,
                unwind,
                span,
            );
            return;
        };

        if let Some(sink) = self.sinks.get(self.tcx, callee.def_id()) {
            let index = u32::try_from(raw.sites.len()).unwrap_or(u32::MAX);
            raw.sites.push(PanicSite {
                category: sink.category,
                termination: sink.termination,
                reason: format!(
                    "calls {}",
                    self.tcx.def_path_str(callee.def_id())
                ),
                sink: Some(self.tcx.def_path_str(callee.def_id())),
                loc: self.loc_of(span),
                guard: Guard::default(),
            });
            raw.site_blocks.push(bb);
            Self::record_unwind(raw, UnwindOrigin::Site(index), unwind);
            return;
        }

        if matches!(
            callee.def,
            ty::InstanceKind::Intrinsic(..)
                | ty::InstanceKind::LlvmIntrinsic(..)
        ) {
            // Intrinsics are compiler defined operations. They cannot call
            // back into the program, so they add nothing to the graph, and
            // recording them as bodies without MIR would report every use of
            // a hint like `cold_path` as an unknown panic.
            return;
        }
        let kind = match callee.def {
            ty::InstanceKind::Virtual(..) => EdgeKind::Vtable,
            _ => EdgeKind::Static,
        };
        let display = self.tcx.def_path_str(callee.def_id());
        let key = self.symbol_of(callee).map(FuncKey);
        self.push_edge(raw, bb, key, display, kind, unwind, span);
        if kind == EdgeKind::Static {
            raw.successors.push(Work { inst: callee, env });
        }
    }

    /// Records the drop glue reached by a `Drop` terminator.
    #[allow(clippy::too_many_arguments)]
    fn push_drop(
        &self,
        raw: &mut Raw<'tcx>,
        inst: Instance<'tcx>,
        env: TypingEnv<'tcx>,
        bb: BasicBlock,
        ty: ty::Ty<'tcx>,
        unwind: UnwindAction,
        span: rustc_span::Span,
    ) {
        let normalized = inst
            .try_instantiate_mir_and_normalize_erasing_regions(
                self.tcx,
                env,
                ty::EarlyBinder::bind(self.tcx, ty),
            );
        let Ok(ty) = normalized else {
            self.push_edge(
                raw,
                bb,
                None,
                "<unresolved drop>".to_owned(),
                EdgeKind::Unresolved,
                unwind,
                span,
            );
            return;
        };
        if !ty.needs_drop(self.tcx, env) {
            // Nothing runs here. A reference or a struct of raw pointers has
            // no glue whatever its parameters turn out to be, so treating
            // the terminator as an unknown target would invent a panic that
            // no instantiation can reach.
            return;
        }
        if ty.has_param() {
            // Something has to run, but which glue is only known once the
            // dropped type is concrete.
            self.push_edge(
                raw,
                bb,
                None,
                format!("drop glue for {ty}"),
                EdgeKind::Unresolved,
                unwind,
                span,
            );
            return;
        }
        let glue = Instance::resolve_drop_glue(self.tcx, ty);
        let display = format!("drop glue for {ty}");
        let key = self.symbol_of(glue).map(FuncKey);
        self.push_edge(raw, bb, key, display, EdgeKind::Drop, unwind, span);
        raw.successors.push(Work { inst: glue, env });
    }

    /// Appends a call edge and its unwind channel.
    #[allow(clippy::too_many_arguments)]
    fn push_edge(
        &self,
        raw: &mut Raw<'tcx>,
        bb: BasicBlock,
        callee: Option<FuncKey>,
        callee_display: String,
        kind: EdgeKind,
        unwind: UnwindAction,
        span: rustc_span::Span,
    ) {
        let index = u32::try_from(raw.calls.len()).unwrap_or(u32::MAX);
        raw.calls.push(CallSite {
            callee,
            callee_display,
            kind,
            loc: self.loc_of(span),
            guard: Guard::default(),
        });
        raw.call_blocks.push(bb);
        Self::record_unwind(raw, UnwindOrigin::Call(index), unwind);
    }

    /// Notes that unwinding from `origin` transfers control to a cleanup
    /// block.
    fn record_unwind(
        raw: &mut Raw<'tcx>,
        origin: UnwindOrigin,
        unwind: UnwindAction,
    ) {
        if let UnwindAction::Cleanup(target) = unwind {
            raw.unwind_edges.push((origin, target));
        }
    }

    /// Marks every cleanup block reachable from each unwind edge.
    fn propagate_origins(
        mir: &mir::Body<'_>,
        edges: &[(UnwindOrigin, BasicBlock)],
    ) -> Map<BasicBlock, Vec<UnwindOrigin>> {
        let mut out: Map<BasicBlock, Vec<UnwindOrigin>> = Map::default();
        for (origin, start) in edges {
            let mut seen: Set<BasicBlock> = Set::default();
            let mut stack = vec![*start];
            // `seen` admits each block once, so the walk is bounded by the
            // number of basic blocks in the body.
            while let Some(bb) = stack.pop() {
                if !seen.insert(bb) {
                    continue;
                }
                let list = out.entry(bb).or_default();
                if !list.contains(origin) {
                    list.push(*origin);
                }
                let Some(term) = &mir.basic_blocks[bb].terminator else {
                    continue;
                };
                stack.extend(term.successors());
            }
        }
        out
    }

    /// Builds the reachability guard for one basic block.
    fn guard_for(
        mir: &mir::Body<'_>,
        origins: &Map<BasicBlock, Vec<UnwindOrigin>>,
        bb: BasicBlock,
    ) -> Guard {
        Guard {
            normal: !mir.basic_blocks[bb].is_cleanup,
            origins: origins.get(&bb).cloned().unwrap_or_default(),
        }
    }

    /// Whether the compiler guarantees a function cannot unwind.
    fn never_unwinds(&self, did: rustc_hir::def_id::DefId) -> bool {
        self.tcx
            .codegen_fn_attrs(did)
            .flags
            .contains(CodegenFnAttrFlags::NEVER_UNWIND)
    }

    /// Whether the compiler can produce a body for this instance.
    fn has_mir_body(tcx: TyCtxt<'tcx>, inst: Instance<'tcx>) -> bool {
        match inst.def {
            ty::InstanceKind::Item(def) => tcx.is_mir_available(def),
            ty::InstanceKind::Intrinsic(..)
            | ty::InstanceKind::LlvmIntrinsic(..)
            | ty::InstanceKind::Virtual(..) => false,
            ty::InstanceKind::Shim(_) => true,
        }
    }

    /// The globally unique key for an instance.
    fn symbol_of(&self, inst: Instance<'tcx>) -> Option<String> {
        if matches!(inst.def, ty::InstanceKind::Virtual(..)) {
            return None;
        }
        if inst.args.has_param() {
            // A symbol name only exists once the generic arguments are
            // concrete, so a generic body is keyed by its path instead.
            return Some(format!(
                "generic:{}",
                self.tcx.def_path_str(inst.def_id())
            ));
        }
        Some(self.tcx.symbol_name(inst).name.to_owned())
    }

    /// Converts a span into a source location.
    fn loc_of(&self, span: rustc_span::Span) -> Option<Loc> {
        if span.is_dummy() {
            return None;
        }
        let map = self.tcx.sess.source_map();
        let pos = map.lookup_char_pos(span.lo());
        Some(Loc {
            file: map.filename_for_diagnostics(&pos.file.name).to_string(),
            line: u32::try_from(pos.line).unwrap_or(0),
            col: pos.col.0.saturating_add(1).try_into().unwrap_or(0),
        })
    }
}

/// Maps a compiler inserted check to a reportable category.
const fn classify_assert<O>(
    msg: &AssertKind<O>,
) -> (Category, Termination, &'static str) {
    match msg {
        AssertKind::BoundsCheck { .. } => {
            (Category::Index, Termination::Unwind, "index out of bounds")
        }
        AssertKind::Overflow(..) => (
            Category::Overflow,
            Termination::Unwind,
            "arithmetic overflow",
        ),
        AssertKind::OverflowNeg(_) => {
            (Category::Overflow, Termination::Unwind, "negation overflow")
        }
        AssertKind::DivisionByZero(_) => (
            Category::DivideByZero,
            Termination::Unwind,
            "attempt to divide by zero",
        ),
        AssertKind::RemainderByZero(_) => (
            Category::RemainderByZero,
            Termination::Unwind,
            "attempt to take remainder by zero",
        ),
        AssertKind::MisalignedPointerDereference { .. } => (
            Category::MisalignedRef,
            Termination::Abort,
            "misaligned pointer dereference",
        ),
        AssertKind::NullPointerDereference
        | AssertKind::NullReferenceConstructed => (
            Category::NullDeref,
            Termination::Abort,
            "null pointer dereference",
        ),
        AssertKind::InvalidEnumConstruction(_) => (
            Category::Explicit,
            Termination::Abort,
            "invalid enum construction",
        ),
        AssertKind::ResumedAfterReturn(_)
        | AssertKind::ResumedAfterPanic(_)
        | AssertKind::ResumedAfterDrop(_) => (
            Category::Explicit,
            Termination::Unwind,
            "coroutine resumed after completion",
        ),
    }
}