rustc_mir_transform/
ffi_unwind_calls.rs

1use rustc_abi::ExternAbi;
2use rustc_hir::def_id::{LOCAL_CRATE, LocalDefId};
3use rustc_middle::mir::*;
4use rustc_middle::query::{LocalCrate, Providers};
5use rustc_middle::ty::{self, TyCtxt, layout};
6use rustc_middle::{bug, span_bug};
7use rustc_session::lint::builtin::FFI_UNWIND_CALLS;
8use rustc_target::spec::PanicStrategy;
9use tracing::debug;
10
11use crate::errors;
12
13// Check if the body of this def_id can possibly leak a foreign unwind into Rust code.
14fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool {
15    debug!("has_ffi_unwind_calls({local_def_id:?})");
16
17    // Only perform check on functions because constants cannot call FFI functions.
18    let def_id = local_def_id.to_def_id();
19    let kind = tcx.def_kind(def_id);
20    if !kind.is_fn_like() {
21        return false;
22    }
23
24    let body = &*tcx.mir_built(local_def_id).borrow();
25
26    let body_ty = tcx.type_of(def_id).skip_binder();
27    let body_abi = match body_ty.kind() {
28        ty::FnDef(..) => body_ty.fn_sig(tcx).abi(),
29        ty::Closure(..) => ExternAbi::RustCall,
30        ty::CoroutineClosure(..) => ExternAbi::RustCall,
31        ty::Coroutine(..) => ExternAbi::Rust,
32        ty::Error(_) => return false,
33        _ => span_bug!(body.span, "unexpected body ty: {:?}", body_ty),
34    };
35    let body_can_unwind = layout::fn_can_unwind(tcx, Some(def_id), body_abi);
36
37    // Foreign unwinds cannot leak past functions that themselves cannot unwind.
38    if !body_can_unwind {
39        return false;
40    }
41
42    let mut tainted = false;
43
44    for block in body.basic_blocks.iter() {
45        if block.is_cleanup {
46            continue;
47        }
48        let Some(terminator) = &block.terminator else { continue };
49        let TerminatorKind::Call { func, .. } = &terminator.kind else { continue };
50
51        let ty = func.ty(body, tcx);
52        let sig = ty.fn_sig(tcx);
53
54        // Rust calls cannot themselves create foreign unwinds.
55        // We assume this is true for intrinsics as well.
56        if let ExternAbi::RustIntrinsic
57        | ExternAbi::Rust
58        | ExternAbi::RustCall
59        | ExternAbi::RustCold = sig.abi()
60        {
61            continue;
62        };
63
64        let fn_def_id = match ty.kind() {
65            ty::FnPtr(..) => None,
66            &ty::FnDef(def_id, _) => {
67                // Rust calls cannot themselves create foreign unwinds (even if they use a non-Rust
68                // ABI). So the leak of the foreign unwind into Rust can only be elsewhere, not
69                // here.
70                if !tcx.is_foreign_item(def_id) {
71                    continue;
72                }
73                Some(def_id)
74            }
75            _ => bug!("invalid callee of type {:?}", ty),
76        };
77
78        if layout::fn_can_unwind(tcx, fn_def_id, sig.abi()) {
79            // We have detected a call that can possibly leak foreign unwind.
80            //
81            // Because the function body itself can unwind, we are not aborting this function call
82            // upon unwind, so this call can possibly leak foreign unwind into Rust code if the
83            // panic runtime linked is panic-abort.
84
85            let lint_root = body.source_scopes[terminator.source_info.scope]
86                .local_data
87                .as_ref()
88                .assert_crate_local()
89                .lint_root;
90            let span = terminator.source_info.span;
91
92            let foreign = fn_def_id.is_some();
93            tcx.emit_node_span_lint(
94                FFI_UNWIND_CALLS,
95                lint_root,
96                span,
97                errors::FfiUnwindCall { span, foreign },
98            );
99
100            tainted = true;
101        }
102    }
103
104    tainted
105}
106
107fn required_panic_strategy(tcx: TyCtxt<'_>, _: LocalCrate) -> Option<PanicStrategy> {
108    if tcx.is_panic_runtime(LOCAL_CRATE) {
109        return Some(tcx.sess.panic_strategy());
110    }
111
112    if tcx.sess.panic_strategy() == PanicStrategy::Abort {
113        return Some(PanicStrategy::Abort);
114    }
115
116    for def_id in tcx.hir().body_owners() {
117        if tcx.has_ffi_unwind_calls(def_id) {
118            // Given that this crate is compiled in `-C panic=unwind`, the `AbortUnwindingCalls`
119            // MIR pass will not be run on FFI-unwind call sites, therefore a foreign exception
120            // can enter Rust through these sites.
121            //
122            // On the other hand, crates compiled with `-C panic=abort` expects that all Rust
123            // functions cannot unwind (whether it's caused by Rust panic or foreign exception),
124            // and this expectation mismatch can cause unsoundness (#96926).
125            //
126            // To address this issue, we enforce that if FFI-unwind calls are used in a crate
127            // compiled with `panic=unwind`, then the final panic strategy must be `panic=unwind`.
128            // This will ensure that no crates will have wrong unwindability assumption.
129            //
130            // It should be noted that it is okay to link `panic=unwind` into a `panic=abort`
131            // program if it contains no FFI-unwind calls. In such case foreign exception can only
132            // enter Rust in a `panic=abort` crate, which will lead to an abort. There will also
133            // be no exceptions generated from Rust, so the assumption which `panic=abort` crates
134            // make, that no Rust function can unwind, indeed holds for crates compiled with
135            // `panic=unwind` as well. In such case this function returns `None`, indicating that
136            // the crate does not require a particular final panic strategy, and can be freely
137            // linked to crates with either strategy (we need such ability for libstd and its
138            // dependencies).
139            return Some(PanicStrategy::Unwind);
140        }
141    }
142
143    // This crate can be linked with either runtime.
144    None
145}
146
147pub(crate) fn provide(providers: &mut Providers) {
148    *providers = Providers { has_ffi_unwind_calls, required_panic_strategy, ..*providers };
149}