]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/interpret/pointer.rs
5fa802236edd307def377e7c33d8e63d87062fb7
[rust.git] / compiler / rustc_middle / src / mir / interpret / pointer.rs
1 use super::{AllocId, InterpResult};
2
3 use rustc_macros::HashStable;
4 use rustc_target::abi::{HasDataLayout, Size};
5
6 use std::convert::{TryFrom, TryInto};
7 use std::fmt;
8
9 ////////////////////////////////////////////////////////////////////////////////
10 // Pointer arithmetic
11 ////////////////////////////////////////////////////////////////////////////////
12
13 pub trait PointerArithmetic: HasDataLayout {
14     // These are not supposed to be overridden.
15
16     #[inline(always)]
17     fn pointer_size(&self) -> Size {
18         self.data_layout().pointer_size
19     }
20
21     #[inline(always)]
22     fn max_size_of_val(&self) -> Size {
23         Size::from_bytes(self.machine_isize_max())
24     }
25
26     #[inline]
27     fn machine_usize_max(&self) -> u64 {
28         self.pointer_size().unsigned_int_max().try_into().unwrap()
29     }
30
31     #[inline]
32     fn machine_isize_min(&self) -> i64 {
33         self.pointer_size().signed_int_min().try_into().unwrap()
34     }
35
36     #[inline]
37     fn machine_isize_max(&self) -> i64 {
38         self.pointer_size().signed_int_max().try_into().unwrap()
39     }
40
41     #[inline]
42     fn machine_usize_to_isize(&self, val: u64) -> i64 {
43         let val = val as i64;
44         // Now wrap-around into the machine_isize range.
45         if val > self.machine_isize_max() {
46             // This can only happen the the ptr size is < 64, so we know max_usize_plus_1 fits into
47             // i64.
48             debug_assert!(self.pointer_size().bits() < 64);
49             let max_usize_plus_1 = 1u128 << self.pointer_size().bits();
50             val - i64::try_from(max_usize_plus_1).unwrap()
51         } else {
52             val
53         }
54     }
55
56     /// Helper function: truncate given value-"overflowed flag" pair to pointer size and
57     /// update "overflowed flag" if there was an overflow.
58     /// This should be called by all the other methods before returning!
59     #[inline]
60     fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) {
61         let val = u128::from(val);
62         let max_ptr_plus_1 = 1u128 << self.pointer_size().bits();
63         (u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1)
64     }
65
66     #[inline]
67     fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) {
68         // We do not need to check if i fits in a machine usize. If it doesn't,
69         // either the wrapping_add will wrap or res will not fit in a pointer.
70         let res = val.overflowing_add(i);
71         self.truncate_to_ptr(res)
72     }
73
74     #[inline]
75     fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) {
76         // We need to make sure that i fits in a machine isize.
77         let n = i.unsigned_abs();
78         if i >= 0 {
79             let (val, over) = self.overflowing_offset(val, n);
80             (val, over || i > self.machine_isize_max())
81         } else {
82             let res = val.overflowing_sub(n);
83             let (val, over) = self.truncate_to_ptr(res);
84             (val, over || i < self.machine_isize_min())
85         }
86     }
87
88     #[inline]
89     fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> {
90         let (res, over) = self.overflowing_offset(val, i);
91         if over { throw_ub!(PointerArithOverflow) } else { Ok(res) }
92     }
93
94     #[inline]
95     fn signed_offset<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> {
96         let (res, over) = self.overflowing_signed_offset(val, i);
97         if over { throw_ub!(PointerArithOverflow) } else { Ok(res) }
98     }
99 }
100
101 impl<T: HasDataLayout> PointerArithmetic for T {}
102
103 /// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is
104 /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to
105 /// some global state.
106 /// We don't actually care about this `Debug` bound (we use `Provenance::fmt` to format the entire
107 /// pointer), but `derive` adds some unnecessary bounds.
108 pub trait Provenance: Copy + fmt::Debug {
109     /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address.
110     /// If `true, ptr-to-int casts work by simply discarding the provenance.
111     /// If `false`, ptr-to-int casts are not supported. The offset *must* be relative in that case.
112     const OFFSET_IS_ADDR: bool;
113
114     /// We also use this trait to control whether to abort execution when a pointer is being partially overwritten
115     /// (this avoids a separate trait in `allocation.rs` just for this purpose).
116     const ERR_ON_PARTIAL_PTR_OVERWRITE: bool;
117
118     /// Determines how a pointer should be printed.
119     fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result
120     where
121         Self: Sized;
122
123     /// If `OFFSET_IS_ADDR == false`, provenance must always be able to
124     /// identify the allocation this ptr points to (i.e., this must return `Some`).
125     /// Otherwise this function is best-effort (but must agree with `Machine::ptr_get_alloc`).
126     /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.)
127     fn get_alloc_id(self) -> Option<AllocId>;
128
129     /// Defines the 'join' of provenance: what happens when doing a pointer load and different bytes have different provenance.
130     fn join(left: Option<Self>, right: Option<Self>) -> Option<Self>;
131 }
132
133 impl Provenance for AllocId {
134     // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*,
135     // so ptr-to-int casts are not possible (since we do not know the global physical offset).
136     const OFFSET_IS_ADDR: bool = false;
137
138     // For now, do not allow this, so that we keep our options open.
139     const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true;
140
141     fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142         // Forward `alternate` flag to `alloc_id` printing.
143         if f.alternate() {
144             write!(f, "{:#?}", ptr.provenance)?;
145         } else {
146             write!(f, "{:?}", ptr.provenance)?;
147         }
148         // Print offset only if it is non-zero.
149         if ptr.offset.bytes() > 0 {
150             write!(f, "+{:#x}", ptr.offset.bytes())?;
151         }
152         Ok(())
153     }
154
155     fn get_alloc_id(self) -> Option<AllocId> {
156         Some(self)
157     }
158
159     fn join(_left: Option<Self>, _right: Option<Self>) -> Option<Self> {
160         panic!("merging provenance is not supported when `OFFSET_IS_ADDR` is false")
161     }
162 }
163
164 /// Represents a pointer in the Miri engine.
165 ///
166 /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
167 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)]
168 #[derive(HashStable)]
169 pub struct Pointer<Prov = AllocId> {
170     pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Prov` type)
171     pub provenance: Prov,
172 }
173
174 static_assert_size!(Pointer, 16);
175 // `Option<Prov>` pointers are also passed around quite a bit
176 // (but not stored in permanent machine state).
177 static_assert_size!(Pointer<Option<AllocId>>, 16);
178
179 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
180 // all the Miri types.
181 impl<Prov: Provenance> fmt::Debug for Pointer<Prov> {
182     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183         Provenance::fmt(self, f)
184     }
185 }
186
187 impl<Prov: Provenance> fmt::Debug for Pointer<Option<Prov>> {
188     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189         match self.provenance {
190             Some(prov) => Provenance::fmt(&Pointer::new(prov, self.offset), f),
191             None => write!(f, "{:#x}[noalloc]", self.offset.bytes()),
192         }
193     }
194 }
195
196 impl<Prov: Provenance> fmt::Display for Pointer<Option<Prov>> {
197     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198         if self.provenance.is_none() && self.offset.bytes() == 0 {
199             write!(f, "null pointer")
200         } else {
201             fmt::Debug::fmt(self, f)
202         }
203     }
204 }
205
206 /// Produces a `Pointer` that points to the beginning of the `Allocation`.
207 impl From<AllocId> for Pointer {
208     #[inline(always)]
209     fn from(alloc_id: AllocId) -> Self {
210         Pointer::new(alloc_id, Size::ZERO)
211     }
212 }
213
214 impl<Prov> From<Pointer<Prov>> for Pointer<Option<Prov>> {
215     #[inline(always)]
216     fn from(ptr: Pointer<Prov>) -> Self {
217         let (prov, offset) = ptr.into_parts();
218         Pointer::new(Some(prov), offset)
219     }
220 }
221
222 impl<Prov> Pointer<Option<Prov>> {
223     /// Convert this pointer that *might* have a provenance into a pointer that *definitely* has a
224     /// provenance, or an absolute address.
225     ///
226     /// This is rarely what you want; call `ptr_try_get_alloc_id` instead.
227     pub fn into_pointer_or_addr(self) -> Result<Pointer<Prov>, Size> {
228         match self.provenance {
229             Some(prov) => Ok(Pointer::new(prov, self.offset)),
230             None => Err(self.offset),
231         }
232     }
233
234     /// Returns the absolute address the pointer points to.
235     /// Only works if Prov::OFFSET_IS_ADDR is true!
236     pub fn addr(self) -> Size
237     where
238         Prov: Provenance,
239     {
240         assert!(Prov::OFFSET_IS_ADDR);
241         self.offset
242     }
243 }
244
245 impl<Prov> Pointer<Option<Prov>> {
246     #[inline(always)]
247     pub fn from_addr(addr: u64) -> Self {
248         Pointer { provenance: None, offset: Size::from_bytes(addr) }
249     }
250
251     #[inline(always)]
252     pub fn null() -> Self {
253         Pointer::from_addr(0)
254     }
255 }
256
257 impl<'tcx, Prov> Pointer<Prov> {
258     #[inline(always)]
259     pub fn new(provenance: Prov, offset: Size) -> Self {
260         Pointer { provenance, offset }
261     }
262
263     /// Obtain the constituents of this pointer. Not that the meaning of the offset depends on the type `Prov`!
264     /// This function must only be used in the implementation of `Machine::ptr_get_alloc`,
265     /// and when a `Pointer` is taken apart to be stored efficiently in an `Allocation`.
266     #[inline(always)]
267     pub fn into_parts(self) -> (Prov, Size) {
268         (self.provenance, self.offset)
269     }
270
271     pub fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
272         Pointer { provenance: f(self.provenance), ..self }
273     }
274
275     #[inline]
276     pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
277         Ok(Pointer {
278             offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?),
279             ..self
280         })
281     }
282
283     #[inline]
284     pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) {
285         let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes());
286         let ptr = Pointer { offset: Size::from_bytes(res), ..self };
287         (ptr, over)
288     }
289
290     #[inline(always)]
291     pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
292         self.overflowing_offset(i, cx).0
293     }
294
295     #[inline]
296     pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
297         Ok(Pointer {
298             offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?),
299             ..self
300         })
301     }
302
303     #[inline]
304     pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) {
305         let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i);
306         let ptr = Pointer { offset: Size::from_bytes(res), ..self };
307         (ptr, over)
308     }
309
310     #[inline(always)]
311     pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
312         self.overflowing_signed_offset(i, cx).0
313     }
314 }