rustc_middle/mir/interpret/
pointer.rs

1use std::fmt;
2use std::num::NonZero;
3
4use rustc_abi::{HasDataLayout, Size};
5use rustc_data_structures::static_assert_size;
6use rustc_macros::{HashStable, TyDecodable, TyEncodable};
7
8use super::AllocId;
9
10////////////////////////////////////////////////////////////////////////////////
11// Pointer arithmetic
12////////////////////////////////////////////////////////////////////////////////
13
14pub trait PointerArithmetic: HasDataLayout {
15    // These are not supposed to be overridden.
16
17    #[inline(always)]
18    fn pointer_size(&self) -> Size {
19        self.data_layout().pointer_size()
20    }
21
22    #[inline(always)]
23    fn max_size_of_val(&self) -> Size {
24        Size::from_bytes(self.target_isize_max())
25    }
26
27    #[inline]
28    fn target_usize_max(&self) -> u64 {
29        self.pointer_size().unsigned_int_max().try_into().unwrap()
30    }
31
32    #[inline]
33    fn target_isize_min(&self) -> i64 {
34        self.pointer_size().signed_int_min().try_into().unwrap()
35    }
36
37    #[inline]
38    fn target_isize_max(&self) -> i64 {
39        self.pointer_size().signed_int_max().try_into().unwrap()
40    }
41
42    #[inline]
43    fn truncate_to_target_usize(&self, val: u64) -> u64 {
44        self.pointer_size().truncate(val.into()).try_into().unwrap()
45    }
46
47    #[inline]
48    fn sign_extend_to_target_isize(&self, val: u64) -> i64 {
49        self.pointer_size().sign_extend(val.into()).try_into().unwrap()
50    }
51}
52
53impl<T: HasDataLayout> PointerArithmetic for T {}
54
55/// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is
56/// mostly opaque; the `Machine` trait extends it with some more operations that also have access to
57/// some global state.
58/// The `Debug` rendering is used to display bare provenance, and for the default impl of `fmt`.
59pub trait Provenance: Copy + PartialEq + fmt::Debug + 'static {
60    /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address.
61    /// - If `false`, the offset *must* be relative. This means the bytes representing a pointer are
62    ///   different from what the Abstract Machine prescribes, so the interpreter must prevent any
63    ///   operation that would inspect the underlying bytes of a pointer, such as ptr-to-int
64    ///   transmutation. A `ReadPointerAsBytes` error will be raised in such situations.
65    /// - If `true`, the interpreter will permit operations to inspect the underlying bytes of a
66    ///   pointer, and implement ptr-to-int transmutation by stripping provenance.
67    const OFFSET_IS_ADDR: bool;
68
69    /// If wildcard provenance is implemented, contains the unique, general wildcard provenance variant.
70    const WILDCARD: Option<Self>;
71
72    /// Determines how a pointer should be printed.
73    fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result;
74
75    /// If `OFFSET_IS_ADDR == false`, provenance must always be able to
76    /// identify the allocation this ptr points to (i.e., this must return `Some`).
77    /// Otherwise this function is best-effort (but must agree with `Machine::ptr_get_alloc`).
78    /// (Identifying the offset in that allocation, however, is harder -- use `Memory::ptr_get_alloc` for that.)
79    fn get_alloc_id(self) -> Option<AllocId>;
80}
81
82/// The type of provenance in the compile-time interpreter.
83/// This is a packed representation of:
84/// - an `AllocId` (non-zero)
85/// - an `immutable: bool`
86/// - a `shared_ref: bool`
87///
88/// with the extra invariant that if `immutable` is `true`, then so
89/// is `shared_ref`.
90#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
91pub struct CtfeProvenance(NonZero<u64>);
92
93impl From<AllocId> for CtfeProvenance {
94    fn from(value: AllocId) -> Self {
95        let prov = CtfeProvenance(value.0);
96        assert!(
97            prov.alloc_id() == value,
98            "`AllocId` with the highest bits set cannot be used in CTFE"
99        );
100        prov
101    }
102}
103
104impl fmt::Debug for CtfeProvenance {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        fmt::Debug::fmt(&self.alloc_id(), f)?; // propagates `alternate` flag
107        if self.immutable() {
108            write!(f, "<imm>")?;
109        }
110        Ok(())
111    }
112}
113
114const IMMUTABLE_MASK: u64 = 1 << 63; // the highest bit
115const SHARED_REF_MASK: u64 = 1 << 62;
116const ALLOC_ID_MASK: u64 = u64::MAX & !IMMUTABLE_MASK & !SHARED_REF_MASK;
117
118impl CtfeProvenance {
119    /// Returns the `AllocId` of this provenance.
120    #[inline(always)]
121    pub fn alloc_id(self) -> AllocId {
122        AllocId(NonZero::new(self.0.get() & ALLOC_ID_MASK).unwrap())
123    }
124
125    /// Returns whether this provenance is immutable.
126    #[inline]
127    pub fn immutable(self) -> bool {
128        self.0.get() & IMMUTABLE_MASK != 0
129    }
130
131    /// Returns whether this provenance is derived from a shared reference.
132    #[inline]
133    pub fn shared_ref(self) -> bool {
134        self.0.get() & SHARED_REF_MASK != 0
135    }
136
137    pub fn into_parts(self) -> (AllocId, bool, bool) {
138        (self.alloc_id(), self.immutable(), self.shared_ref())
139    }
140
141    pub fn from_parts((alloc_id, immutable, shared_ref): (AllocId, bool, bool)) -> Self {
142        let prov = CtfeProvenance::from(alloc_id);
143        if immutable {
144            // This sets both flags, so we don't even have to check `shared_ref`.
145            prov.as_immutable()
146        } else if shared_ref {
147            prov.as_shared_ref()
148        } else {
149            prov
150        }
151    }
152
153    /// Returns an immutable version of this provenance.
154    #[inline]
155    pub fn as_immutable(self) -> Self {
156        CtfeProvenance(self.0 | IMMUTABLE_MASK | SHARED_REF_MASK)
157    }
158
159    /// Returns a "shared reference" (but not necessarily immutable!) version of this provenance.
160    #[inline]
161    pub fn as_shared_ref(self) -> Self {
162        CtfeProvenance(self.0 | SHARED_REF_MASK)
163    }
164}
165
166impl Provenance for CtfeProvenance {
167    // With the `CtfeProvenance` as provenance, the `offset` is interpreted *relative to the allocation*,
168    // so ptr-to-int casts are not possible (since we do not know the global physical offset).
169    const OFFSET_IS_ADDR: bool = false;
170
171    // `CtfeProvenance` does not implement wildcard provenance.
172    const WILDCARD: Option<Self> = None;
173
174    fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        // Print AllocId.
176        fmt::Debug::fmt(&ptr.provenance.alloc_id(), f)?; // propagates `alternate` flag
177        // Print offset only if it is non-zero.
178        if ptr.offset.bytes() > 0 {
179            write!(f, "+{:#x}", ptr.offset.bytes())?;
180        }
181        // Print immutable status.
182        if ptr.provenance.immutable() {
183            write!(f, "<imm>")?;
184        }
185        Ok(())
186    }
187
188    fn get_alloc_id(self) -> Option<AllocId> {
189        Some(self.alloc_id())
190    }
191}
192
193// We also need this impl so that one can debug-print `Pointer<AllocId>`
194impl Provenance for AllocId {
195    // With the `AllocId` as provenance, the `offset` is interpreted *relative to the allocation*,
196    // so ptr-to-int casts are not possible (since we do not know the global physical offset).
197    const OFFSET_IS_ADDR: bool = false;
198
199    // `AllocId` does not implement wildcard provenance.
200    const WILDCARD: Option<Self> = None;
201
202    fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        // Forward `alternate` flag to `alloc_id` printing.
204        if f.alternate() {
205            write!(f, "{:#?}", ptr.provenance)?;
206        } else {
207            write!(f, "{:?}", ptr.provenance)?;
208        }
209        // Print offset only if it is non-zero.
210        if ptr.offset.bytes() > 0 {
211            write!(f, "+{:#x}", ptr.offset.bytes())?;
212        }
213        Ok(())
214    }
215
216    fn get_alloc_id(self) -> Option<AllocId> {
217        Some(self)
218    }
219}
220
221/// Represents a pointer in the Miri engine.
222///
223/// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
224#[derive(Copy, Clone, Eq, PartialEq, TyEncodable, TyDecodable, Hash)]
225#[derive(HashStable)]
226pub struct Pointer<Prov = CtfeProvenance> {
227    pub(super) offset: Size, // kept private to avoid accidental misinterpretation (meaning depends on `Prov` type)
228    pub provenance: Prov,
229}
230
231static_assert_size!(Pointer, 16);
232// `Option<Prov>` pointers are also passed around quite a bit
233// (but not stored in permanent machine state).
234static_assert_size!(Pointer<Option<CtfeProvenance>>, 16);
235
236// We want the `Debug` output to be readable as it is used by `derive(Debug)` for
237// all the Miri types.
238impl<Prov: Provenance> fmt::Debug for Pointer<Prov> {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        Provenance::fmt(self, f)
241    }
242}
243
244impl<Prov: Provenance> fmt::Debug for Pointer<Option<Prov>> {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        match self.provenance {
247            Some(prov) => Provenance::fmt(&Pointer::new(prov, self.offset), f),
248            None => write!(f, "{:#x}[noalloc]", self.offset.bytes()),
249        }
250    }
251}
252
253impl<Prov: Provenance> fmt::Display for Pointer<Option<Prov>> {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        if self.provenance.is_none() && self.offset.bytes() == 0 {
256            write!(f, "null pointer")
257        } else {
258            fmt::Debug::fmt(self, f)
259        }
260    }
261}
262
263/// Produces a `Pointer` that points to the beginning of the `Allocation`.
264impl From<AllocId> for Pointer {
265    #[inline(always)]
266    fn from(alloc_id: AllocId) -> Self {
267        Pointer::new(alloc_id.into(), Size::ZERO)
268    }
269}
270impl From<CtfeProvenance> for Pointer {
271    #[inline(always)]
272    fn from(prov: CtfeProvenance) -> Self {
273        Pointer::new(prov, Size::ZERO)
274    }
275}
276
277impl<Prov> From<Pointer<Prov>> for Pointer<Option<Prov>> {
278    #[inline(always)]
279    fn from(ptr: Pointer<Prov>) -> Self {
280        let (prov, offset) = ptr.into_raw_parts();
281        Pointer::new(Some(prov), offset)
282    }
283}
284
285impl<Prov> Pointer<Option<Prov>> {
286    /// Convert this pointer that *might* have a provenance into a pointer that *definitely* has a
287    /// provenance, or an absolute address.
288    ///
289    /// This is rarely what you want; call `ptr_try_get_alloc_id` instead.
290    pub fn into_pointer_or_addr(self) -> Result<Pointer<Prov>, Size> {
291        match self.provenance {
292            Some(prov) => Ok(Pointer::new(prov, self.offset)),
293            None => Err(self.offset),
294        }
295    }
296
297    /// Returns the absolute address the pointer points to.
298    /// Only works if Prov::OFFSET_IS_ADDR is true!
299    pub fn addr(self) -> Size
300    where
301        Prov: Provenance,
302    {
303        assert!(Prov::OFFSET_IS_ADDR);
304        self.offset
305    }
306
307    /// Creates a pointer to the given address, with invalid provenance (i.e., cannot be used for
308    /// any memory access).
309    #[inline(always)]
310    pub fn without_provenance(addr: u64) -> Self {
311        Pointer { provenance: None, offset: Size::from_bytes(addr) }
312    }
313
314    #[inline(always)]
315    pub fn null() -> Self {
316        Pointer::without_provenance(0)
317    }
318}
319
320impl<Prov> Pointer<Prov> {
321    #[inline(always)]
322    pub fn new(provenance: Prov, offset: Size) -> Self {
323        Pointer { provenance, offset }
324    }
325
326    /// Obtain the constituents of this pointer. Note that the meaning of the offset depends on the
327    /// type `Prov`! This is a low-level function that should only be used when absolutely
328    /// necessary. Prefer `prov_and_relative_offset` if possible.
329    #[inline(always)]
330    pub fn into_raw_parts(self) -> (Prov, Size) {
331        (self.provenance, self.offset)
332    }
333
334    pub fn map_provenance(self, f: impl FnOnce(Prov) -> Prov) -> Self {
335        Pointer { provenance: f(self.provenance), ..self }
336    }
337
338    #[inline(always)]
339    pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
340        let res =
341            cx.data_layout().truncate_to_target_usize(self.offset.bytes().wrapping_add(i.bytes()));
342        Pointer { offset: Size::from_bytes(res), ..self }
343    }
344
345    #[inline(always)]
346    pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
347        // It's wrapping anyway, so we can just cast to `u64`.
348        self.wrapping_offset(Size::from_bytes(i as u64), cx)
349    }
350}
351
352impl Pointer<CtfeProvenance> {
353    /// Return the provenance and relative offset stored in this pointer. Safer alternative to
354    /// `into_raw_parts` since the type ensures that the offset is indeed relative.
355    #[inline(always)]
356    pub fn prov_and_relative_offset(self) -> (CtfeProvenance, Size) {
357        (self.provenance, self.offset)
358    }
359}