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;
1112use crate::diagnostics;
1314// 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:?})");
1718// Only perform check on functions because constants cannot call FFI functions.
19let def_id = local_def_id.to_def_id();
20let kind = tcx.def_kind(def_id);
21if !kind.is_fn_like() {
22return false;
23 }
2425let body_ty = tcx.type_of(def_id).skip_binder();
26let 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 };
34let body_can_unwind = layout::fn_can_unwind(tcx, Some(def_id), body_abi);
3536// Foreign unwinds cannot leak past functions that themselves cannot unwind.
37if !body_can_unwind {
38return false;
39 }
4041// Intrinsics without a body can't be checked and we must instead rely on the signature.
42if tcx.is_intrinsic_that_must_be_overridden(def_id) {
43return false;
44 }
4546let body = &*tcx.mir_built(local_def_id).borrow();
4748let mut tainted = false;
4950for block in body.basic_blocks.iter() {
51if block.is_cleanup {
52continue;
53 }
54let terminator = &block.terminator;
5556if let TerminatorKind::InlineAsm { options, .. } = &terminator.kind {
57if 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.
6364let lint_root = body.source_scopes[terminator.source_info.scope]
65 .local_data
66 .as_ref()
67 .unwrap_crate_local()
68 .lint_root;
69let span = terminator.source_info.span;
7071 tcx.emit_node_span_lint(
72 FFI_UNWIND_CALLS,
73 lint_root,
74 span,
75 diagnostics::AsmUnwindCall { span },
76 );
7778 tainted = true;
79 }
80continue;
81 }
8283let TerminatorKind::Call { func, .. } = &terminator.kind else { continue };
8485let ty = func.ty(body, tcx);
86let abi = ty.fn_sig_abi(tcx);
8788// Rust calls cannot themselves create foreign unwinds.
89 // We assume this is true for intrinsics as well.
90if abi.is_rustic_abi() {
91continue;
92 }
9394let 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.
100if !tcx.is_foreign_item(def_id) {
101continue;
102 }
103Some(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 };
107108if 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.
114115let lint_root = body.source_scopes[terminator.source_info.scope]
116 .local_data
117 .as_ref()
118 .unwrap_crate_local()
119 .lint_root;
120let span = terminator.source_info.span;
121122let 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 );
129130 tainted = true;
131 }
132 }
133134tainted135}
136137fn required_panic_strategy(tcx: TyCtxt<'_>, _: LocalCrate) -> Option<PanicStrategy> {
138let local_strategy = tcx.sess.panic_strategy();
139140if tcx.is_panic_runtime(LOCAL_CRATE) {
141return Some(local_strategy);
142 }
143144match local_strategy {
145 PanicStrategy::Abort | PanicStrategy::ImmediateAbort => return Some(local_strategy),
146_ => {}
147 }
148149for def_id in tcx.hir_body_owners() {
150if 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).
172return Some(PanicStrategy::Unwind);
173 }
174 }
175176// This crate can be linked with either runtime.
177None178}
179180pub(crate) fn provide(providers: &mut Providers) {
181*providers = Providers { has_ffi_unwind_calls, required_panic_strategy, ..*providers };
182}