Skip to content

Commit

Permalink
Validate before reporting interning errors.
Browse files Browse the repository at this point in the history
validation produces much higher quality errors and already handles most of the cases
  • Loading branch information
oli-obk committed Apr 17, 2024
1 parent 8b2a4f8 commit 77fe9f0
Show file tree
Hide file tree
Showing 18 changed files with 253 additions and 513 deletions.
29 changes: 26 additions & 3 deletions compiler/rustc_const_eval/src/const_eval/eval_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@ use rustc_middle::traits::Reveal;
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_session::lint;
use rustc_span::def_id::LocalDefId;
use rustc_span::Span;
use rustc_target::abi::{self, Abi};

use super::{CanAccessMutGlobal, CompileTimeEvalContext, CompileTimeInterpreter};
use crate::const_eval::CheckAlignment;
use crate::errors;
use crate::errors::ConstEvalError;
use crate::interpret::eval_nullary_intrinsic;
use crate::errors::{self, DanglingPtrInFinal};
use crate::interpret::{
create_static_alloc, intern_const_alloc_recursive, CtfeValidationMode, GlobalId, Immediate,
InternKind, InterpCx, InterpError, InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking,
StackPopCleanup,
};
use crate::interpret::{eval_nullary_intrinsic, InternResult};
use crate::CTRL_C_RECEIVED;

// Returns a pointer to where the result lives
Expand Down Expand Up @@ -89,11 +90,33 @@ fn eval_body_using_ecx<'mir, 'tcx, R: InterpretationResult<'tcx>>(
}

// Intern the result
intern_const_alloc_recursive(ecx, intern_kind, &ret)?;
let intern_result = intern_const_alloc_recursive(ecx, intern_kind, &ret);

// Since evaluation had no errors, validate the resulting constant.
const_validate_mplace(&ecx, &ret, cid)?;

// Only report this after validation, as validaiton produces much better diagnostics.
// FIXME: ensure validation always reports this and stop making interning care about it.

if let Err(InternResult { found_bad_mutable_pointer, found_dangling_pointer }) = intern_result {
if found_dangling_pointer {
return Err(ecx
.tcx
.dcx()
.emit_err(DanglingPtrInFinal { span: ecx.tcx.span, kind: intern_kind })
.into());
} else if found_bad_mutable_pointer {
// only report mutable pointers if there were no dangling pointers
let err_diag = errors::MutablePtrInFinal { span: ecx.tcx.span, kind: intern_kind };
ecx.tcx.emit_node_span_lint(
lint::builtin::CONST_EVAL_MUTABLE_PTR_IN_FINAL_VALUE,
ecx.best_lint_scope(),
err_diag.span,
err_diag,
)
}
}

Ok(R::make_result(ret, ecx))
}

Expand Down
45 changes: 25 additions & 20 deletions compiler/rustc_const_eval/src/interpret/intern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,17 @@
use hir::def::DefKind;
use rustc_ast::Mutability;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
use rustc_middle::mir::interpret::{ConstAllocation, CtfeProvenance, InterpResult};
use rustc_middle::query::TyCtxtAt;
use rustc_middle::ty::layout::TyAndLayout;
use rustc_session::lint;
use rustc_span::def_id::LocalDefId;
use rustc_span::sym;

use super::{AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy};
use crate::const_eval;
use crate::errors::{DanglingPtrInFinal, MutablePtrInFinal, NestedStaticInThreadLocal};
use crate::errors::NestedStaticInThreadLocal;

pub trait CompileTimeMachine<'mir, 'tcx: 'mir, T> = Machine<
'mir,
Expand Down Expand Up @@ -134,6 +132,19 @@ pub enum InternKind {
Promoted,
}

#[derive(Default, Debug)]
pub struct InternResult {
pub found_bad_mutable_pointer: bool,
pub found_dangling_pointer: bool,
}

impl InternResult {
fn has_errors(&self) -> bool {
let Self { found_bad_mutable_pointer, found_dangling_pointer } = *self;
found_bad_mutable_pointer || found_dangling_pointer
}
}

/// Intern `ret` and everything it references.
///
/// This *cannot raise an interpreter error*. Doing so is left to validation, which
Expand All @@ -149,7 +160,7 @@ pub fn intern_const_alloc_recursive<
ecx: &mut InterpCx<'mir, 'tcx, M>,
intern_kind: InternKind,
ret: &MPlaceTy<'tcx>,
) -> Result<(), ErrorGuaranteed> {
) -> Result<(), InternResult> {
// We are interning recursively, and for mutability we are distinguishing the "root" allocation
// that we are starting in, and all other allocations that we are encountering recursively.
let (base_mutability, inner_mutability, is_static) = match intern_kind {
Expand Down Expand Up @@ -201,7 +212,7 @@ pub fn intern_const_alloc_recursive<
// Whether we encountered a bad mutable pointer.
// We want to first report "dangling" and then "mutable", so we need to delay reporting these
// errors.
let mut found_bad_mutable_pointer = false;
let mut result = InternResult::default();

// Keep interning as long as there are things to intern.
// We show errors if there are dangling pointers, or mutable pointers in immutable contexts
Expand Down Expand Up @@ -251,7 +262,7 @@ pub fn intern_const_alloc_recursive<
// on the promotion analysis not screwing up to ensure that it is sound to intern
// promoteds as immutable.
trace!("found bad mutable pointer");
found_bad_mutable_pointer = true;
result.found_bad_mutable_pointer = true;
}
if ecx.tcx.try_get_global_alloc(alloc_id).is_some() {
// Already interned.
Expand All @@ -269,21 +280,15 @@ pub fn intern_const_alloc_recursive<
// pointers before deciding which allocations can be made immutable; but for now we are
// okay with losing some potential for immutability here. This can anyway only affect
// `static mut`.
todo.extend(intern_shallow(ecx, alloc_id, inner_mutability).map_err(|()| {
ecx.tcx.dcx().emit_err(DanglingPtrInFinal { span: ecx.tcx.span, kind: intern_kind })
})?);
}
if found_bad_mutable_pointer {
let err_diag = MutablePtrInFinal { span: ecx.tcx.span, kind: intern_kind };
ecx.tcx.emit_node_span_lint(
lint::builtin::CONST_EVAL_MUTABLE_PTR_IN_FINAL_VALUE,
ecx.best_lint_scope(),
err_diag.span,
err_diag,
)
match intern_shallow(ecx, alloc_id, inner_mutability) {
Ok(nested) => todo.extend(nested),
Err(()) => {
ecx.tcx.dcx().delayed_bug("found dangling pointer during const interning");
result.found_dangling_pointer = true
}
}
}

Ok(())
if result.has_errors() { Err(result) } else { Ok(()) }
}

/// Intern `ret`. This function assumes that `ret` references no other allocation.
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_const_eval/src/interpret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub use rustc_middle::mir::interpret::*; // have all the `interpret` symbols in
pub use self::eval_context::{format_interp_error, Frame, FrameInfo, InterpCx, StackPopCleanup};
pub use self::intern::{
intern_const_alloc_for_constprop, intern_const_alloc_recursive, HasStaticRootDefId, InternKind,
InternResult,
};
pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, StackPopJump};
pub use self::memory::{AllocKind, AllocRef, AllocRefMut, FnVal, Memory, MemoryKind};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@
#![feature(const_heap)]
#![feature(const_mut_refs)]

// Strip out raw byte dumps to make comparison platform-independent:
//@ normalize-stderr-test "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)"
//@ normalize-stderr-test "([0-9a-f][0-9a-f] |╾─*A(LLOC)?[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP"
//@ normalize-stderr-test "HEX_DUMP\s*\n\s*HEX_DUMP" -> "HEX_DUMP"

use std::intrinsics;

const _X: &'static u8 = unsafe {
//~^ error: dangling pointer in final value of constant
//~^ error: it is undefined behavior to use this value
let ptr = intrinsics::const_allocate(4, 4);
intrinsics::const_deallocate(ptr, 4, 4);
&*ptr
Expand Down
15 changes: 10 additions & 5 deletions tests/ui/consts/const-eval/heap/dealloc_intrinsic_dangling.stderr
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
error: encountered dangling pointer in final value of constant
--> $DIR/dealloc_intrinsic_dangling.rs:7:1
error[E0080]: it is undefined behavior to use this value
--> $DIR/dealloc_intrinsic_dangling.rs:12:1
|
LL | const _X: &'static u8 = unsafe {
| ^^^^^^^^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (use-after-free)
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
= note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) {
HEX_DUMP
}

error[E0080]: evaluation of constant value failed
--> $DIR/dealloc_intrinsic_dangling.rs:18:5
--> $DIR/dealloc_intrinsic_dangling.rs:23:5
|
LL | *reference
| ^^^^^^^^^^ memory access failed: ALLOC0 has been freed, so this pointer is dangling
| ^^^^^^^^^^ memory access failed: ALLOC1 has been freed, so this pointer is dangling

error: aborting due to 2 previous errors

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ const fn helper_dangling() -> Option<&'static mut i32> { unsafe {
// Undefined behaviour (dangling pointer), who doesn't love tests like this.
Some(&mut *(&mut 42 as *mut i32))
} }
const DANGLING: Option<&mut i32> = helper_dangling(); //~ ERROR encountered dangling pointer
static DANGLING_STATIC: Option<&mut i32> = helper_dangling(); //~ ERROR encountered dangling pointer
const DANGLING: Option<&mut i32> = helper_dangling(); //~ ERROR it is undefined behavior to use this value
static DANGLING_STATIC: Option<&mut i32> = helper_dangling(); //~ ERROR it is undefined behavior to use this value

// These are fine! Just statics pointing to mutable statics, nothing fundamentally wrong with this.
static MUT_STATIC: Option<&mut i32> = helper();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,27 @@ LL | static INT2PTR_STATIC: Option<&mut i32> = helper_int2ptr();
HEX_DUMP
}

error: encountered dangling pointer in final value of constant
error[E0080]: it is undefined behavior to use this value
--> $DIR/mut_ref_in_final_dynamic_check.rs:36:1
|
LL | const DANGLING: Option<&mut i32> = helper_dangling();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .<enum-variant(Some)>.0: encountered a dangling reference (use-after-free)
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
= note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) {
HEX_DUMP
}

error: encountered dangling pointer in final value of static
error[E0080]: it is undefined behavior to use this value
--> $DIR/mut_ref_in_final_dynamic_check.rs:37:1
|
LL | static DANGLING_STATIC: Option<&mut i32> = helper_dangling();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value at .<enum-variant(Some)>.0: encountered a dangling reference (use-after-free)
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
= note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) {
HEX_DUMP
}

error: aborting due to 5 previous errors

Expand Down
6 changes: 5 additions & 1 deletion tests/ui/consts/dangling-alloc-id-ice.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
// https://github.com/rust-lang/rust/issues/55223
// Strip out raw byte dumps to make comparison platform-independent:
//@ normalize-stderr-test "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)"
//@ normalize-stderr-test "([0-9a-f][0-9a-f] |╾─*A(LLOC)?[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP"
//@ normalize-stderr-test "HEX_DUMP\s*\n\s*HEX_DUMP" -> "HEX_DUMP"

union Foo<'a> {
y: &'a (),
long_live_the_unit: &'static (),
}

const FOO: &() = {
//~^ ERROR encountered dangling pointer in final value of constant
//~^ ERROR it is undefined behavior to use this value
let y = ();
unsafe { Foo { y: &y }.long_live_the_unit }
};
Expand Down
12 changes: 9 additions & 3 deletions tests/ui/consts/dangling-alloc-id-ice.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
error: encountered dangling pointer in final value of constant
--> $DIR/dangling-alloc-id-ice.rs:8:1
error[E0080]: it is undefined behavior to use this value
--> $DIR/dangling-alloc-id-ice.rs:12:1
|
LL | const FOO: &() = {
| ^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (use-after-free)
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
= note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) {
HEX_DUMP
}

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0080`.
27 changes: 24 additions & 3 deletions tests/ui/consts/dangling_raw_ptr.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@
const FOO: *const u32 = { //~ ERROR encountered dangling pointer in final value of constant
const FOO: *const u32 = {
//~^ ERROR encountered dangling pointer in final value of constant
let x = 42;
&x
};

fn main() {
let x = FOO;
union Union {
ptr: *const u32,
}

const BAR: Union = {
//~^ ERROR encountered dangling pointer in final value of constant
let x = 42;
Union { ptr: &x }
};

const BAZ: Union = {
//~^ ERROR encountered dangling pointer in final value of constant
let x = 42_u32;
Union { ptr: &(&x as *const u32) as *const *const u32 as _ }
};

const FOOMP: *const u32 = {
//~^ ERROR encountered dangling pointer in final value of constant
let x = 42_u32;
&(&x as *const u32) as *const *const u32 as _
};

fn main() {}
20 changes: 19 additions & 1 deletion tests/ui/consts/dangling_raw_ptr.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,23 @@ error: encountered dangling pointer in final value of constant
LL | const FOO: *const u32 = {
| ^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 1 previous error
error: encountered dangling pointer in final value of constant
--> $DIR/dangling_raw_ptr.rs:11:1
|
LL | const BAR: Union = {
| ^^^^^^^^^^^^^^^^

error: encountered dangling pointer in final value of constant
--> $DIR/dangling_raw_ptr.rs:17:1
|
LL | const BAZ: Union = {
| ^^^^^^^^^^^^^^^^

error: encountered dangling pointer in final value of constant
--> $DIR/dangling_raw_ptr.rs:23:1
|
LL | const FOOMP: *const u32 = {
| ^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 4 previous errors

15 changes: 4 additions & 11 deletions tests/ui/consts/miri_unleashed/mutable_references.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,9 @@
#![deny(const_eval_mutable_ptr_in_final_value)]
use std::cell::UnsafeCell;

// a test demonstrating what things we could allow with a smarter const qualification

// This requires walking nested statics.
static FOO: &&mut u32 = &&mut 42;
//~^ ERROR encountered mutable pointer in final value of static
//~| WARNING this was previously accepted by the compiler
//~| ERROR it is undefined behavior to use this value
//~^ ERROR it is undefined behavior to use this value

static BAR: &mut () = &mut ();
//~^ ERROR encountered mutable pointer in final value of static
Expand All @@ -27,14 +24,10 @@ struct Meh {
}
unsafe impl Sync for Meh {}
static MEH: Meh = Meh { x: &UnsafeCell::new(42) };
//~^ ERROR encountered mutable pointer in final value of static
//~| WARNING this was previously accepted by the compiler
//~| ERROR it is undefined behavior to use this value
//~^ ERROR it is undefined behavior to use this value

static OH_YES: &mut i32 = &mut 42;
//~^ ERROR encountered mutable pointer in final value of static
//~| WARNING this was previously accepted by the compiler
//~| ERROR it is undefined behavior to use this value
//~^ ERROR it is undefined behavior to use this value

fn main() {
unsafe {
Expand Down
Loading

0 comments on commit 77fe9f0

Please sign in to comment.