Skip to content

Commit d53ed12

Browse files
committed
Auto merge of rust-lang#104862 - saethlin:mir-niche-checks, r=<try>
Check for occupied niches Implementation of rust-lang/compiler-team#624 Crater run has 62 crates that hit the check, 43 of those are published to crates.io. I see a lot of null function pointers and use of `mem::uninitialized` where the 0x1-filling collides with an enum niche. But that is with full niche checks; checking transmute, plus any place where that we Copy, Move, or Inspect. Such checking is definitely too thorough to be on by default because it is 2x compile time overhead. --- During implementation, this ran into llvm/llvm-project#68381 r? `@ghost`
2 parents 7cc36de + 9174f14 commit d53ed12

File tree

39 files changed

+628
-46
lines changed

39 files changed

+628
-46
lines changed

compiler/rustc_codegen_cranelift/src/base.rs

+13
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,19 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
368368
source_info.span,
369369
);
370370
}
371+
AssertKind::OccupiedNiche { ref found, ref start, ref end } => {
372+
let found = codegen_operand(fx, found).load_scalar(fx);
373+
let start = codegen_operand(fx, start).load_scalar(fx);
374+
let end = codegen_operand(fx, end).load_scalar(fx);
375+
let location = fx.get_caller_location(source_info).load_scalar(fx);
376+
377+
codegen_panic_inner(
378+
fx,
379+
rustc_hir::LangItem::PanicOccupiedNiche,
380+
&[found, start, end, location],
381+
source_info.span,
382+
)
383+
}
371384
_ => {
372385
let msg_str = msg.description();
373386
codegen_panic(fx, msg_str, source_info);

compiler/rustc_codegen_ssa/src/common.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
use rustc_hir::LangItem;
44
use rustc_middle::mir;
5-
use rustc_middle::ty::{self, layout::TyAndLayout, Ty, TyCtxt};
5+
use rustc_middle::ty::{self, layout::TyAndLayout, GenericArg, Ty, TyCtxt};
66
use rustc_span::Span;
77

88
use crate::base;
@@ -120,10 +120,15 @@ pub fn build_langcall<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
120120
bx: &Bx,
121121
span: Option<Span>,
122122
li: LangItem,
123+
generic: Option<GenericArg<'tcx>>,
123124
) -> (Bx::FnAbiOfResult, Bx::Value) {
124125
let tcx = bx.tcx();
125126
let def_id = tcx.require_lang_item(li, span);
126-
let instance = ty::Instance::mono(tcx, def_id);
127+
let instance = if let Some(arg) = generic {
128+
ty::Instance::new(def_id, tcx.mk_args(&[arg]))
129+
} else {
130+
ty::Instance::mono(tcx, def_id)
131+
};
127132
(bx.fn_abi_of_instance(instance, ty::List::empty()), bx.get_fn_addr(instance))
128133
}
129134

compiler/rustc_codegen_ssa/src/mir/block.rs

+23-9
Original file line numberDiff line numberDiff line change
@@ -609,30 +609,40 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
609609
let location = self.get_caller_location(bx, terminator.source_info).immediate();
610610

611611
// Put together the arguments to the panic entry point.
612-
let (lang_item, args) = match msg {
612+
let (lang_item, args, generic) = match msg {
613613
AssertKind::BoundsCheck { ref len, ref index } => {
614614
let len = self.codegen_operand(bx, len).immediate();
615615
let index = self.codegen_operand(bx, index).immediate();
616616
// It's `fn panic_bounds_check(index: usize, len: usize)`,
617617
// and `#[track_caller]` adds an implicit third argument.
618-
(LangItem::PanicBoundsCheck, vec![index, len, location])
618+
(LangItem::PanicBoundsCheck, vec![index, len, location], None)
619619
}
620620
AssertKind::MisalignedPointerDereference { ref required, ref found } => {
621621
let required = self.codegen_operand(bx, required).immediate();
622622
let found = self.codegen_operand(bx, found).immediate();
623623
// It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
624624
// and `#[track_caller]` adds an implicit third argument.
625-
(LangItem::PanicMisalignedPointerDereference, vec![required, found, location])
625+
(LangItem::PanicMisalignedPointerDereference, vec![required, found, location], None)
626+
}
627+
AssertKind::OccupiedNiche { ref found, ref start, ref end } => {
628+
let found = self.codegen_operand(bx, found);
629+
let generic_arg = ty::GenericArg::from(found.layout.ty);
630+
let found = found.immediate();
631+
let start = self.codegen_operand(bx, start).immediate();
632+
let end = self.codegen_operand(bx, end).immediate();
633+
// It's `fn panic_occupied_niche<T>(found: T, start: T, end: T)`,
634+
// and `#[track_caller]` adds an implicit fourth argument.
635+
(LangItem::PanicOccupiedNiche, vec![found, start, end, location], Some(generic_arg))
626636
}
627637
_ => {
628638
let msg = bx.const_str(msg.description());
629639
// It's `pub fn panic(expr: &str)`, with the wide reference being passed
630640
// as two arguments, and `#[track_caller]` adds an implicit third argument.
631-
(LangItem::Panic, vec![msg.0, msg.1, location])
641+
(LangItem::Panic, vec![msg.0, msg.1, location], None)
632642
}
633643
};
634644

635-
let (fn_abi, llfn) = common::build_langcall(bx, Some(span), lang_item);
645+
let (fn_abi, llfn) = common::build_langcall(bx, Some(span), lang_item, generic);
636646

637647
// Codegen the actual panic invoke/call.
638648
let merging_succ = helper.do_call(self, bx, fn_abi, llfn, &args, None, unwind, &[], false);
@@ -651,7 +661,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
651661
self.set_debug_loc(bx, terminator.source_info);
652662

653663
// Obtain the panic entry point.
654-
let (fn_abi, llfn) = common::build_langcall(bx, Some(span), reason.lang_item());
664+
let (fn_abi, llfn) = common::build_langcall(bx, Some(span), reason.lang_item(), None);
655665

656666
// Codegen the actual panic invoke/call.
657667
let merging_succ = helper.do_call(
@@ -712,8 +722,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
712722
let msg = bx.const_str(&msg_str);
713723

714724
// Obtain the panic entry point.
715-
let (fn_abi, llfn) =
716-
common::build_langcall(bx, Some(source_info.span), LangItem::PanicNounwind);
725+
let (fn_abi, llfn) = common::build_langcall(
726+
bx,
727+
Some(source_info.span),
728+
LangItem::PanicNounwind,
729+
None,
730+
);
717731

718732
// Codegen the actual panic invoke/call.
719733
helper.do_call(
@@ -1622,7 +1636,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
16221636

16231637
self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
16241638

1625-
let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, reason.lang_item());
1639+
let (fn_abi, fn_ptr) = common::build_langcall(&bx, None, reason.lang_item(), None);
16261640
let fn_ty = bx.fn_decl_backend_type(&fn_abi);
16271641

16281642
let llret = bx.call(fn_ty, None, Some(&fn_abi), fn_ptr, &[], funclet.as_ref());

compiler/rustc_const_eval/src/const_eval/machine.rs

+5
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,11 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
542542
found: eval_to_int(found)?,
543543
}
544544
}
545+
OccupiedNiche { ref found, ref start, ref end } => OccupiedNiche {
546+
found: eval_to_int(found)?,
547+
start: eval_to_int(start)?,
548+
end: eval_to_int(end)?,
549+
},
545550
};
546551
Err(ConstEvalErrKind::AssertFailure(err).into())
547552
}

compiler/rustc_const_eval/src/interpret/cast.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar};
66
use rustc_middle::mir::CastKind;
77
use rustc_middle::ty::adjustment::PointerCoercion;
88
use rustc_middle::ty::layout::{IntegerExt, LayoutOf, TyAndLayout};
9+
use rustc_middle::ty::print::with_no_trimmed_paths;
910
use rustc_middle::ty::{self, FloatTy, Ty, TypeAndMut};
1011
use rustc_target::abi::Integer;
1112
use rustc_type_ir::TyKind::*;
@@ -147,8 +148,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
147148
if src.layout.size != dest.layout.size {
148149
let src_bytes = src.layout.size.bytes();
149150
let dest_bytes = dest.layout.size.bytes();
150-
let src_ty = format!("{}", src.layout.ty);
151-
let dest_ty = format!("{}", dest.layout.ty);
151+
let src_ty = with_no_trimmed_paths!(format!("{}", src.layout.ty));
152+
let dest_ty = with_no_trimmed_paths!(format!("{}", dest.layout.ty));
152153
throw_ub_custom!(
153154
fluent::const_eval_invalid_transmute,
154155
src_bytes = src_bytes,

compiler/rustc_hir/src/lang_items.rs

+1
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@ language_item_table! {
234234
ConstPanicFmt, sym::const_panic_fmt, const_panic_fmt, Target::Fn, GenericRequirement::None;
235235
PanicBoundsCheck, sym::panic_bounds_check, panic_bounds_check_fn, Target::Fn, GenericRequirement::Exact(0);
236236
PanicMisalignedPointerDereference, sym::panic_misaligned_pointer_dereference, panic_misaligned_pointer_dereference_fn, Target::Fn, GenericRequirement::Exact(0);
237+
PanicOccupiedNiche, sym::panic_occupied_niche, panic_occupied_niche_fn, Target::Fn, GenericRequirement::Exact(1);
237238
PanicInfo, sym::panic_info, panic_info, Target::Struct, GenericRequirement::None;
238239
PanicLocation, sym::panic_location, panic_location, Target::Struct, GenericRequirement::None;
239240
PanicImpl, sym::panic_impl, panic_impl, Target::Fn, GenericRequirement::None;

compiler/rustc_middle/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ middle_assert_divide_by_zero =
1515
middle_assert_misaligned_ptr_deref =
1616
misaligned pointer dereference: address must be a multiple of {$required} but is {$found}
1717
18+
middle_assert_occupied_niche =
19+
occupied niche: {$found} must be in {$start}..={$end}
20+
1821
middle_assert_op_overflow =
1922
attempt to compute `{$left} {$op} {$right}`, which would overflow
2023

compiler/rustc_middle/src/mir/syntax.rs

+1
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,7 @@ pub enum AssertKind<O> {
886886
ResumedAfterReturn(CoroutineKind),
887887
ResumedAfterPanic(CoroutineKind),
888888
MisalignedPointerDereference { required: O, found: O },
889+
OccupiedNiche { found: O, start: O, end: O },
889890
}
890891

891892
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]

compiler/rustc_middle/src/mir/terminator.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ impl<O> AssertKind<O> {
150150
ResumedAfterReturn(CoroutineKind::Async(_)) => "`async fn` resumed after completion",
151151
ResumedAfterPanic(CoroutineKind::Coroutine) => "coroutine resumed after panicking",
152152
ResumedAfterPanic(CoroutineKind::Async(_)) => "`async fn` resumed after panicking",
153-
BoundsCheck { .. } | MisalignedPointerDereference { .. } => {
153+
BoundsCheck { .. } | MisalignedPointerDereference { .. } | OccupiedNiche { .. } => {
154154
bug!("Unexpected AssertKind")
155155
}
156156
}
@@ -213,6 +213,13 @@ impl<O> AssertKind<O> {
213213
"\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {required:?}, {found:?}"
214214
)
215215
}
216+
OccupiedNiche { found, start, end } => {
217+
write!(
218+
f,
219+
"\"occupied niche: {{}} must be in {{}}..={{}}\", {:?}, {:?}, {:?}",
220+
found, start, end
221+
)
222+
}
216223
_ => write!(f, "\"{}\"", self.description()),
217224
}
218225
}
@@ -243,8 +250,8 @@ impl<O> AssertKind<O> {
243250
ResumedAfterPanic(CoroutineKind::Coroutine) => {
244251
middle_assert_coroutine_resume_after_panic
245252
}
246-
247253
MisalignedPointerDereference { .. } => middle_assert_misaligned_ptr_deref,
254+
OccupiedNiche { .. } => middle_assert_occupied_niche,
248255
}
249256
}
250257

@@ -281,6 +288,11 @@ impl<O> AssertKind<O> {
281288
add!("required", format!("{required:#?}"));
282289
add!("found", format!("{found:#?}"));
283290
}
291+
OccupiedNiche { found, start, end } => {
292+
add!("found", format!("{found:?}"));
293+
add!("start", format!("{start:?}"));
294+
add!("end", format!("{end:?}"));
295+
}
284296
}
285297
}
286298
}

compiler/rustc_middle/src/mir/visit.rs

+5
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,11 @@ macro_rules! make_mir_visitor {
625625
self.visit_operand(required, location);
626626
self.visit_operand(found, location);
627627
}
628+
OccupiedNiche { found, start, end } => {
629+
self.visit_operand(found, location);
630+
self.visit_operand(start, location);
631+
self.visit_operand(end, location);
632+
}
628633
}
629634
}
630635

0 commit comments

Comments
 (0)