diff --git a/compiler/rustc_attr_ir/src/lang_items.rs b/compiler/rustc_attr_ir/src/lang_items.rs index d8a2a54566be8..2987b46940f25 100644 --- a/compiler/rustc_attr_ir/src/lang_items.rs +++ b/compiler/rustc_attr_ir/src/lang_items.rs @@ -342,6 +342,9 @@ language_item_table! { /// libstd panic entry point. Necessary for const eval to be able to catch it BeginPanic, sym::begin_panic, begin_panic_fn, Target::Fn, GenericRequirement::None; + /// If this lang item is present, the `abort_immediate` intrinsic lowers to a call to it at runtime. + CrashImpl, sym::crash_impl, crash_impl, Target::Fn, GenericRequirement::Exact(0); + // Lang items needed for `format_args!()`. FormatArgument, sym::format_argument, format_argument, Target::Struct, GenericRequirement::None; FormatArguments, sym::format_arguments, format_arguments, Target::Struct, GenericRequirement::None; diff --git a/compiler/rustc_codegen_cranelift/src/inline_asm.rs b/compiler/rustc_codegen_cranelift/src/inline_asm.rs index c13af35f94108..d1427fb9bbf55 100644 --- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs @@ -47,14 +47,6 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>( options: InlineAsmOptions, destination: Option, ) { - // Used by panic_abort on Windows, but uses a syntax which only happens to work with - // asm!() by accident and breaks with the GNU assembler as well as global_asm!() for - // the LLVM backend. - if template.len() == 1 && template[0] == InlineAsmTemplatePiece::String("int $$0x29".into()) { - fx.bcx.ins().trap(TrapCode::user(2).unwrap()); - return; - } - if fx.tcx.sess.target.arch == Arch::S390x && template.len() == 3 && template[0] == InlineAsmTemplatePiece::String("stfle 0(".into()) diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index d2e5a4e6661e2..44ac0abff87f0 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -342,7 +342,20 @@ fn codegen_regular_intrinsic_call<'tcx>( match intrinsic { sym::abort_immediate => { fx.bcx.set_cold_block(fx.bcx.current_block().unwrap()); - fx.bcx.ins().trap(TrapCode::user(2).unwrap()); + if let Some(def_id) = fx.tcx.lang_items().crash_impl() { + let instance = Instance::mono(fx.tcx, def_id); + let func_ref = fx.get_function_ref(instance); + codegen_call_with_unwind_action( + fx, + source_info.span, + CallTarget::Direct(func_ref), + UnwindAction::Unreachable, + &[], + None, + ); + } else { + fx.bcx.ins().trap(TrapCode::user(2).unwrap()); + } return Ok(()); } sym::breakpoint | sym::resumable_breakpoint => { diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 32ed80437ed95..43eca5031daf4 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -602,7 +602,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc } } - fn abort_immediate(&mut self) { + fn abort_immediate_impl(&mut self) { let func = self.context.get_builtin_function("__builtin_trap"); self.block.add_eval(self.location, self.context.new_call(self.location, func, &[])); } diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index ebaeb8895e4d4..c2036cbcf9913 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -2090,6 +2090,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { self.unreachable(); } } else { + // FIXME use `__fastfail(FAST_FAIL_GUARD_ICALL_CHECK_FAILURE)` on Windows self.abort_immediate(); self.unreachable(); } diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 1052f2be7c6c9..ec2133cda7075 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -1098,7 +1098,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } - fn abort_immediate(&mut self) { + fn abort_immediate_impl(&mut self) { self.call_intrinsic("llvm.trap", &[], &[]); } diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 9acfad1fb2a5e..bcd79da2fc593 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -2,14 +2,14 @@ use std::ops::Deref; use rustc_abi::{Align, Scalar, Size, WrappingRange}; use rustc_ast::expand::typetree::{FncTree, TypeTree}; -use rustc_attr_ir::UnrollAttr; +use rustc_attr_ir::{LangItem, UnrollAttr}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::mir; use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; use rustc_middle::ty::typetree::typetree_from_ty; use rustc_middle::ty::{AtomicOrdering, Instance, Ty}; use rustc_session::config::OptLevel; -use rustc_span::Span; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::callconv::FnAbi; use super::abi::AbiBuilderMethods; @@ -22,7 +22,9 @@ use super::misc::MiscCodegenMethods; use super::type_::{ArgAbiBuilderMethods, BaseTypeCodegenMethods, LayoutTypeCodegenMethods}; use super::{CodegenMethods, StaticBuilderMethods}; use crate::MemFlags; -use crate::common::{AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope}; +use crate::common::{ + AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope, build_langcall, +}; use crate::mir::operand::{OperandRef, OperandValue}; use crate::mir::place::{PlaceRef, PlaceValue}; @@ -685,4 +687,23 @@ pub trait BuilderMethods<'a, 'tcx>: fn zext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn apply_attrs_to_cleanup_callsite(&mut self, llret: Self::Value); + + fn abort_immediate(&mut self) { + if self.tcx().lang_items().crash_impl().is_some() { + let (fn_abi, fn_val, instance) = build_langcall(self, DUMMY_SP, LangItem::CrashImpl); + let fn_ty = self.fn_decl_backend_type(fn_abi); + self.call( + fn_ty, + None, + Some(fn_abi), + fn_val, + ReturnSlot::Direct, + &[], + None, + Some(instance), + ); + } else { + self.abort_immediate_impl(); + } + } } diff --git a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs index 49a8eedc8898b..332c050026c35 100644 --- a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs @@ -39,8 +39,9 @@ pub trait IntrinsicCallBuilderMethods<'tcx>: BackendTypes { is_cleanup: bool, ) -> Self::Value; - /// Ungracefully stop execution in the simplest way possible. - fn abort_immediate(&mut self); + /// Implementation of `abort_immediate` + /// when not overwritten by the `crash_impl` lang item + fn abort_immediate_impl(&mut self); fn assume(&mut self, val: Self::Value); fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value; /// Returns the number of bits set. The return type must be `u32`. diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 19af8d7a1a230..afd374b19e9d8 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -1375,6 +1375,15 @@ fn collect_items_of_instance<'tcx>( for (bb, data) in traversal::mono_reachable(body, tcx, instance) { collector.visit_basic_block_data(bb, data) } + + // The backend may insert calls to this lang item at any time, + // so collect it unconditionally. + if let Some(def_id) = tcx.lang_items().get(LangItem::CrashImpl) { + let crash_impl_instance = Instance::mono(tcx, def_id); + if tcx.should_codegen_locally(crash_impl_instance) { + collector.used_items.push(create_fn_mono_item(tcx, crash_impl_instance, DUMMY_SP)); + } + } } // Always visit all `required_consts`, so that we evaluate them and abort compilation if any of diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d8b7f245f3003..9485d419eb0a5 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -781,6 +781,7 @@ symbols! { coverage, coverage_attribute, cr, + crash_impl, crate_in_paths, crate_local, crate_name, diff --git a/library/core/src/os/windows.rs b/library/core/src/os/windows.rs index 47528f67f6428..1c7e9446aa980 100644 --- a/library/core/src/os/windows.rs +++ b/library/core/src/os/windows.rs @@ -1,6 +1,6 @@ //! Platform-specific extensions to `core` for Windows platforms. -#![unstable(feature = "codeview_annotation", issue = "163964")] +#![unstable(feature = "core_os_windows", issue = "none")] #![doc(cfg(windows))] #[doc(inline)] @@ -21,7 +21,7 @@ pub use crate::intrinsics::CodeViewAnnotationArgs; /// #[cfg_attr(windows, doc = "```")] #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] -/// #![feature(codeview_annotation, core_os)] +/// #![feature(codeview_annotation, core_os, core_os_windows)] /// use core::os::windows::{codeview_annotation, CodeViewAnnotationArgs}; /// /// struct Args; @@ -37,3 +37,47 @@ pub use crate::intrinsics::CodeViewAnnotationArgs; pub fn codeview_annotation() { crate::intrinsics::codeview_annotation::(); } + +/// Use [`__fastfail`] to abort the process with the specified error code. +/// +/// In Windows 8 and later, this will terminate the process immediately without +/// running any in-process exception handlers. In earlier versions of Windows, +/// this sequence of instructions will be treated as an access violation, which +/// will still terminate the process but might run some exception handlers. +/// +/// See [Microsoft's documentation][`__fastfail`] for more information. +/// +/// [`__fastfail`]: https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail +#[inline(always)] +#[unstable(feature = "windows_fastfail", issue = "none")] +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +pub fn __fastfail(code: crate::ffi::c_uint) -> ! { + // SAFETY: These assembly sequences are documented at + // + unsafe { + cfg_select! { + // Miri does not support inline assembly + any(miri, doc) => crate::intrinsics::abort_immediate(), + any(target_arch = "x86", target_arch = "x86_64") => { + crate::arch::asm!("int 0x29", in("ecx") code, options(noreturn, nostack)) + } + all(target_arch = "arm", target_feature = "thumb-mode") => { + crate::arch::asm!(".inst 0xDEFB", in("r0") code, options(noreturn, nostack)) + } + any(target_arch = "aarch64", target_arch = "arm64ec") => { + crate::arch::asm!("brk 0xF003", in("x0") code, options(noreturn, nostack)) + } + } + } +} + +#[cfg(windows)] +#[lang = "crash_impl"] +#[rustc_nounwind] +#[inline(always)] +fn crash_impl() { + /// From `winnt.h` + const FAST_FAIL_FATAL_APP_EXIT: crate::ffi::c_uint = 7; + + __fastfail(FAST_FAIL_FATAL_APP_EXIT) +} diff --git a/library/core/src/process.rs b/library/core/src/process.rs index 2f116992e6d91..6fa1d4682fa87 100644 --- a/library/core/src/process.rs +++ b/library/core/src/process.rs @@ -35,6 +35,11 @@ /// Other signals such as `SIGABRT`, `SIGTRAP`, `SIGSEGV`, and `SIGBUS` may be /// produced instead, depending on specifics. This is not an exhaustive list. /// +/// On Windows, this function is currently equivalent to MSVC's [`__fastfail`] +/// with error code 7 (`FAST_FAIL_FATAL_APP_EXIT`). +/// +/// [`__fastfail`]: https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail +/// /// # Examples /// /// ```no_run @@ -73,10 +78,10 @@ /// // the destructor implemented for HasDrop will never get run /// } /// ``` -/// #[unstable(feature = "abort_immediate", issue = "154601")] #[rustc_const_unstable(feature = "abort_immediate", issue = "154601")] #[cold] +#[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[doc(alias = "halt")] #[doc(alias = "trap")] diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index fc22eaecc0043..5a910e5cf54df 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -317,6 +317,8 @@ // // Library features (core): // tidy-alphabetical-start +#![cfg_attr(windows, feature(core_os_windows))] +#![cfg_attr(windows, feature(windows_fastfail))] #![feature(borrowed_buf_init)] #![feature(byte_str)] #![feature(byte_str_internals)] @@ -333,6 +335,7 @@ #![feature(core_io)] #![feature(core_io_borrowed_buf)] #![feature(core_io_internals)] +#![feature(core_os)] #![feature(cursor_split)] #![feature(derive_const)] #![feature(duration_constants)] diff --git a/library/std/src/os/windows/mod.rs b/library/std/src/os/windows/mod.rs index 507d14765e3fa..ef91d7bb8c3b8 100644 --- a/library/std/src/os/windows/mod.rs +++ b/library/std/src/os/windows/mod.rs @@ -36,8 +36,11 @@ pub mod process; pub mod raw; pub mod thread; -#[unstable(feature = "codeview_annotation", issue = "163964")] #[cfg(windows)] +#[unstable(feature = "windows_fastfail", issue = "none")] +pub use core::os::windows::__fastfail; +#[cfg(windows)] +#[unstable(feature = "codeview_annotation", issue = "163964")] pub use core::os::windows::{CodeViewAnnotationArgs, codeview_annotation}; /// A prelude for conveniently writing platform-specific code. diff --git a/library/std/src/sys/pal/windows/c/bindings.txt b/library/std/src/sys/pal/windows/c/bindings.txt index 1c7035028e83f..31efcee2a7221 100644 --- a/library/std/src/sys/pal/windows/c/bindings.txt +++ b/library/std/src/sys/pal/windows/c/bindings.txt @@ -1967,7 +1967,6 @@ EXTENDED_STARTUPINFO_PRESENT FACILITY_NT_BIT FALSE FARPROC -FAST_FAIL_FATAL_APP_EXIT FD_SET FILE_ADD_FILE FILE_ADD_SUBDIRECTORY diff --git a/library/std/src/sys/pal/windows/c/windows_sys.rs b/library/std/src/sys/pal/windows/c/windows_sys.rs index 131d410edc9ad..e11ff06e960ea 100644 --- a/library/std/src/sys/pal/windows/c/windows_sys.rs +++ b/library/std/src/sys/pal/windows/c/windows_sys.rs @@ -2445,7 +2445,6 @@ pub const ExceptionNestedException: EXCEPTION_DISPOSITION = 2; pub const FACILITY_NT_BIT: i32 = 268435456; pub const FALSE: i32 = 0; pub type FARPROC = Option isize>; -pub const FAST_FAIL_FATAL_APP_EXIT: i32 = 7; pub type FD_SET = fd_set; #[repr(C)] #[derive(Clone, Copy, Default)] diff --git a/library/std/src/sys/pal/windows/mod.rs b/library/std/src/sys/pal/windows/mod.rs index 0f79a4b09000e..599e7d29168f8 100644 --- a/library/std/src/sys/pal/windows/mod.rs +++ b/library/std/src/sys/pal/windows/mod.rs @@ -253,39 +253,8 @@ pub fn dur2timeout(dur: Duration) -> u32 { .unwrap_or(c::INFINITE) } -/// Use `__fastfail` to abort the process -/// -/// In Windows 8 and later, this will terminate the process immediately without -/// running any in-process exception handlers. In earlier versions of Windows, -/// this sequence of instructions will be treated as an access violation, which -/// will still terminate the process but might run some exception handlers. -/// -/// -#[cfg(not(miri))] // inline assembly does not work in Miri -pub fn abort_internal() -> ! { - unsafe { - cfg_select! { - any(target_arch = "x86", target_arch = "x86_64") => { - core::arch::asm!("int $$0x29", in("ecx") c::FAST_FAIL_FATAL_APP_EXIT, options(noreturn, nostack)); - } - all(target_arch = "arm", target_feature = "thumb-mode") => { - core::arch::asm!(".inst 0xDEFB", in("r0") c::FAST_FAIL_FATAL_APP_EXIT, options(noreturn, nostack)); - } - any(target_arch = "aarch64", target_arch = "arm64ec") => { - core::arch::asm!("brk 0xF003", in("x0") c::FAST_FAIL_FATAL_APP_EXIT, options(noreturn, nostack)); - } - _ => { - core::intrinsics::abort_immediate(); - } - } - } -} - -#[cfg(miri)] -#[track_caller] // even without panics, this helps for Miri backtraces -pub fn abort_internal() -> ! { - crate::intrinsics::abort_immediate(); -} +// Uses `__fastfail` to abort the process +pub use crate::process::crash as abort_internal; /// Align the inner value to 8 bytes. /// diff --git a/tests/assembly-llvm/win-fastfail.rs b/tests/assembly-llvm/win-fastfail.rs new file mode 100644 index 0000000000000..0af9b8c427696 --- /dev/null +++ b/tests/assembly-llvm/win-fastfail.rs @@ -0,0 +1,29 @@ +//@ assembly-output: emit-asm +//@ only-windows + +//@ revisions: i686 x86_64 aarch64 arm64ec +//@[i686] only-x86 +//@[x86_64] only-x86_64 +//@[aarch64] only-aarch64 +//@[arm64ec] only-arm64ec + +#![feature(abort_immediate)] +#![no_std] +#![crate_type = "lib"] + +// CHECK-LABEL: my_abort: +#[unsafe(no_mangle)] +extern "C" fn my_abort() { + // i686: movl $7, %ecx + // i686: int $41 + + // x86_64: movl $7, %ecx + // x86_64: int $41 + + // aarch64: mov w0, #7 + // aarch64: brk #0xf003 + + // arm64ec: mov w0, #7 + // arm64ec: brk #0xf003 + core::process::crash() +}