rust/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

177 lines
6.8 KiB
Rust
Raw Normal View History

2023-03-13 18:54:05 +00:00
use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE};
use rustc_middle::mir::*;
2023-03-13 22:22:59 +00:00
use rustc_middle::query::LocalCrate;
use rustc_middle::query::Providers;
use rustc_middle::ty::layout;
use rustc_middle::ty::{self, TyCtxt};
use rustc_session::lint::builtin::FFI_UNWIND_CALLS;
use rustc_target::spec::abi::Abi;
use rustc_target::spec::PanicStrategy;
use crate::errors;
/// Some of the functions declared as "may unwind" by `fn_can_unwind` can't actually unwind. In
/// particular, `extern "C"` is still considered as can-unwind on stable, but we need to consider
/// it cannot-unwind here. So below we check `fn_can_unwind() && abi_can_unwind()` before concluding
/// that a function call can unwind.
fn abi_can_unwind(abi: Abi) -> bool {
use Abi::*;
match abi {
C { unwind }
| System { unwind }
| Cdecl { unwind }
| Stdcall { unwind }
| Fastcall { unwind }
| Vectorcall { unwind }
| Thiscall { unwind }
| Aapcs { unwind }
| Win64 { unwind }
| SysV64 { unwind } => unwind,
PtxKernel
| Msp430Interrupt
| X86Interrupt
| EfiApi
| AvrInterrupt
| AvrNonBlockingInterrupt
feat: `riscv-interrupt-{m,s}` calling conventions Similar to prior support added for the mips430, avr, and x86 targets this change implements the rough equivalent of clang's [`__attribute__((interrupt))`][clang-attr] for riscv targets, enabling e.g. ```rust static mut CNT: usize = 0; pub extern "riscv-interrupt-m" fn isr_m() { unsafe { CNT += 1; } } ``` to produce highly effective assembly like: ```asm pub extern "riscv-interrupt-m" fn isr_m() { 420003a0: 1141 addi sp,sp,-16 unsafe { CNT += 1; 420003a2: c62a sw a0,12(sp) 420003a4: c42e sw a1,8(sp) 420003a6: 3fc80537 lui a0,0x3fc80 420003aa: 63c52583 lw a1,1596(a0) # 3fc8063c <_ZN12esp_riscv_rt3CNT17hcec3e3a214887d53E.0> 420003ae: 0585 addi a1,a1,1 420003b0: 62b52e23 sw a1,1596(a0) } } 420003b4: 4532 lw a0,12(sp) 420003b6: 45a2 lw a1,8(sp) 420003b8: 0141 addi sp,sp,16 420003ba: 30200073 mret ``` (disassembly via `riscv64-unknown-elf-objdump -C -S --disassemble ./esp32c3-hal/target/riscv32imc-unknown-none-elf/release/examples/gpio_interrupt`) This outcome is superior to hand-coded interrupt routines which, lacking visibility into any non-assembly body of the interrupt handler, have to be very conservative and save the [entire CPU state to the stack frame][full-frame-save]. By instead asking LLVM to only save the registers that it uses, we defer the decision to the tool with the best context: it can more accurately account for the cost of spills if it knows that every additional register used is already at the cost of an implicit spill. At the LLVM level, this is apparently [implemented by] marking every register as "[callee-save]," matching the semantics of an interrupt handler nicely (it has to leave the CPU state just as it found it after its `{m|s}ret`). This approach is not suitable for every interrupt handler, as it makes no attempt to e.g. save the state in a user-accessible stack frame. For a full discussion of those challenges and tradeoffs, please refer to [the interrupt calling conventions RFC][rfc]. Inside rustc, this implementation differs from prior art because LLVM does not expose the "all-saved" function flavor as a calling convention directly, instead preferring to use an attribute that allows for differentiating between "machine-mode" and "superivsor-mode" interrupts. Finally, some effort has been made to guide those who may not yet be aware of the differences between machine-mode and supervisor-mode interrupts as to why no `riscv-interrupt` calling convention is exposed through rustc, and similarly for why `riscv-interrupt-u` makes no appearance (as it would complicate future LLVM upgrades). [clang-attr]: https://clang.llvm.org/docs/AttributeReference.html#interrupt-risc-v [full-frame-save]: https://github.com/esp-rs/esp-riscv-rt/blob/9281af2ecffe13e40992917316f36920c26acaf3/src/lib.rs#L440-L469 [implemented by]: https://github.com/llvm/llvm-project/blob/b7fb2a3fec7c187d58a6d338ab512d9173bca987/llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp#L61-L67 [callee-save]: https://github.com/llvm/llvm-project/blob/973f1fe7a8591c7af148e573491ab68cc15b6ecf/llvm/lib/Target/RISCV/RISCVCallingConv.td#L30-L37 [rfc]: https://github.com/rust-lang/rfcs/pull/3246
2023-05-23 15:08:23 -07:00
| RiscvInterruptM
| RiscvInterruptS
| CCmseNonSecureCall
| Wasm
| Unadjusted => false,
RustIntrinsic | Rust | RustCall | RustCold => unreachable!(), // these ABIs are already skipped earlier
}
}
// Check if the body of this def_id can possibly leak a foreign unwind into Rust code.
fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool {
debug!("has_ffi_unwind_calls({local_def_id:?})");
// Only perform check on functions because constants cannot call FFI functions.
let def_id = local_def_id.to_def_id();
let kind = tcx.def_kind(def_id);
if !kind.is_fn_like() {
return false;
}
2022-05-08 15:53:19 +02:00
let body = &*tcx.mir_built(local_def_id).borrow();
let body_ty = tcx.type_of(def_id).skip_binder();
let body_abi = match body_ty.kind() {
ty::FnDef(..) => body_ty.fn_sig(tcx).abi(),
ty::Closure(..) => Abi::RustCall,
ty::CoroutineClosure(..) => Abi::RustCall,
2023-10-19 16:06:43 +00:00
ty::Coroutine(..) => Abi::Rust,
ty::Error(_) => return false,
_ => span_bug!(body.span, "unexpected body ty: {:?}", body_ty),
};
let body_can_unwind = layout::fn_can_unwind(tcx, Some(def_id), body_abi);
// Foreign unwinds cannot leak past functions that themselves cannot unwind.
if !body_can_unwind {
return false;
}
let mut tainted = false;
for block in body.basic_blocks.iter() {
if block.is_cleanup {
continue;
}
let Some(terminator) = &block.terminator else { continue };
let TerminatorKind::Call { func, .. } = &terminator.kind else { continue };
let ty = func.ty(body, tcx);
let sig = ty.fn_sig(tcx);
// Rust calls cannot themselves create foreign unwinds.
// We assume this is true for intrinsics as well.
if let Abi::RustIntrinsic | Abi::Rust | Abi::RustCall | Abi::RustCold = sig.abi() {
continue;
};
let fn_def_id = match ty.kind() {
ty::FnPtr(_) => None,
&ty::FnDef(def_id, _) => {
// Rust calls cannot themselves create foreign unwinds (even if they use a non-Rust ABI).
// So the leak of the foreign unwind into Rust can only be elsewhere, not here.
if !tcx.is_foreign_item(def_id) {
continue;
}
Some(def_id)
}
_ => bug!("invalid callee of type {:?}", ty),
};
if layout::fn_can_unwind(tcx, fn_def_id, sig.abi()) && abi_can_unwind(sig.abi()) {
// We have detected a call that can possibly leak foreign unwind.
//
// Because the function body itself can unwind, we are not aborting this function call
// upon unwind, so this call can possibly leak foreign unwind into Rust code if the
// panic runtime linked is panic-abort.
let lint_root = body.source_scopes[terminator.source_info.scope]
.local_data
.as_ref()
.assert_crate_local()
.lint_root;
let span = terminator.source_info.span;
let foreign = fn_def_id.is_some();
tcx.emit_node_span_lint(
FFI_UNWIND_CALLS,
lint_root,
span,
errors::FfiUnwindCall { span, foreign },
);
tainted = true;
}
}
tainted
}
2023-03-13 22:22:59 +00:00
fn required_panic_strategy(tcx: TyCtxt<'_>, _: LocalCrate) -> Option<PanicStrategy> {
2022-05-19 17:38:54 +01:00
if tcx.is_panic_runtime(LOCAL_CRATE) {
return Some(tcx.sess.panic_strategy());
}
if tcx.sess.panic_strategy() == PanicStrategy::Abort {
return Some(PanicStrategy::Abort);
}
for def_id in tcx.hir().body_owners() {
if tcx.has_ffi_unwind_calls(def_id) {
// Given that this crate is compiled in `-C panic=unwind`, the `AbortUnwindingCalls`
// MIR pass will not be run on FFI-unwind call sites, therefore a foreign exception
// can enter Rust through these sites.
//
// On the other hand, crates compiled with `-C panic=abort` expects that all Rust
// functions cannot unwind (whether it's caused by Rust panic or foreign exception),
// and this expectation mismatch can cause unsoundness (#96926).
//
// To address this issue, we enforce that if FFI-unwind calls are used in a crate
// compiled with `panic=unwind`, then the final panic strategy must be `panic=unwind`.
// This will ensure that no crates will have wrong unwindability assumption.
//
// It should be noted that it is okay to link `panic=unwind` into a `panic=abort`
// program if it contains no FFI-unwind calls. In such case foreign exception can only
// enter Rust in a `panic=abort` crate, which will lead to an abort. There will also
// be no exceptions generated from Rust, so the assumption which `panic=abort` crates
// make, that no Rust function can unwind, indeed holds for crates compiled with
// `panic=unwind` as well. In such case this function returns `None`, indicating that
// the crate does not require a particular final panic strategy, and can be freely
// linked to crates with either strategy (we need such ability for libstd and its
// dependencies).
return Some(PanicStrategy::Unwind);
}
}
// This crate can be linked with either runtime.
None
}
pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers { has_ffi_unwind_calls, required_panic_strategy, ..*providers };
}