Skip to main content

miri/
meta_obj.rs

1use std::any::Any;
2use std::{fmt, iter};
3
4use rustc_abi::Size;
5
6use crate::*;
7
8/// The byte that will be filled into the memory that backs an opaque meta object.
9/// Can be basically anything, the only constraint is that we must be able to tell
10/// it apart from static initializers to avoid allowing a destryed object to be
11/// implicitly re-initialized. Therefore, this must *not* be 0x00.
12pub const OPAQUE_OBJ_COOKIE: u8 = 0x42;
13
14/// A trait for the synchronization metadata that can be attached to a memory location.
15/// Must *not* contain any provenance!
16pub trait MetaObj: Any {
17    /// Determines whether this object is opaque, which means that the underlying memory is "hidden"
18    /// from the program for as long as the meta object exists. Opaque objects have their memory
19    /// contents reset to "uninit" on creation, and are implicitly removed on writes.
20    fn opaque(&self) -> bool {
21        true
22    }
23
24    /// Determines whether reads/writes to this object's location are currently permitted.
25    /// The default is to allow them, but treat the object as opaque (see above), which means reads
26    /// will return `Uninit` and writes will destroy the meta object.
27    fn on_access<'tcx>(&self) -> InterpResult<'tcx> {
28        interp_ok(())
29    }
30}
31
32impl dyn MetaObj {
33    #[inline(always)]
34    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
35        let x: &dyn Any = self;
36        x.downcast_ref()
37    }
38
39    #[inline(always)]
40    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
41        let x: &mut dyn Any = self;
42        x.downcast_mut()
43    }
44
45    #[inline(always)]
46    pub fn downcast<T: Any>(self: Box<Self>) -> Option<Box<T>> {
47        let x: Box<dyn Any> = self;
48        x.downcast().ok()
49    }
50}
51
52impl fmt::Debug for dyn MetaObj {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.debug_struct("MetaObj").finish_non_exhaustive()
55    }
56}
57
58impl<'tcx> AllocExtra<'tcx> {
59    /// Get the meta object that starts at the given offset.
60    fn get_meta<T: MetaObj>(&self, offset: Size) -> Option<&T> {
61        self.meta_objs.get_start(offset).and_then(|s| s.downcast_ref::<T>())
62    }
63
64    /// Get the meta object that starts at the given offset.
65    fn get_meta_mut<T: MetaObj>(&mut self, offset: Size) -> Option<&mut T> {
66        self.meta_objs.get_start_mut(offset).and_then(|s| s.downcast_mut::<T>())
67    }
68
69    /// Insert a new meta object covering the given range. Any other objects that exist
70    /// in that range are removed.
71    fn insert_meta(&mut self, range: AllocRange, obj: Box<dyn MetaObj>) {
72        use data_structures::range_object_map::AccessType;
73        let pos = match self.meta_objs.access_type(range) {
74            AccessType::PerfectlyOverlapping(pos) => {
75                self.meta_objs.remove_from_pos(pos);
76                pos
77            }
78            AccessType::Empty(pos) => pos,
79            AccessType::ImperfectlyOverlapping(pos_range) => {
80                self.meta_objs.remove_pos_range(pos_range.clone());
81                pos_range.start
82            }
83        };
84        self.meta_objs.insert_at_pos(pos, range, obj);
85    }
86
87    fn remove_meta(&mut self, range: AllocRange) -> Option<Box<dyn MetaObj>> {
88        use data_structures::range_object_map::AccessType;
89        match self.meta_objs.access_type(range) {
90            AccessType::PerfectlyOverlapping(pos) => Some(self.meta_objs.remove_from_pos(pos)),
91            _ => None,
92        }
93    }
94}
95
96#[derive(Debug, Copy, Clone)]
97pub enum GetMetaError {
98    /// There is no memory behind this pointer.
99    NoMem,
100    /// There is no object stored at this location.
101    NoObj,
102}
103
104impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
105pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
106    /// Get the meta object that starts at the given offset.
107    fn try_get_meta<'a, T: MetaObj>(&'a self, ptr: Pointer) -> Result<&'a T, GetMetaError>
108    where
109        'tcx: 'a,
110    {
111        let ecx = self.eval_context_ref();
112        let Ok((alloc_id, offset, ..)) = ecx.ptr_try_get_alloc_id(ptr, 0) else {
113            return Err(GetMetaError::NoMem);
114        };
115        let info = ecx.get_alloc_info(alloc_id);
116        if info.kind != AllocKind::LiveData || offset >= info.size {
117            return Err(GetMetaError::NoMem);
118        }
119        // This cannot fail now.
120        let alloc_extra = ecx.get_alloc_extra(alloc_id).unwrap();
121        alloc_extra.get_meta::<T>(offset).ok_or(GetMetaError::NoObj)
122    }
123
124    fn insert_meta(&mut self, place: &MPlaceTy<'tcx>, obj: Box<dyn MetaObj>) -> InterpResult<'tcx> {
125        let ecx = self.eval_context_mut();
126        assert!(place.layout.size > Size::ZERO);
127
128        // Ensure there is memory here, and reset it for opaque objects.
129        // We reset to something initialized so that e.g. a typed copy of a `pthread_mutex_t`
130        // does not raise UB due to an invalid value.
131        if obj.opaque() {
132            ecx.write_bytes_ptr(
133                place.ptr(),
134                iter::repeat_n(OPAQUE_OBJ_COOKIE, place.layout.size.bytes_usize()),
135            )?;
136        } else {
137            ecx.check_ptr_access(place.ptr(), place.layout.size, CheckInAllocMsg::MemoryAccess)?;
138        }
139
140        // Now we can insert the object.
141        let (alloc_id, offset, ..) = ecx.ptr_try_get_alloc_id(place.ptr(), 0).unwrap();
142        let (alloc_extra, _machine) = ecx.get_alloc_extra_mut(alloc_id)?;
143        alloc_extra.insert_meta(AllocRange { start: offset, size: place.layout.size }, obj);
144        interp_ok(())
145    }
146
147    fn get_or_insert_meta<'a, T: MetaObj>(
148        &'a mut self,
149        place: &MPlaceTy<'tcx>,
150        obj: impl FnOnce(&mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, T>,
151    ) -> InterpResult<'tcx, &'a mut T>
152    where
153        'tcx: 'a,
154    {
155        let ecx = self.eval_context_mut();
156        let (alloc_id, offset, ..) = ecx.ptr_get_alloc_id(place.ptr(), 0)?;
157        // Sadly, without Polonius, we cannot reuse `get_meta`, and we do some double-lookups.
158        let alloc_extra = ecx.get_alloc_extra(alloc_id)?;
159        if alloc_extra.get_meta::<T>(offset).is_none() {
160            // No object yet. Create one.
161            let obj = obj(ecx)?;
162            ecx.insert_meta(place, Box::new(obj))?;
163        }
164        // Now there is an object.
165        let (alloc_extra, _machine) = ecx.get_alloc_extra_mut(alloc_id).unwrap();
166        interp_ok(alloc_extra.get_meta_mut(offset).unwrap())
167    }
168
169    fn remove_meta<'a, T: MetaObj>(
170        &'a mut self,
171        place: &MPlaceTy<'tcx>,
172    ) -> InterpResult<'tcx, Option<Box<T>>> {
173        let ecx = self.eval_context_mut();
174        let (alloc_id, offset, ..) = ecx.ptr_get_alloc_id(place.ptr(), 0)?;
175        let (alloc_extra, _machine) = ecx.get_alloc_extra_mut(alloc_id).unwrap();
176
177        interp_ok(
178            alloc_extra
179                .remove_meta(AllocRange { start: offset, size: place.layout.size })
180                .and_then(|obj| obj.downcast()),
181        )
182    }
183}