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