1 use std::cell::{Cell, RefCell};
5 use rustc::mir::interpret::{AllocId, Pointer, InterpResult};
6 use rustc_mir::interpret::Memory;
7 use rustc_target::abi::Size;
9 use crate::stacked_borrows::Tag;
12 pub type MemoryExtra = RefCell<GlobalState>;
14 #[derive(Clone, Debug, Default)]
15 pub struct AllocExtra {
16 base_addr: Cell<Option<u64>>
19 #[derive(Clone, Debug)]
20 pub struct GlobalState {
21 /// This is used as a map between the address of each allocation and its `AllocId`.
22 /// It is always sorted
23 pub int_to_ptr_map: Vec<(u64, AllocId)>,
24 /// This is used as a memory address when a new pointer is casted to an integer. It
25 /// is always larger than any address that was previously made part of a block.
26 pub next_base_addr: u64,
29 impl Default for GlobalState {
30 // FIXME: Query the page size in the future
31 fn default() -> Self {
33 int_to_ptr_map: Vec::default(),
34 next_base_addr: 2u64.pow(16)
39 impl<'mir, 'tcx> GlobalState {
42 memory: &Memory<'mir, 'tcx, Evaluator<'tcx>>,
43 ) -> InterpResult<'tcx, Pointer<Tag>> {
44 let global_state = memory.extra.intptrcast.borrow();
46 match global_state.int_to_ptr_map.binary_search_by_key(&int, |(addr, _)| *addr) {
48 let (_, alloc_id) = global_state.int_to_ptr_map[pos];
49 // `int` is equal to the starting address for an allocation, the offset should be
50 // zero. The pointer is untagged because it was created from a cast
51 Ok(Pointer::new_with_tag(alloc_id, Size::from_bytes(0), Tag::Untagged))
53 Err(0) => err!(DanglingPointerDeref),
55 // This is the largest of the adresses smaller than `int`,
56 // i.e. the greatest lower bound (glb)
57 let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
58 // This never overflows because `int >= glb`
59 let offset = int - glb;
60 // If the offset exceeds the size of the allocation, this access is illegal
61 if offset <= memory.get(alloc_id)?.bytes.len() as u64 {
62 // This pointer is untagged because it was created from a cast
63 Ok(Pointer::new_with_tag(alloc_id, Size::from_bytes(offset), Tag::Untagged))
65 err!(DanglingPointerDeref)
73 memory: &Memory<'mir, 'tcx, Evaluator<'tcx>>,
74 ) -> InterpResult<'tcx, u64> {
75 let mut global_state = memory.extra.intptrcast.borrow_mut();
77 let alloc = memory.get(ptr.alloc_id)?;
78 let align = alloc.align.bytes();
80 let base_addr = match alloc.extra.intptrcast.base_addr.get() {
81 Some(base_addr) => base_addr,
83 // This allocation does not have a base address yet, pick one.
84 // Leave some space to the previous allocation, to give it some chance to be less aligned.
86 let mut rng = memory.extra.rng.as_ref().unwrap().borrow_mut();
87 rng.gen_range(0, align)
89 // From next_base_addr + slack, round up to adjust for alignment.
90 let base_addr = Self::align_addr(global_state.next_base_addr + slack, align);
91 alloc.extra.intptrcast.base_addr.set(Some(base_addr));
93 // Remember next base address.
94 global_state.next_base_addr = base_addr + alloc.bytes.len() as u64;
95 // Given that `next_base_addr` increases in each allocation, pushing the
96 // corresponding tuple keeps `int_to_ptr_map` sorted
97 global_state.int_to_ptr_map.push((base_addr, ptr.alloc_id));
103 debug_assert_eq!(base_addr % align, 0); // sanity check
104 Ok(base_addr + ptr.offset.bytes())
107 /// Shifts `addr` to make it aligned with `align` by rounding `addr` to the smallest multiple
108 /// of `align` that is larger or equal to `addr`
109 fn align_addr(addr: u64, align: u64) -> u64 {
110 if addr % align == 0 {
113 addr + align - addr % align
123 fn test_align_addr() {
124 assert_eq!(GlobalState::align_addr(37, 4), 40);
125 assert_eq!(GlobalState::align_addr(44, 4), 44);