1 use super::{AllocId, InterpResult};
3 use rustc_macros::HashStable;
4 use rustc_target::abi::{HasDataLayout, Size};
6 use std::convert::{TryFrom, TryInto};
9 ////////////////////////////////////////////////////////////////////////////////
11 ////////////////////////////////////////////////////////////////////////////////
13 pub trait PointerArithmetic: HasDataLayout {
14 // These are not supposed to be overridden.
17 fn pointer_size(&self) -> Size {
18 self.data_layout().pointer_size
22 fn max_size_of_val(&self) -> Size {
23 Size::from_bytes(self.machine_isize_max())
27 fn machine_usize_max(&self) -> u64 {
28 self.pointer_size().unsigned_int_max().try_into().unwrap()
32 fn machine_isize_min(&self) -> i64 {
33 self.pointer_size().signed_int_min().try_into().unwrap()
37 fn machine_isize_max(&self) -> i64 {
38 self.pointer_size().signed_int_max().try_into().unwrap()
42 fn machine_usize_to_isize(&self, val: u64) -> 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
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()
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!
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)
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)
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();
79 let (val, over) = self.overflowing_offset(val, n);
80 (val, over || i > self.machine_isize_max())
82 let res = val.overflowing_sub(n);
83 let (val, over) = self.truncate_to_ptr(res);
84 (val, over || i < self.machine_isize_min())
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) }
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) }
101 impl<T: HasDataLayout> PointerArithmetic for T {}
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;
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;
118 /// Determines how a pointer should be printed.
119 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result
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;
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;
133 // For now, do not allow this, so that we keep our options open.
134 const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true;
136 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 // Forward `alternate` flag to `alloc_id` printing.
139 write!(f, "{:#?}", ptr.provenance)?;
141 write!(f, "{:?}", ptr.provenance)?;
143 // Print offset only if it is non-zero.
144 if ptr.offset.bytes() > 0 {
145 write!(f, "+0x{:x}", ptr.offset.bytes())?;
150 fn get_alloc_id(self) -> AllocId {
155 /// Represents a pointer in the Miri engine.
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)
165 static_assert_size!(Pointer, 16);
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)
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()),
184 /// Produces a `Pointer` that points to the beginning of the `Allocation`.
185 impl From<AllocId> for Pointer {
187 fn from(alloc_id: AllocId) -> Self {
188 Pointer::new(alloc_id, Size::ZERO)
192 impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> {
194 fn from(ptr: Pointer<Tag>) -> Self {
195 let (tag, offset) = ptr.into_parts();
196 Pointer::new(Some(tag), offset)
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),
209 impl<Tag> Pointer<Option<Tag>> {
211 pub fn null() -> Self {
212 Pointer { provenance: None, offset: Size::ZERO }
216 impl<'tcx, Tag> Pointer<Tag> {
218 pub fn new(provenance: Tag, offset: Size) -> Self {
219 Pointer { provenance, offset }
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`.
226 pub fn into_parts(self) -> (Tag, Size) {
227 (self.provenance, self.offset)
230 pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self {
231 Pointer { provenance: f(self.provenance), ..self }
235 pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
237 offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?),
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 };
250 pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
251 self.overflowing_offset(i, cx).0
255 pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
257 offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?),
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 };
270 pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
271 self.overflowing_signed_offset(i, cx).0