]> git.lizzy.rs Git - rust.git/blob - src/intptrcast.rs
8eb28e4f4700a6d29e3c97e13a520097d72425e0
[rust.git] / src / intptrcast.rs
1 use std::cell::RefCell;
2 use std::cmp::max;
3 use std::collections::hash_map::Entry;
4
5 use log::trace;
6 use rand::Rng;
7
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_middle::ty::layout::HasDataLayout;
10 use rustc_mir::interpret::{AllocCheck, AllocId, InterpResult, Memory, Machine, Pointer, PointerArithmetic};
11 use rustc_target::abi::Size;
12
13 use crate::{Evaluator, Tag, STACK_ADDR};
14
15 pub type MemoryExtra = RefCell<GlobalState>;
16
17 #[derive(Clone, Debug)]
18 pub struct GlobalState {
19     /// This is used as a map between the address of each allocation and its `AllocId`.
20     /// It is always sorted
21     pub int_to_ptr_map: Vec<(u64, AllocId)>,
22     /// The base address for each allocation.  We cannot put that into
23     /// `AllocExtra` because function pointers also have a base address, and
24     /// they do not have an `AllocExtra`.
25     /// This is the inverse of `int_to_ptr_map`.
26     pub base_addr: FxHashMap<AllocId, u64>,
27     /// This is used as a memory address when a new pointer is casted to an integer. It
28     /// is always larger than any address that was previously made part of a block.
29     pub next_base_addr: u64,
30 }
31
32 impl Default for GlobalState {
33     fn default() -> Self {
34         GlobalState {
35             int_to_ptr_map: Vec::default(),
36             base_addr: FxHashMap::default(),
37             next_base_addr: STACK_ADDR,
38         }
39     }
40 }
41
42 impl<'mir, 'tcx> GlobalState {
43     pub fn int_to_ptr(
44         int: u64,
45         memory: &Memory<'mir, 'tcx, Evaluator<'tcx>>,
46     ) -> InterpResult<'tcx, Pointer<Tag>> {
47         let global_state = memory.extra.intptrcast.borrow();
48         let pos = global_state.int_to_ptr_map.binary_search_by_key(&int, |(addr, _)| *addr);
49
50         Ok(match pos {
51             Ok(pos) => {
52                 let (_, alloc_id) = global_state.int_to_ptr_map[pos];
53                 // `int` is equal to the starting address for an allocation, the offset should be
54                 // zero. The pointer is untagged because it was created from a cast
55                 Pointer::new_with_tag(alloc_id, Size::from_bytes(0), Tag::Untagged)
56             }
57             Err(0) => throw_ub!(InvalidIntPointerUsage(int)),
58             Err(pos) => {
59                 // This is the largest of the adresses smaller than `int`,
60                 // i.e. the greatest lower bound (glb)
61                 let (glb, alloc_id) = global_state.int_to_ptr_map[pos - 1];
62                 // This never overflows because `int >= glb`
63                 let offset = int - glb;
64                 // If the offset exceeds the size of the allocation, this access is illegal
65                 if offset <= memory.get_size_and_align(alloc_id, AllocCheck::MaybeDead)?.0.bytes() {
66                     // This pointer is untagged because it was created from a cast
67                     Pointer::new_with_tag(alloc_id, Size::from_bytes(offset), Tag::Untagged)
68                 } else {
69                     throw_ub!(InvalidIntPointerUsage(int))
70                 }
71             }
72         })
73     }
74
75     pub fn ptr_to_int(
76         ptr: Pointer<Tag>,
77         memory: &Memory<'mir, 'tcx, Evaluator<'tcx>>,
78     ) -> InterpResult<'tcx, u64> {
79         let mut global_state = memory.extra.intptrcast.borrow_mut();
80         let global_state = &mut *global_state;
81         let id = Evaluator::canonical_alloc_id(memory, ptr.alloc_id);
82
83         // There is nothing wrong with a raw pointer being cast to an integer only after
84         // it became dangling.  Hence `MaybeDead`.
85         let (size, align) = memory.get_size_and_align(id, AllocCheck::MaybeDead)?;
86
87         let base_addr = match global_state.base_addr.entry(id) {
88             Entry::Occupied(entry) => *entry.get(),
89             Entry::Vacant(entry) => {
90                 // This allocation does not have a base address yet, pick one.
91                 // Leave some space to the previous allocation, to give it some chance to be less aligned.
92                 let slack = {
93                     let mut rng = memory.extra.rng.borrow_mut();
94                     // This means that `(global_state.next_base_addr + slack) % 16` is uniformly distributed.
95                     rng.gen_range(0, 16)
96                 };
97                 // From next_base_addr + slack, round up to adjust for alignment.
98                 let base_addr = global_state.next_base_addr.checked_add(slack).unwrap();
99                 let base_addr = Self::align_addr(base_addr, align.bytes());
100                 entry.insert(base_addr);
101                 trace!(
102                     "Assigning base address {:#x} to allocation {:?} (slack: {}, align: {})",
103                     base_addr,
104                     id,
105                     slack,
106                     align.bytes(),
107                 );
108
109                 // Remember next base address.  If this allocation is zero-sized, leave a gap
110                 // of at least 1 to avoid two allocations having the same base address.
111                 global_state.next_base_addr = base_addr.checked_add(max(size.bytes(), 1)).unwrap();
112                 // Given that `next_base_addr` increases in each allocation, pushing the
113                 // corresponding tuple keeps `int_to_ptr_map` sorted
114                 global_state.int_to_ptr_map.push((base_addr, id));
115
116                 base_addr
117             }
118         };
119
120         // Sanity check that the base address is aligned.
121         debug_assert_eq!(base_addr % align.bytes(), 0);
122         // Add offset with the right kind of pointer-overflowing arithmetic.
123         let dl = memory.data_layout();
124         Ok(dl.overflowing_offset(base_addr, ptr.offset.bytes()).0)
125     }
126
127     /// Shifts `addr` to make it aligned with `align` by rounding `addr` to the smallest multiple
128     /// of `align` that is larger or equal to `addr`
129     fn align_addr(addr: u64, align: u64) -> u64 {
130         match addr % align {
131             0 => addr,
132             rem => addr.checked_add(align).unwrap() - rem,
133         }
134     }
135 }
136
137 #[cfg(test)]
138 mod tests {
139     use super::*;
140
141     #[test]
142     fn test_align_addr() {
143         assert_eq!(GlobalState::align_addr(37, 4), 40);
144         assert_eq!(GlobalState::align_addr(44, 4), 44);
145     }
146 }