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