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 machine_usize_max(&self) -> u64 {
23 self.pointer_size().unsigned_int_max().try_into().unwrap()
27 fn machine_isize_min(&self) -> i64 {
28 self.pointer_size().signed_int_min().try_into().unwrap()
32 fn machine_isize_max(&self) -> i64 {
33 self.pointer_size().signed_int_max().try_into().unwrap()
37 fn machine_usize_to_isize(&self, val: u64) -> 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
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()
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!
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)
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)
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();
74 let (val, over) = self.overflowing_offset(val, n);
75 (val, over || i > self.machine_isize_max())
77 let res = val.overflowing_sub(n);
78 let (val, over) = self.truncate_to_ptr(res);
79 (val, over || i < self.machine_isize_min())
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) }
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) }
96 impl<T: HasDataLayout> PointerArithmetic for T {}
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 unecessary 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;
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;
113 /// Determines how a pointer should be printed.
114 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result
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;
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;
128 // For now, do not allow this, so that we keep our options open.
129 const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true;
131 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 // Forward `alternate` flag to `alloc_id` printing.
134 write!(f, "{:#?}", ptr.provenance)?;
136 write!(f, "{:?}", ptr.provenance)?;
138 // Print offset only if it is non-zero.
139 if ptr.offset.bytes() > 0 {
140 write!(f, "+0x{:x}", ptr.offset.bytes())?;
145 fn get_alloc_id(self) -> AllocId {
150 /// Represents a pointer in the Miri engine.
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)
160 static_assert_size!(Pointer, 16);
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)
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()),
179 /// Produces a `Pointer` that points to the beginning of the `Allocation`.
180 impl From<AllocId> for Pointer {
182 fn from(alloc_id: AllocId) -> Self {
183 Pointer::new(alloc_id, Size::ZERO)
187 impl<Tag> From<Pointer<Tag>> for Pointer<Option<Tag>> {
189 fn from(ptr: Pointer<Tag>) -> Self {
190 let (tag, offset) = ptr.into_parts();
191 Pointer::new(Some(tag), offset)
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),
204 impl<Tag> Pointer<Option<Tag>> {
206 pub fn null() -> Self {
207 Pointer { provenance: None, offset: Size::ZERO }
211 impl<'tcx, Tag> Pointer<Tag> {
213 pub fn new(provenance: Tag, offset: Size) -> Self {
214 Pointer { provenance, offset }
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`.
221 pub fn into_parts(self) -> (Tag, Size) {
222 (self.provenance, self.offset)
225 pub fn map_provenance(self, f: impl FnOnce(Tag) -> Tag) -> Self {
226 Pointer { provenance: f(self.provenance), ..self }
230 pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
232 offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?),
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 };
245 pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
246 self.overflowing_offset(i, cx).0
250 pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
252 offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?),
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 };
265 pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
266 self.overflowing_signed_offset(i, cx).0