Skip to content

Commit bee72cf

Browse files
committed
Auto merge of rust-lang#141759 - 1c3t3a:discriminants-query, r=saethlin
Insert checks for enum discriminants when debug assertions are enabled Similar to the existing null-pointer and alignment checks, this checks for valid enum discriminants on creation of enums through unsafe transmutes. Essentially this sanitizes patterns like the following: ```rust let val: MyEnum = unsafe { std::mem::transmute<u32, MyEnum>(42) }; ``` An extension of this check will be done in a follow-up that explicitly sanitizes for extern enum values that come into Rust from e.g. C/C++. This check is similar to Miri's capabilities of checking for valid construction of enum values. This PR is inspired by saethlin@'s PR rust-lang#104862. Thank you so much for keeping this code up and the detailed comments! I also pair-programmed large parts of this together with vabr-g@. r? `@saethlin`
2 parents 6967ac3 + a14206b commit bee72cf

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

core/src/panicking.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,22 @@ fn panic_null_pointer_dereference() -> ! {
314314
)
315315
}
316316

317+
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold, optimize(size))]
318+
#[cfg_attr(feature = "panic_immediate_abort", inline)]
319+
#[track_caller]
320+
#[lang = "panic_invalid_enum_construction"] // needed by codegen for panic on invalid enum construction.
321+
#[rustc_nounwind] // `CheckEnums` MIR pass requires this function to never unwind
322+
fn panic_invalid_enum_construction(source: u128) -> ! {
323+
if cfg!(feature = "panic_immediate_abort") {
324+
super::intrinsics::abort()
325+
}
326+
327+
panic_nounwind_fmt(
328+
format_args!("trying to construct an enum from an invalid value {source:#x}"),
329+
/* force_no_backtrace */ false,
330+
)
331+
}
332+
317333
/// Panics because we cannot unwind out of a function.
318334
///
319335
/// This is a separate function to avoid the codesize impact of each crate containing the string to

0 commit comments

Comments
 (0)