1 use std::cell::RefCell;
2 use std::collections::hash_map::Entry;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_target::abi::{HasDataLayout, Size};
12 pub type MemoryExtra = RefCell<GlobalState>;
14 #[derive(Clone, Debug)]
15 pub struct GlobalState {
16 /// This is used as a map between the address of each allocation and its `AllocId`.
17 /// It is always sorted
18 pub int_to_ptr_map: Vec<(u64, AllocId)>,
19 /// The base address for each allocation. We cannot put that into
20 /// `AllocExtra` because function pointers also have a base address, and
21 /// they do not have an `AllocExtra`.
22 /// This is the inverse of `int_to_ptr_map`.
23 pub base_addr: FxHashMap<AllocId, u64>,
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 fn default() -> Self {
32 int_to_ptr_map: Vec::default(),
33 base_addr: FxHashMap::default(),
34 next_base_addr: STACK_ADDR,
39 impl<'mir, 'tcx> GlobalState {
42 memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
43 ) -> Pointer<Option<Tag>> {
44 trace!("Casting 0x{:x} to a pointer", addr);
45 let global_state = memory.extra.intptrcast.borrow();
46 let pos = global_state.int_to_ptr_map.binary_search_by_key(&addr, |(addr, _)| *addr);
48 let alloc_id = match pos {
49 Ok(pos) => Some(global_state.int_to_ptr_map[pos].1),
52 // This is the largest of the adresses smaller than `int`,
53 // i.e. the greatest lower bound (glb)
54 let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
55 // This never overflows because `addr >= glb`
56 let offset = addr - glb;
57 // If the offset exceeds the size of the allocation, don't use this `alloc_id`.
59 <= memory.get_size_and_align(alloc_id, AllocCheck::MaybeDead).unwrap().0.bytes()
67 // Pointers created from integers are untagged.
69 alloc_id.map(|alloc_id| Tag { alloc_id, sb: SbTag::Untagged }),
70 Size::from_bytes(addr),
75 memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
78 let mut global_state = memory.extra.intptrcast.borrow_mut();
79 let global_state = &mut *global_state;
81 match global_state.base_addr.entry(alloc_id) {
82 Entry::Occupied(entry) => *entry.get(),
83 Entry::Vacant(entry) => {
84 // There is nothing wrong with a raw pointer being cast to an integer only after
85 // it became dangling. Hence `MaybeDead`.
87 memory.get_size_and_align(alloc_id, AllocCheck::MaybeDead).unwrap();
89 // This allocation does not have a base address yet, pick one.
90 // Leave some space to the previous allocation, to give it some chance to be less aligned.
92 let mut rng = memory.extra.rng.borrow_mut();
93 // This means that `(global_state.next_base_addr + slack) % 16` is uniformly distributed.
96 // From next_base_addr + slack, round up to adjust for alignment.
97 let base_addr = global_state.next_base_addr.checked_add(slack).unwrap();
98 let base_addr = Self::align_addr(base_addr, align.bytes());
99 entry.insert(base_addr);
101 "Assigning base address {:#x} to allocation {:?} (size: {}, align: {}, slack: {})",
109 // Remember next base address. Leave a gap of at least 1 to avoid two zero-sized allocations
110 // having the same base address, and to avoid ambiguous provenance for the address between two
111 // allocations (also see https://github.com/rust-lang/unsafe-code-guidelines/issues/313).
112 let size_plus_1 = size.bytes().checked_add(1).unwrap();
113 global_state.next_base_addr = base_addr.checked_add(size_plus_1).unwrap();
114 // Given that `next_base_addr` increases in each allocation, pushing the
115 // corresponding tuple keeps `int_to_ptr_map` sorted
116 global_state.int_to_ptr_map.push((base_addr, alloc_id));
123 /// Convert a relative (tcx) pointer to an absolute address.
124 pub fn rel_ptr_to_addr(
125 memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
126 ptr: Pointer<AllocId>,
128 let (alloc_id, offset) = ptr.into_parts(); // offset is relative
129 let base_addr = GlobalState::alloc_base_addr(memory, alloc_id);
131 // Add offset with the right kind of pointer-overflowing arithmetic.
132 let dl = memory.data_layout();
133 dl.overflowing_offset(base_addr, offset.bytes()).0
136 pub fn abs_ptr_to_rel(
137 memory: &Memory<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
140 let (tag, addr) = ptr.into_parts(); // addr is absolute
141 let base_addr = GlobalState::alloc_base_addr(memory, tag.alloc_id);
143 // Wrapping "addr - base_addr"
144 let dl = memory.data_layout();
145 let neg_base_addr = (base_addr as i64).wrapping_neg();
146 Size::from_bytes(dl.overflowing_signed_offset(addr.bytes(), neg_base_addr).0)
149 /// Shifts `addr` to make it aligned with `align` by rounding `addr` to the smallest multiple
150 /// of `align` that is larger or equal to `addr`
151 fn align_addr(addr: u64, align: u64) -> u64 {
154 rem => addr.checked_add(align).unwrap() - rem,
164 fn test_align_addr() {
165 assert_eq!(GlobalState::align_addr(37, 4), 40);
166 assert_eq!(GlobalState::align_addr(44, 4), 44);