Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Test and assert that we do not reveal a static item's memory AllocId #116571

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 4 additions & 0 deletions compiler/rustc_const_eval/src/const_eval/eval_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@ pub fn eval_to_const_value_raw_provider<'tcx>(
tcx: TyCtxt<'tcx>,
key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
assert!(
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
assert!(
// This shouldn't be used for statics, since statics are conceptually places,
// not values -- so what we do here could break pointer identity.
assert!(

key.value.promoted.is_some() || !tcx.is_static(key.value.instance.def_id()),
"use `eval_static_initializer` instead"
);
// see comment in eval_to_allocation_raw_provider for what we're doing here
if key.param_env.reveal() == Reveal::All {
let mut key = key;
Expand Down
1 change: 1 addition & 0 deletions tests/ui/statics/auxiliary/bad_alloc_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub static mut FOO: Option<u32> = Some(42);
28 changes: 28 additions & 0 deletions tests/ui/statics/bad_alloc_id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// aux-build: bad_alloc_id.rs
// run-pass

//! This test checks that we do not accidentally duplicate static items' base
//! allocation, even if we go through some projections. This is achieved by
//! never exposing a static item's "memory alloc id". Every static item has two
//! `AllocId`s: One which is backed by `GlobalAlloc::Static` and allows us to
//! figure out the static item. Then we can evaluate that static item, giving us
//! the static's memory-id, which is backed by `GlobalAlloc::Memory`. We always
//! immediately convert to the memory representation and throw away the memory
//! alloc id.

#![feature(const_mut_refs)]

extern crate bad_alloc_id;

static mut BAR: &mut u32 = unsafe {
match &mut bad_alloc_id::FOO {
Some(x) => x,
None => panic!(),
}
};

fn main() {
unsafe {
assert_eq!(BAR as *mut u32, bad_alloc_id::FOO.as_mut().unwrap() as *mut u32);
}
}