Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/rustc_attr_ir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 0 additions & 8 deletions compiler/rustc_codegen_cranelift/src/inline_asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,6 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>(
options: InlineAsmOptions,
destination: Option<mir::BasicBlock>,
) {
// 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())
Expand Down
15 changes: 14 additions & 1 deletion compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_gcc/src/intrinsic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, &[]));
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_llvm/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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", &[], &[]);
}

Expand Down
27 changes: 24 additions & 3 deletions compiler/rustc_codegen_ssa/src/traits/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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};

Expand Down Expand Up @@ -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();
}
}
}
5 changes: 3 additions & 2 deletions compiler/rustc_codegen_ssa/src/traits/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
9 changes: 9 additions & 0 deletions compiler/rustc_monomorphize/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,7 @@ symbols! {
coverage,
coverage_attribute,
cr,
crash_impl,
crate_in_paths,
crate_local,
crate_name,
Expand Down
48 changes: 46 additions & 2 deletions library/core/src/os/windows.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand All @@ -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;
Expand All @@ -37,3 +37,47 @@ pub use crate::intrinsics::CodeViewAnnotationArgs;
pub fn codeview_annotation<T: CodeViewAnnotationArgs>() {
crate::intrinsics::codeview_annotation::<T>();
}

/// 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")]

@RalfJung RalfJung Nov 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this meant to be an internal feature? Then it should be called something_internal to trigger the lint.

View changes since the review

@Jules-Bertholet Jules-Bertholet Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may want to consider putting it on a stabilization track, so that users can pass custom codes. (I don't have a strong opinion either way)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should keep it unstable for now anyway. I don't know if calling it __fastfail is the best name rather than without the two underscores, but I'm not going to nitpick here.

#[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
// <https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail>
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)
}
7 changes: 6 additions & 1 deletion library/core/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")]
Expand Down
3 changes: 3 additions & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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)]
Expand Down
5 changes: 4 additions & 1 deletion library/std/src/os/windows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 0 additions & 1 deletion library/std/src/sys/pal/windows/c/bindings.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion library/std/src/sys/pal/windows/c/windows_sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<unsafe extern "system" fn() -> isize>;
pub const FAST_FAIL_FATAL_APP_EXIT: i32 = 7;
pub type FD_SET = fd_set;
#[repr(C)]
#[derive(Clone, Copy, Default)]
Expand Down
35 changes: 2 additions & 33 deletions library/std/src/sys/pal/windows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
/// <https://docs.microsoft.com/en-us/cpp/intrinsics/fastfail>
#[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.
///
Expand Down
29 changes: 29 additions & 0 deletions tests/assembly-llvm/win-fastfail.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//@ assembly-output: emit-asm

@clarfonthey clarfonthey Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe we still have const tests that would run on every platform, right? Just to verify those still go through the regular intrinsic.

View changes since the review

//@ 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() {
Comment thread
Jules-Bertholet marked this conversation as resolved.
Resolved
// 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()
}
Loading