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 /// 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>;
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>;
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;
138 // For now, do not allow this, so that we keep our options open.
139 const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = true;
141 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 // Forward `alternate` flag to `alloc_id` printing.
144 write!(f, "{:#?}", ptr.provenance)?;
146 write!(f, "{:?}", ptr.provenance)?;
148 // Print offset only if it is non-zero.
149 if ptr.offset.bytes() > 0 {
150 write!(f, "+{:#x}", ptr.offset.bytes())?;
155 fn get_alloc_id(self) -> Option<AllocId> {
159 fn join(_left: Option<Self>, _right: Option<Self>) -> Option<Self> {
160 panic!("merging provenance is not supported when `OFFSET_IS_ADDR` is false")
164 /// Represents a pointer in the Miri engine.
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,
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);
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)
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()),
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")
201 fmt::Debug::fmt(self, f)
206 /// Produces a `Pointer` that points to the beginning of the `Allocation`.
207 impl From<AllocId> for Pointer {
209 fn from(alloc_id: AllocId) -> Self {
210 Pointer::new(alloc_id, Size::ZERO)
214 impl<Prov> From<Pointer<Prov>> for Pointer<Option<Prov>> {
216 fn from(ptr: Pointer<Prov>) -> Self {
217 let (prov, offset) = ptr.into_parts();
218 Pointer::new(Some(prov), offset)
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.
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),
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
240 assert!(Prov::OFFSET_IS_ADDR);
245 impl<Prov> Pointer<Option<Prov>> {
247 pub fn from_addr(addr: u64) -> Self {
248 Pointer { provenance: None, offset: Size::from_bytes(addr) }
252 pub fn null() -> Self {
253 Pointer::from_addr(0)
257 impl<'tcx, Prov> Pointer<Prov> {
259 pub fn new(provenance: Prov, offset: Size) -> Self {
260 Pointer { provenance, offset }
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`.
267 pub fn into_parts(self) -> (Prov, Size) {
268 (self.provenance, self.offset)
271 pub fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
272 Pointer { provenance: f(self.provenance), ..self }
276 pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
278 offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?),
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 };
291 pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
292 self.overflowing_offset(i, cx).0
296 pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
298 offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?),
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 };
311 pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
312 self.overflowing_signed_offset(i, cx).0