Skip to main content

rustc_mir_transform/
ffi_unwind_calls.rs

1use rustc_abi::ExternAbi;
2use rustc_ast::InlineAsmOptions;
3use rustc_hir::def_id::{LOCAL_CRATE, LocalDefId};
4use rustc_lint_defs::builtin::FFI_UNWIND_CALLS;
5use rustc_middle::mir::*;
6use rustc_middle::query::{LocalCrate, Providers};
7use rustc_middle::ty::{self, TyCtxt, layout};
8use rustc_span::{bug, span_bug};
9use rustc_target::spec::PanicStrategy;
10use tracing::debug;
11
12use crate::diagnostics;
13
14// Check if the body of this def_id can possibly leak a foreign unwind into Rust code.
15fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool {
16    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs:16",
                        "rustc_mir_transform::ffi_unwind_calls",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs"),
                        ::tracing_core::__macro_support::Option::Some(16u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::ffi_unwind_calls"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("has_ffi_unwind_calls({0:?})",
                                                    local_def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("has_ffi_unwind_calls({local_def_id:?})");
17
18    // Only perform check on functions because constants cannot call FFI functions.
19    let def_id = local_def_id.to_def_id();
20    let kind = tcx.def_kind(def_id);
21    if !kind.is_fn_like() {
22        return false;
23    }
24
25    let body_ty = tcx.type_of(def_id).skip_binder();
26    let body_abi = match body_ty.kind() {
27        ty::FnDef(..) => body_ty.fn_sig_abi(tcx),
28        ty::Closure(..) => ExternAbi::RustCall,
29        ty::CoroutineClosure(..) => ExternAbi::RustCall,
30        ty::Coroutine(..) => ExternAbi::Rust,
31        ty::Error(_) => return false,
32        _ => ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
    format_args!("unexpected body ty: {0:?}", body_ty), Location::caller())span_bug!(tcx.def_span(def_id), "unexpected body ty: {:?}", body_ty),
33    };
34    let body_can_unwind = layout::fn_can_unwind(tcx, Some(def_id), body_abi);
35
36    // Foreign unwinds cannot leak past functions that themselves cannot unwind.
37    if !body_can_unwind {
38        return false;
39    }
40
41    // Intrinsics without a body can't be checked and we must instead rely on the signature.
42    if tcx.is_intrinsic_that_must_be_overridden(def_id) {
43        return false;
44    }
45
46    let body = &*tcx.mir_built(local_def_id).borrow();
47
48    let mut tainted = false;
49
50    for block in body.basic_blocks.iter() {
51        if block.is_cleanup {
52            continue;
53        }
54        let terminator = &block.terminator;
55
56        if let TerminatorKind::InlineAsm { options, .. } = &terminator.kind {
57            if options.contains(InlineAsmOptions::MAY_UNWIND) {
58                // We have detected an inline asm block that can possibly leak foreign unwind.
59                //
60                // Because the function body itself can unwind, we are not aborting this function call
61                // upon unwind, so this call can possibly leak foreign unwind into Rust code if the
62                // panic runtime linked is panic-abort.
63
64                let lint_root = body.source_scopes[terminator.source_info.scope]
65                    .local_data
66                    .as_ref()
67                    .unwrap_crate_local()
68                    .lint_root;
69                let span = terminator.source_info.span;
70
71                tcx.emit_node_span_lint(
72                    FFI_UNWIND_CALLS,
73                    lint_root,
74                    span,
75                    diagnostics::AsmUnwindCall { span },
76                );
77
78                tainted = true;
79            }
80            continue;
81        }
82
83        let TerminatorKind::Call { func, .. } = &terminator.kind else { continue };
84
85        let ty = func.ty(body, tcx);
86        let abi = ty.fn_sig_abi(tcx);
87
88        // Rust calls cannot themselves create foreign unwinds.
89        // We assume this is true for intrinsics as well.
90        if abi.is_rustic_abi() {
91            continue;
92        }
93
94        let fn_def_id = match ty.kind() {
95            ty::FnPtr(..) => None,
96            &ty::FnDef(def_id, _) => {
97                // Rust calls cannot themselves create foreign unwinds (even if they use a non-Rust
98                // ABI). So the leak of the foreign unwind into Rust can only be elsewhere, not
99                // here.
100                if !tcx.is_foreign_item(def_id) {
101                    continue;
102                }
103                Some(def_id)
104            }
105            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("invalid callee of type {0:?}", ty), Location::caller())bug!("invalid callee of type {:?}", ty),
106        };
107
108        if layout::fn_can_unwind(tcx, fn_def_id, abi) {
109            // We have detected a call that can possibly leak foreign unwind.
110            //
111            // Because the function body itself can unwind, we are not aborting this function call
112            // upon unwind, so this call can possibly leak foreign unwind into Rust code if the
113            // panic runtime linked is panic-abort.
114
115            let lint_root = body.source_scopes[terminator.source_info.scope]
116                .local_data
117                .as_ref()
118                .unwrap_crate_local()
119                .lint_root;
120            let span = terminator.source_info.span;
121
122            let foreign = fn_def_id.is_some();
123            tcx.emit_node_span_lint(
124                FFI_UNWIND_CALLS,
125                lint_root,
126                span,
127                diagnostics::FfiUnwindCall { span, foreign },
128            );
129
130            tainted = true;
131        }
132    }
133
134    tainted
135}
136
137fn required_panic_strategy(tcx: TyCtxt<'_>, _: LocalCrate) -> Option<PanicStrategy> {
138    let local_strategy = tcx.sess.panic_strategy();
139
140    if tcx.is_panic_runtime(LOCAL_CRATE) {
141        return Some(local_strategy);
142    }
143
144    match local_strategy {
145        PanicStrategy::Abort | PanicStrategy::ImmediateAbort => return Some(local_strategy),
146        _ => {}
147    }
148
149    for def_id in tcx.hir_body_owners() {
150        if tcx.has_ffi_unwind_calls(def_id) {
151            // Given that this crate is compiled in `-C panic=unwind`, the `AbortUnwindingCalls`
152            // MIR pass will not be run on FFI-unwind call sites, therefore a foreign exception
153            // can enter Rust through these sites.
154            //
155            // On the other hand, crates compiled with `-C panic=abort` expects that all Rust
156            // functions cannot unwind (whether it's caused by Rust panic or foreign exception),
157            // and this expectation mismatch can cause unsoundness (#96926).
158            //
159            // To address this issue, we enforce that if FFI-unwind calls are used in a crate
160            // compiled with `panic=unwind`, then the final panic strategy must be `panic=unwind`.
161            // This will ensure that no crates will have wrong unwindability assumption.
162            //
163            // It should be noted that it is okay to link `panic=unwind` into a `panic=abort`
164            // program if it contains no FFI-unwind calls. In such case foreign exception can only
165            // enter Rust in a `panic=abort` crate, which will lead to an abort. There will also
166            // be no exceptions generated from Rust, so the assumption which `panic=abort` crates
167            // make, that no Rust function can unwind, indeed holds for crates compiled with
168            // `panic=unwind` as well. In such case this function returns `None`, indicating that
169            // the crate does not require a particular final panic strategy, and can be freely
170            // linked to crates with either strategy (we need such ability for libstd and its
171            // dependencies).
172            return Some(PanicStrategy::Unwind);
173        }
174    }
175
176    // This crate can be linked with either runtime.
177    None
178}
179
180pub(crate) fn provide(providers: &mut Providers) {
181    *providers = Providers { has_ffi_unwind_calls, required_panic_strategy, ..*providers };
182}