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_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 2f57ecdaa6f19..e41613426f7ab 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_ssa/src/traits/intrinsic.rs b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs index 530597c616ff9..c71135e428c33 100644 --- a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs @@ -38,7 +38,12 @@ pub trait IntrinsicCallBuilderMethods<'tcx>: BackendTypes { is_cleanup: bool, ) -> Self::Value; - /// Ungracefully stop execution in the simplest way possible. + /// Ungracefully stop execution in the simplest way possible + /// that uses the fewest instructions. + /// Use this when [`super::BuilderMethods::unreachable`] would also work + /// but you want to be nice. + /// Prefer e.g. [`core::process::crash`] when the abort is meant to be + /// a user-visible guarantee. fn abort_immediate(&mut self); fn assume(&mut self, val: Self::Value); fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value; diff --git a/library/alloc/src/collections/btree/mem.rs b/library/alloc/src/collections/btree/mem.rs index c9a1ec8ca63c6..1afda4127f3b7 100644 --- a/library/alloc/src/collections/btree/mem.rs +++ b/library/alloc/src/collections/btree/mem.rs @@ -1,4 +1,4 @@ -use core::{intrinsics, mem, ptr}; +use core::{mem, process, ptr}; /// This replaces the value behind the `v` unique reference by calling the /// relevant function. @@ -19,7 +19,7 @@ pub(super) fn replace(v: &mut T, change: impl FnOnce(T) -> (T, R)) -> R { struct PanicGuard; impl Drop for PanicGuard { fn drop(&mut self) { - intrinsics::abort_immediate() + process::crash() } } let guard = PanicGuard; diff --git a/library/alloc/src/collections/btree/split.rs b/library/alloc/src/collections/btree/split.rs index fde6810ed4143..370d061aae203 100644 --- a/library/alloc/src/collections/btree/split.rs +++ b/library/alloc/src/collections/btree/split.rs @@ -1,6 +1,6 @@ use core::alloc::AllocatorClone; use core::borrow::Borrow; -use core::{intrinsics, mem}; +use core::{mem, process}; use super::node::ForceResult::*; use super::node::Root; @@ -61,7 +61,7 @@ impl Root { // A panic from a later `search_node` comparison would unwind out of // that state and double-free the shared values (#158165), so abort // instead of exposing it. - let guard = mem::DropGuard::new((), |()| intrinsics::abort_immediate()); + let guard = mem::DropGuard::new((), |()| process::crash()); loop { split_edge.move_suffix(&mut right_node); diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 7bd8dac3f6084..68d9a5f48b373 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -89,6 +89,10 @@ // // Library features: // tidy-alphabetical-start +#![cfg_attr(windows, feature(core_os))] +#![cfg_attr(windows, feature(core_os_windows))] +#![cfg_attr(windows, feature(windows_fastfail))] +#![feature(abort_immediate)] #![feature(allocator_ext)] #![feature(array_into_iter_constructors)] #![feature(ascii_char)] diff --git a/library/alloc/src/raw_vec/mod.rs b/library/alloc/src/raw_vec/mod.rs index 2f284bb4229eb..32d74ce045d96 100644 --- a/library/alloc/src/raw_vec/mod.rs +++ b/library/alloc/src/raw_vec/mod.rs @@ -25,6 +25,7 @@ mod tests; // only one location which panics rather than a bunch throughout the module. #[cfg(not(no_global_oom_handling))] #[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] const fn capacity_overflow() -> ! { panic!("capacity overflow"); } diff --git a/library/alloc/src/rcs/arc.rs b/library/alloc/src/rcs/arc.rs index b76001e55ae65..8156806cf34ef 100644 --- a/library/alloc/src/rcs/arc.rs +++ b/library/alloc/src/rcs/arc.rs @@ -20,7 +20,7 @@ use core::ptr::{self, NonNull}; use core::slice::from_raw_parts_mut; use core::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use core::sync::atomic::{self, Atomic}; -use core::{borrow, fmt, hint, intrinsics}; +use core::{borrow, fmt, hint}; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -29,7 +29,7 @@ use crate::alloc::{ }; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; -use crate::rc::is_dangling; +use crate::rc::{crash_for_invalid_refcount, is_dangling}; #[cfg(not(no_global_oom_handling))] use crate::string::String; #[cfg(not(no_global_oom_handling))] @@ -2541,7 +2541,7 @@ impl Clone for Arc { // Otherwise, the counter could be brought to an almost-overflow using a compare-exchange loop, // and then overflow using a few `fetch_add`s. if old_size > MAX_REFCOUNT { - intrinsics::abort_immediate(); + crash_for_invalid_refcount() } // SAFETY: Pointer is valid & allocator corresponds to the one used to allocate it. @@ -3595,7 +3595,7 @@ impl Clone for Weak { // See comments in Arc::clone() for why we do this (for mem::forget). if old_size > MAX_REFCOUNT { - intrinsics::abort_immediate(); + crash_for_invalid_refcount() } } @@ -5073,7 +5073,7 @@ impl UniqueArc { // See comments in Arc::clone() for why we do this (for mem::forget). if old_size > MAX_REFCOUNT { - intrinsics::abort_immediate(); + crash_for_invalid_refcount() } Weak { ptr: this.ptr, alloc: this.alloc.clone() } diff --git a/library/alloc/src/rcs/rc.rs b/library/alloc/src/rcs/rc.rs index 1874441f3f920..ff9546cebd0e9 100644 --- a/library/alloc/src/rcs/rc.rs +++ b/library/alloc/src/rcs/rc.rs @@ -3436,6 +3436,23 @@ pub(crate) fn is_dangling(ptr: *const T) -> bool { (ptr.cast::<()>()).addr() == usize::MAX } +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cold] +#[inline] +pub(super) fn crash_for_invalid_refcount() -> ! { + cfg_select! { + windows => { + // `core::process::crash()` crashes with `FAST_FAIL_FATAL_APP_EXIT`, + // but in this case we can use a more specific error code + + /// From `winnt.h` + const FAST_FAIL_INVALID_REFERENCE_COUNT: core::ffi::c_uint = 14; + core::os::windows::__fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT) + } + _ => core::process::crash(), + } +} + /// Helper type to allow accessing the reference counts without /// making any assertions about the data field. struct WeakInner<'a> { @@ -3951,7 +3968,7 @@ trait RcInnerPtr { // Checking for overflow after the store instead of before // allows for slightly better code generation. if intrinsics::unlikely(strong == 0) { - intrinsics::abort_immediate(); + crash_for_invalid_refcount() } } @@ -3984,7 +4001,7 @@ trait RcInnerPtr { // Checking for overflow after the store instead of before // allows for slightly better code generation. if intrinsics::unlikely(weak == 0) { - intrinsics::abort_immediate(); + crash_for_invalid_refcount() } } diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 0458c27ecf5a9..8c7c2caa70ed6 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -2181,6 +2181,7 @@ impl Vec { pub fn swap_remove(&mut self, index: usize) -> T { #[cold] #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[cfg_attr(panic = "immediate-abort", inline)] #[optimize(size)] fn assert_failed(index: usize, len: usize) -> ! { panic!("swap_remove index (is {index}) should be < len (is {len})"); @@ -2262,6 +2263,7 @@ impl Vec { pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T { #[cold] #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] #[optimize(size)] fn assert_failed(index: usize, len: usize) -> ! { @@ -2327,6 +2329,7 @@ impl Vec { pub fn remove(&mut self, index: usize) -> T { #[cold] #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] #[optimize(size)] fn assert_failed(index: usize, len: usize) -> ! { @@ -3226,6 +3229,7 @@ impl Vec { { #[cold] #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] #[optimize(size)] fn assert_failed(at: usize, len: usize) -> ! { diff --git a/library/alloctests/lib.rs b/library/alloctests/lib.rs index e5179bf489ecc..bf3276501ec31 100644 --- a/library/alloctests/lib.rs +++ b/library/alloctests/lib.rs @@ -13,6 +13,7 @@ // // Library features: // tidy-alphabetical-start +#![feature(abort_immediate)] #![feature(allocator_ext)] #![feature(array_into_iter_constructors)] #![feature(char_internals)] @@ -26,7 +27,6 @@ #![feature(const_result_trait_fn)] #![feature(const_try)] #![feature(copied_into_inner)] -#![feature(core_intrinsics)] #![feature(exact_size_is_empty)] #![feature(extend_one)] #![feature(extend_one_unchecked)] diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 515b68de43bfb..1a1096788e7f2 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -912,6 +912,7 @@ impl Display for BorrowMutError { // This ensures the panicking code is outlined from `borrow_mut` for `RefCell`. #[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] #[cold] const fn panic_already_borrowed(err: BorrowMutError) -> ! { @@ -924,6 +925,7 @@ const fn panic_already_borrowed(err: BorrowMutError) -> ! { // This ensures the panicking code is outlined from `borrow` for `RefCell`. #[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] #[cold] const fn panic_already_mutably_borrowed(err: BorrowError) -> ! { diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 0a170fae1e186..f460bb7d57d26 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -617,8 +617,7 @@ pub fn rustc_peek(_: T) -> T; /// Ungracefully aborts the execution of the process. /// -/// This is the intrinsic for directly implementing [`core::process::crash`] which, on most -/// platforms, will invoke an invalid instruction. On Unix, the process will probably terminate with +/// On most platforms, this will invoke an invalid instruction. On Unix, the process will probably terminate with /// a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or `SIGBUS`. The precise behavior is not /// guaranteed and not stable. /// @@ -628,7 +627,10 @@ pub fn rustc_peek(_: T) -> T; /// Note that, unlike most intrinsics, this is safe to call; it does not require an `unsafe` block. /// Therefore, implementations must not require the user to uphold any safety invariants. /// -/// The stabilized version of this intrinsic is [`core::process::crash`]. +/// Used to implement [`core::process::crash`] on most platforms, but not Windows. +/// Prefer that function over this one for "user-visible well-defined immediate abort"; +/// prefer this intrinsic for for contexts where [`unreachable()`] +/// would also have been acceptable. #[rustc_nounwind] #[rustc_intrinsic] pub const fn abort_immediate() -> !; diff --git a/library/core/src/os/windows.rs b/library/core/src/os/windows.rs index 47528f67f6428..f3a0a3e66b58b 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,34 @@ pub use crate::intrinsics::CodeViewAnnotationArgs; pub fn codeview_annotation() { crate::intrinsics::codeview_annotation::(); } + +/// 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. +/// +/// +#[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 + miri => 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)) + } + } + } +} diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 8a5e0f035d775..6621ec2fae26b 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -31,6 +31,8 @@ use crate::fmt; use crate::intrinsics::const_eval_select; use crate::panic::{Location, PanicInfo}; +#[cfg(panic = "immediate-abort")] +use crate::process; #[cfg(feature = "panic_immediate_abort")] compile_error!( @@ -58,26 +60,27 @@ compile_error!( #[rustc_do_not_const_check] // hooked by const-eval #[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() - } - - // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call - // that gets resolved to the `#[panic_handler]` function. - unsafe extern "Rust" { - #[lang = "panic_impl"] - fn panic_impl(pi: &PanicInfo<'_>) -> !; - } + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => { + // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call + // that gets resolved to the `#[panic_handler]` function. + unsafe extern "Rust" { + #[lang = "panic_impl"] + fn panic_impl(pi: &PanicInfo<'_>) -> !; + } - let pi = PanicInfo::new( - &fmt, - Location::caller(), - /* can_unwind */ true, - /* force_no_backtrace */ false, - ); + let pi = PanicInfo::new( + &fmt, + Location::caller(), + /* can_unwind */ true, + /* force_no_backtrace */ false, + ); - // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call. - unsafe { panic_impl(&pi) } + // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call. + unsafe { panic_impl(&pi) } + } + } } /// Like `panic_fmt`, but for non-unwinding panics. @@ -98,28 +101,29 @@ pub const fn panic_nounwind_fmt(fmt: fmt::Arguments<'_>, force_no_backtrace: boo if const #[track_caller] { // We don't unwind anyway at compile-time so we can call the regular `panic_fmt`. panic_fmt(fmt) - } else #[track_caller] { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() - } - - // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call - // that gets resolved to the `#[panic_handler]` function. - unsafe extern "Rust" { - #[lang = "panic_impl"] - fn panic_impl(pi: &PanicInfo<'_>) -> !; + } else #[track_caller] #[cfg_attr(panic = "immediate-abort", inline)] { + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => { + // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call + // that gets resolved to the `#[panic_handler]` function. + unsafe extern "Rust" { + #[lang = "panic_impl"] + fn panic_impl(pi: &PanicInfo<'_>) -> !; + } + + // PanicInfo with the `can_unwind` flag set to false forces an abort. + let pi = PanicInfo::new( + &fmt, + Location::caller(), + /* can_unwind */ false, + force_no_backtrace, + ); + + // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call. + unsafe { panic_impl(&pi) } + } } - - // PanicInfo with the `can_unwind` flag set to false forces an abort. - let pi = PanicInfo::new( - &fmt, - Location::caller(), - /* can_unwind */ false, - force_no_backtrace, - ); - - // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call. - unsafe { panic_impl(&pi) } } ) } @@ -264,11 +268,18 @@ pub const fn panic_display(x: &T) -> ! { #[track_caller] #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access fn panic_bounds_check(index: usize, len: usize) -> ! { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() + cfg_select! { + all(panic = "immediate-abort", windows) => { + // `core::process::crash()` crashes with `FAST_FAIL_FATAL_APP_EXIT`, + // but in this case we can use a more specific error code + + /// From `winnt.h` + const FAST_FAIL_RANGE_CHECK_FAILURE: crate::ffi::c_uint = 8; + crate::os::windows::__fastfail(FAST_FAIL_RANGE_CHECK_FAILURE) + } + panic = "immediate-abort" => process::crash(), + _ => panic!("index out of bounds: the len is {len} but the index is {index}"), } - - panic!("index out of bounds: the len is {len} but the index is {index}") } #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))] @@ -277,16 +288,15 @@ fn panic_bounds_check(index: usize, len: usize) -> ! { #[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref #[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() - } - - panic_nounwind_fmt( - format_args!( - "misaligned pointer dereference: address must be a multiple of {required:#x} but is {found:#x}" + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => panic_nounwind_fmt( + format_args!( + "misaligned pointer dereference: address must be a multiple of {required:#x} but is {found:#x}" + ), + /* force_no_backtrace */ false, ), - /* force_no_backtrace */ false, - ) + } } #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))] @@ -295,14 +305,13 @@ fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! { #[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref #[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind fn panic_null_pointer_dereference() -> ! { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => panic_nounwind_fmt( + format_args!("null pointer dereference occurred"), + /* force_no_backtrace */ false, + ), } - - panic_nounwind_fmt( - format_args!("null pointer dereference occurred"), - /* force_no_backtrace */ false, - ) } #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))] @@ -311,11 +320,13 @@ fn panic_null_pointer_dereference() -> ! { #[lang = "panic_null_reference_constructed"] // needed by codegen for panic on null reference formation #[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind fn panic_null_reference_constructed() -> ! { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => panic_nounwind_fmt( + format_args!("null reference produced"), + /* force_no_backtrace */ false, + ), } - - panic_nounwind_fmt(format_args!("null reference produced"), /* force_no_backtrace */ false) } #[cfg_attr(not(panic = "immediate-abort"), inline(never), cold, optimize(size))] @@ -324,14 +335,13 @@ fn panic_null_reference_constructed() -> ! { #[lang = "panic_invalid_enum_construction"] // needed by codegen for panic on invalid enum construction. #[rustc_nounwind] // `CheckEnums` MIR pass requires this function to never unwind fn panic_invalid_enum_construction(source: u128) -> ! { - if cfg!(panic = "immediate-abort") { - super::intrinsics::abort_immediate() + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => panic_nounwind_fmt( + format_args!("trying to construct an enum from an invalid value {source:#x}"), + /* force_no_backtrace */ false, + ), } - - panic_nounwind_fmt( - format_args!("trying to construct an enum from an invalid value {source:#x}"), - /* force_no_backtrace */ false, - ) } /// Panics because we cannot unwind out of a function. diff --git a/library/core/src/process.rs b/library/core/src/process.rs index 2f116992e6d91..fa744f2989287 100644 --- a/library/core/src/process.rs +++ b/library/core/src/process.rs @@ -77,11 +77,30 @@ #[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")] pub const fn crash() -> ! { - crate::intrinsics::abort_immediate() + cfg_select! { + windows => { + #[inline] + #[cfg_attr(miri, track_caller)] + fn fastfail_fatal_app_exit() -> ! { + /// From `winnt.h` + const FAST_FAIL_FATAL_APP_EXIT: crate::ffi::c_uint = 7; + + crate::os::windows::__fastfail(FAST_FAIL_FATAL_APP_EXIT) + } + + crate::intrinsics::const_eval_select( + (), + crate::intrinsics::abort_immediate, + fastfail_fatal_app_exit, + ) + } + _ => crate::intrinsics::abort_immediate(), + } } /// Triggers a debugger breakpoint, pausing execution if possible. diff --git a/library/core/src/slice/sort/shared/mod.rs b/library/core/src/slice/sort/shared/mod.rs index e1977d79f3207..ca6e909160df5 100644 --- a/library/core/src/slice/sort/shared/mod.rs +++ b/library/core/src/slice/sort/shared/mod.rs @@ -45,3 +45,20 @@ pub(crate) fn find_existing_run bool>( (run_len, strictly_descending) } } + +#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces +#[cold] +#[inline] +pub(super) fn crash_for_invalid_arg() { + cfg_select! { + windows => { + // `core::process::crash()` crashes with `FAST_FAIL_FATAL_APP_EXIT`, + // but in this case we can use a more specific error code + + /// From `winnt.h` + const FAST_FAIL_INVALID_ARG: crate::ffi::c_uint = 5; + crate::os::windows::__fastfail(FAST_FAIL_INVALID_ARG) + } + _ => core::process::crash(), + } +} diff --git a/library/core/src/slice/sort/shared/pivot.rs b/library/core/src/slice/sort/shared/pivot.rs index 878ec27419fc2..b30d38d3fb34f 100644 --- a/library/core/src/slice/sort/shared/pivot.rs +++ b/library/core/src/slice/sort/shared/pivot.rs @@ -1,6 +1,6 @@ //! This module contains the logic for pivot selection. -use crate::{hint, intrinsics}; +use crate::hint; // Recursively select a pseudomedian if above this threshold. const PSEUDO_MEDIAN_REC_THRESHOLD: usize = 64; @@ -17,7 +17,7 @@ pub fn choose_pivot bool>(v: &[T], is_less: &mut F) -> us let len = v.len(); if len < 8 { - intrinsics::abort_immediate(); + super::crash_for_invalid_arg(); } // SAFETY: a, b, c point to initialized regions of len_div_8 elements, diff --git a/library/core/src/slice/sort/shared/smallsort.rs b/library/core/src/slice/sort/shared/smallsort.rs index 1510c3d6d8d6c..650a3cc2dacf5 100644 --- a/library/core/src/slice/sort/shared/smallsort.rs +++ b/library/core/src/slice/sort/shared/smallsort.rs @@ -228,7 +228,7 @@ fn small_sort_general_with_scratch bool>( } if scratch.len() < len + 16 { - intrinsics::abort_immediate(); + super::crash_for_invalid_arg(); } let v_base = v.as_mut_ptr(); @@ -321,7 +321,7 @@ where } if len > SMALL_SORT_NETWORK_SCRATCH_LEN { - intrinsics::abort_immediate(); + super::crash_for_invalid_arg(); } let mut stack_array = MaybeUninit::<[T; SMALL_SORT_NETWORK_SCRATCH_LEN]>::uninit(); @@ -422,7 +422,7 @@ where F: FnMut(&T, &T) -> bool, { if v.len() < 9 { - intrinsics::abort_immediate(); + super::crash_for_invalid_arg(); } let v_base = v.as_mut_ptr(); @@ -471,7 +471,7 @@ where F: FnMut(&T, &T) -> bool, { if v.len() < 13 { - intrinsics::abort_immediate(); + super::crash_for_invalid_arg(); } let v_base = v.as_mut_ptr(); @@ -578,7 +578,7 @@ pub fn insertion_sort_shift_left bool>( ) { let len = v.len(); if offset == 0 || offset > len { - intrinsics::abort_immediate(); + super::crash_for_invalid_arg(); } // SAFETY: see individual comments. diff --git a/library/core/src/slice/sort/stable/quicksort.rs b/library/core/src/slice/sort/stable/quicksort.rs index e127978f01c9a..2a1e4ce38f962 100644 --- a/library/core/src/slice/sort/stable/quicksort.rs +++ b/library/core/src/slice/sort/stable/quicksort.rs @@ -1,6 +1,7 @@ //! This module contains a stable quicksort and partition implementation. use crate::mem::MaybeUninit; +use crate::slice::sort::shared; use crate::slice::sort::shared::FreezeMarker; use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::StableSmallSortTypeImpl; @@ -96,7 +97,7 @@ fn stable_partition bool>( let len = v.len(); if intrinsics::unlikely(scratch.len() < len || pivot_pos >= len) { - intrinsics::abort_immediate() + shared::crash_for_invalid_arg() } let v_base = v.as_ptr(); diff --git a/library/core/src/slice/sort/unstable/quicksort.rs b/library/core/src/slice/sort/unstable/quicksort.rs index 58a9aae7c7afa..cc8ccf1403c4f 100644 --- a/library/core/src/slice/sort/unstable/quicksort.rs +++ b/library/core/src/slice/sort/unstable/quicksort.rs @@ -3,13 +3,14 @@ #[cfg(not(feature = "optimize_for_size"))] use crate::mem; use crate::mem::ManuallyDrop; +use crate::slice::sort::shared; #[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::pivot::choose_pivot; #[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::smallsort::UnstableSmallSortTypeImpl; #[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::unstable::heapsort; -use crate::{cfg_select, intrinsics, ptr}; +use crate::{cfg_select, intrinsics, process, ptr}; /// Sorts `v` recursively. /// @@ -102,7 +103,7 @@ where } if pivot >= len { - intrinsics::abort_immediate(); + shared::crash_for_invalid_arg() } // SAFETY: We checked that `pivot` is in-bounds. @@ -124,7 +125,7 @@ where let num_lt = (const { inst_partition::() })(v_without_pivot, pivot, is_less); if num_lt >= len { - intrinsics::abort_immediate(); + process::crash() } // SAFETY: We checked that `num_lt` is in-bounds. diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 01c93465ca251..f38dfb95cd039 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -71,11 +71,13 @@ const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! { } #[cfg(panic = "immediate-abort")] +#[inline] const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! { slice_error_fail_ct(s, begin, end) } #[track_caller] +#[cfg_attr(panic = "immediate-abort", inline)] const fn slice_error_fail_ct(_: &str, _: usize, _: usize) -> ! { panic!("failed to slice string"); } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 192f1931fb69d..23fd10022944c 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -315,6 +315,9 @@ // // Library features (core): // tidy-alphabetical-start +#![cfg_attr(windows, feature(core_os_windows))] +#![cfg_attr(windows, feature(windows_fastfail))] +#![feature(abort_immediate)] #![feature(borrowed_buf_init)] #![feature(byte_str)] #![feature(byte_str_internals)] @@ -331,6 +334,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..1d9f38edbb8a2 100644 --- a/library/std/src/os/windows/mod.rs +++ b/library/std/src/os/windows/mod.rs @@ -36,8 +36,12 @@ 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)] +#[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/panicking.rs b/library/std/src/panicking.rs index 4a66d2c1d55f5..216fa7abf91a5 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -705,53 +705,54 @@ pub(crate) fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! { #[track_caller] #[rustc_do_not_const_check] // hooked by const-eval pub const fn begin_panic(msg: M) -> ! { - if cfg!(panic = "immediate-abort") { - intrinsics::abort_immediate() - } + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => { + struct Payload { + inner: Option, + } - struct Payload { - inner: Option, - } + impl PanicPayload for Payload { + fn take_box(&mut self) -> Box { + // Note that this should be the only allocation performed in this code path. Currently + // this means that panic!() on OOM will invoke this code path, but then again we're not + // really ready for panic on OOM anyway. If we do start doing this, then we should + // propagate this allocation to be performed in the parent of this thread instead of the + // thread that's panicking. + match self.inner.take() { + Some(a) => Box::new(a) as Box, + None => process::abort(), + } + } - impl PanicPayload for Payload { - fn take_box(&mut self) -> Box { - // Note that this should be the only allocation performed in this code path. Currently - // this means that panic!() on OOM will invoke this code path, but then again we're not - // really ready for panic on OOM anyway. If we do start doing this, then we should - // propagate this allocation to be performed in the parent of this thread instead of the - // thread that's panicking. - match self.inner.take() { - Some(a) => Box::new(a) as Box, - None => process::abort(), + fn get(&mut self) -> &(dyn Any + Send) { + match self.inner { + Some(ref a) => a, + None => process::abort(), + } + } } - } - fn get(&mut self) -> &(dyn Any + Send) { - match self.inner { - Some(ref a) => a, - None => process::abort(), + impl fmt::Display for Payload { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.inner { + Some(a) => f.write_str(payload_as_str(a)), + None => process::abort(), + } + } } - } - } - impl fmt::Display for Payload { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match &self.inner { - Some(a) => f.write_str(payload_as_str(a)), - None => process::abort(), - } + let loc = Location::caller(); + crate::sys::backtrace::__rust_end_short_backtrace(move || { + panic_with_hook( + &mut Payload { inner: Some(msg) }, + loc, + /* can_unwind */ true, + /* force_no_backtrace */ false, + ) + }) } } - - let loc = Location::caller(); - crate::sys::backtrace::__rust_end_short_backtrace(move || { - panic_with_hook( - &mut Payload { inner: Some(msg) }, - loc, - /* can_unwind */ true, - /* force_no_backtrace */ false, - ) - }) } fn payload_as_str(payload: &dyn Any) -> &str { @@ -876,16 +877,15 @@ pub(crate) fn resume_unwind(payload: Box) -> ! { /// A function with a fixed suffix (through `rustc_std_internal_symbol`) /// on which to slap yer breakpoints. -#[inline(never)] +#[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] #[cfg_attr(not(test), rustc_std_internal_symbol)] -#[cfg(not(panic = "immediate-abort"))] fn rust_panic(msg: &mut dyn PanicPayload) -> ! { - let code = __rust_start_panic(msg); - rtabort!("failed to initiate panic, error {code}") -} - -#[cfg_attr(not(test), rustc_std_internal_symbol)] -#[cfg(panic = "immediate-abort")] -fn rust_panic(_: &mut dyn PanicPayload) -> ! { - crate::intrinsics::abort_immediate(); + cfg_select! { + panic = "immediate-abort" => process::crash(), + _ => { + let code = __rust_start_panic(msg); + rtabort!("failed to initiate panic, error {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/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index 8285682c81ba0..e2dc8ce50f3ba 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -386,6 +386,7 @@ impl Error for AccessError {} // This ensures the panicking code is outlined from `with` for `LocalKey`. #[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] #[track_caller] #[cold] fn panic_access_error(err: AccessError) -> ! {