]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/interpret/pointer.rs
interpret: make isize::MAX the limit for dynamic value sizes
[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     /// Provenance must always be able to identify the allocation this ptr points to.
124     /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.)
125     fn get_alloc_id(self) -> AllocId;
126 }
127
128 impl Provenance for AllocId {
129     // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*,
130     // so ptr-to-int casts are not possible (since we do not know the global physical offset).
131     const OFFSET_IS_ADDR: bool = false;
132
133     // For now, do not allow this, so that we keep our options open.
134     const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true;
135
136     fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137         // Forward `alternate` flag to `alloc_id` printing.
138         if f.alternate() {
139             write!(f, "{:#?}", ptr.provenance)?;
140         } else {
141             write!(f, "{:?}", ptr.provenance)?;
142         }
143         // Print offset only if it is non-zero.
144         if ptr.offset.bytes() > 0 {
145             write!(f, "+0x{:x}", ptr.offset.bytes())?;
146         }
147         Ok(())
148     }
149
150     fn get_alloc_id(self) -> AllocId {
151         self
152     }
153 }
154
155 /// Represents a pointer in the Miri engine.
156 ///
157 /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
158 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)]
159 #[derive(HashStable)]
160 pub struct Pointer<Tag = AllocId> {
161     pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Tag` type)
162     pub provenance: Tag,
163 }
164
165 static_assert_size!(Pointer, 16);
166
167 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
168 // all the Miri types.
169 impl<Tag: Provenance> fmt::Debug for Pointer<Tag> {
170     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171         Provenance::fmt(self, f)
172     }
173 }
174
175 impl<Tag: Provenance> fmt::Debug for Pointer<Option<Tag>> {
176     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177         match self.provenance {
178             Some(tag) => Provenance::fmt(&Pointer::new(tag, self.offset), f),
179             None => write!(f, "0x{:x}", self.offset.bytes()),
180         }
181     }
182 }
183
184 /// Produces a `Pointer` that points to the beginning of the `Allocation`.
185 impl From<AllocId> for Pointer {
186     #[inline(always)]
187     fn from(alloc_id: AllocId) -> Self {
188         Pointer::new(alloc_id, Size::ZERO)
189     }
190 }
191
192 impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> {
193     #[inline(always)]
194     fn from(ptr: Pointer<Tag>) -> Self {
195         let (tag, offset) = ptr.into_parts();
196         Pointer::new(Some(tag), offset)
197     }
198 }
199
200 impl<Tag> Pointer<Option<Tag>> {
201     pub fn into_pointer_or_addr(self) -> Result<Pointer<Tag>, Size> {
202         match self.provenance {
203             Some(tag) => Ok(Pointer::new(tag, self.offset)),
204             None => Err(self.offset),
205         }
206     }
207 }
208
209 impl<Tag> Pointer<Option<Tag>> {
210     #[inline(always)]
211     pub fn null() -> Self {
212         Pointer { provenance: None, offset: Size::ZERO }
213     }
214 }
215
216 impl<'tcx, Tag> Pointer<Tag> {
217     #[inline(always)]
218     pub fn new(provenance: Tag, offset: Size) -> Self {
219         Pointer { provenance, offset }
220     }
221
222     /// Obtain the constituents of this pointer. Not that the meaning of the offset depends on the type `Tag`!
223     /// This function must only be used in the implementation of `Machine::ptr_get_alloc`,
224     /// and when a `Pointer` is taken apart to be stored efficiently in an `Allocation`.
225     #[inline(always)]
226     pub fn into_parts(self) -> (Tag, Size) {
227         (self.provenance, self.offset)
228     }
229
230     pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self {
231         Pointer { provenance: f(self.provenance), ..self }
232     }
233
234     #[inline]
235     pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
236         Ok(Pointer {
237             offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?),
238             ..self
239         })
240     }
241
242     #[inline]
243     pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) {
244         let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes());
245         let ptr = Pointer { offset: Size::from_bytes(res), ..self };
246         (ptr, over)
247     }
248
249     #[inline(always)]
250     pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
251         self.overflowing_offset(i, cx).0
252     }
253
254     #[inline]
255     pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
256         Ok(Pointer {
257             offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?),
258             ..self
259         })
260     }
261
262     #[inline]
263     pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) {
264         let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i);
265         let ptr = Pointer { offset: Size::from_bytes(res), ..self };
266         (ptr, over)
267     }
268
269     #[inline(always)]
270     pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
271         self.overflowing_signed_offset(i, cx).0
272     }
273 }