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