rustc_middle/mir/interpret/allocation/
provenance_map.rs

1//! Store the provenance for each byte in the range, with a more efficient
2//! representation for the common case where PTR_SIZE consecutive bytes have the same provenance.
3
4use std::cmp;
5use std::ops::Range;
6
7use rustc_abi::{HasDataLayout, Size};
8use rustc_data_structures::sorted_map::SortedMap;
9use rustc_macros::HashStable;
10use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
11use tracing::trace;
12
13use super::{AllocRange, CtfeProvenance, Provenance, alloc_range};
14
15/// Stores the provenance information of pointers stored in memory.
16#[derive(Clone, PartialEq, Eq, Hash, Debug)]
17#[derive(HashStable)]
18pub struct ProvenanceMap<Prov = CtfeProvenance> {
19    /// `Provenance` in this map applies from the given offset for an entire pointer-size worth of
20    /// bytes. Two entries in this map are always at least a pointer size apart.
21    ptrs: SortedMap<Size, Prov>,
22    /// This stores byte-sized provenance fragments.
23    /// The `u8` indicates the position of this byte inside its original pointer.
24    /// If the bytes are re-assembled in their original order, the pointer can be used again.
25    /// Wildcard provenance is allowed to have index 0 everywhere.
26    bytes: Option<Box<SortedMap<Size, (Prov, u8)>>>,
27}
28
29// These impls are generic over `Prov` since `CtfeProvenance` is only decodable/encodable
30// for some particular `D`/`S`.
31impl<D: Decoder, Prov: Provenance + Decodable<D>> Decodable<D> for ProvenanceMap<Prov> {
32    fn decode(d: &mut D) -> Self {
33        // `bytes` is not in the serialized format
34        Self { ptrs: Decodable::decode(d), bytes: None }
35    }
36}
37impl<S: Encoder, Prov: Provenance + Encodable<S>> Encodable<S> for ProvenanceMap<Prov> {
38    fn encode(&self, s: &mut S) {
39        let Self { ptrs, bytes } = self;
40        assert!(bytes.is_none()); // interning refuses allocations with pointer fragments
41        ptrs.encode(s)
42    }
43}
44
45impl<Prov> ProvenanceMap<Prov> {
46    pub fn new() -> Self {
47        ProvenanceMap { ptrs: SortedMap::new(), bytes: None }
48    }
49
50    /// The caller must guarantee that the given provenance list is already sorted
51    /// by address and contain no duplicates.
52    pub fn from_presorted_ptrs(r: Vec<(Size, Prov)>) -> Self {
53        ProvenanceMap { ptrs: SortedMap::from_presorted_elements(r), bytes: None }
54    }
55}
56
57impl ProvenanceMap {
58    /// Give access to the ptr-sized provenances (which can also be thought of as relocations, and
59    /// indeed that is how codegen treats them).
60    ///
61    /// Only use on interned allocations, as other allocations may have per-byte provenance!
62    #[inline]
63    pub fn ptrs(&self) -> &SortedMap<Size, CtfeProvenance> {
64        assert!(self.bytes.is_none(), "`ptrs()` called on non-interned allocation");
65        &self.ptrs
66    }
67}
68
69impl<Prov: Provenance> ProvenanceMap<Prov> {
70    fn adjusted_range_ptrs(range: AllocRange, cx: &impl HasDataLayout) -> Range<Size> {
71        // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
72        // the beginning of this range.
73        let adjusted_start = Size::from_bytes(
74            range.start.bytes().saturating_sub(cx.data_layout().pointer_size().bytes() - 1),
75        );
76        adjusted_start..range.end()
77    }
78
79    /// Returns all ptr-sized provenance in the given range.
80    /// If the range has length 0, returns provenance that crosses the edge between `start-1` and
81    /// `start`.
82    pub(super) fn range_ptrs_get(
83        &self,
84        range: AllocRange,
85        cx: &impl HasDataLayout,
86    ) -> &[(Size, Prov)] {
87        self.ptrs.range(Self::adjusted_range_ptrs(range, cx))
88    }
89
90    /// `pm.range_ptrs_is_empty(r, cx)` == `pm.range_ptrs_get(r, cx).is_empty()`, but is faster.
91    fn range_ptrs_is_empty(&self, range: AllocRange, cx: &impl HasDataLayout) -> bool {
92        self.ptrs.range_is_empty(Self::adjusted_range_ptrs(range, cx))
93    }
94
95    /// Returns all byte-wise provenance in the given range.
96    fn range_bytes_get(&self, range: AllocRange) -> &[(Size, (Prov, u8))] {
97        if let Some(bytes) = self.bytes.as_ref() {
98            bytes.range(range.start..range.end())
99        } else {
100            &[]
101        }
102    }
103
104    /// Same as `range_bytes_get(range).is_empty()`, but faster.
105    fn range_bytes_is_empty(&self, range: AllocRange) -> bool {
106        self.bytes.as_ref().is_none_or(|bytes| bytes.range_is_empty(range.start..range.end()))
107    }
108
109    /// Get the provenance of a single byte.
110    pub fn get_byte(&self, offset: Size, cx: &impl HasDataLayout) -> Option<(Prov, u8)> {
111        let prov = self.range_ptrs_get(alloc_range(offset, Size::from_bytes(1)), cx);
112        debug_assert!(prov.len() <= 1);
113        if let Some(entry) = prov.first() {
114            // If it overlaps with this byte, it is on this byte.
115            debug_assert!(self.bytes.as_ref().is_none_or(|b| !b.contains_key(&offset)));
116            Some((entry.1, (offset - entry.0).bytes() as u8))
117        } else {
118            // Look up per-byte provenance.
119            self.bytes.as_ref().and_then(|b| b.get(&offset).copied())
120        }
121    }
122
123    /// Attempt to merge per-byte provenance back into ptr chunks, if the right fragments
124    /// sit next to each other. Return `false` is that is not possible due to partial pointers.
125    pub fn merge_bytes(&mut self, cx: &impl HasDataLayout) -> bool {
126        let Some(bytes) = self.bytes.as_deref_mut() else {
127            return true;
128        };
129        let ptr_size = cx.data_layout().pointer_size();
130        while let Some((offset, (prov, _))) = bytes.iter().next().copied() {
131            // Check if this fragment starts a pointer.
132            let range = offset..offset + ptr_size;
133            let frags = bytes.range(range.clone());
134            if frags.len() != ptr_size.bytes_usize() {
135                return false;
136            }
137            for (idx, (_offset, (frag_prov, frag_idx))) in frags.iter().copied().enumerate() {
138                if frag_prov != prov || frag_idx != idx as u8 {
139                    return false;
140                }
141            }
142            // Looks like a pointer! Move it over to the ptr provenance map.
143            bytes.remove_range(range);
144            self.ptrs.insert(offset, prov);
145        }
146        // We managed to convert everything into whole pointers.
147        self.bytes = None;
148        true
149    }
150
151    /// Check if there is ptr-sized provenance at the given index.
152    /// Does not mean anything for bytewise provenance! But can be useful as an optimization.
153    pub fn get_ptr(&self, offset: Size) -> Option<Prov> {
154        self.ptrs.get(&offset).copied()
155    }
156
157    /// Returns whether this allocation has provenance overlapping with the given range.
158    ///
159    /// Note: this function exists to allow `range_get_provenance` to be private, in order to somewhat
160    /// limit access to provenance outside of the `Allocation` abstraction.
161    ///
162    pub fn range_empty(&self, range: AllocRange, cx: &impl HasDataLayout) -> bool {
163        self.range_ptrs_is_empty(range, cx) && self.range_bytes_is_empty(range)
164    }
165
166    /// Yields all the provenances stored in this map.
167    pub fn provenances(&self) -> impl Iterator<Item = Prov> {
168        let bytes = self.bytes.iter().flat_map(|b| b.values().map(|(p, _i)| p));
169        self.ptrs.values().chain(bytes).copied()
170    }
171
172    pub fn insert_ptr(&mut self, offset: Size, prov: Prov, cx: &impl HasDataLayout) {
173        debug_assert!(self.range_empty(alloc_range(offset, cx.data_layout().pointer_size()), cx));
174        self.ptrs.insert(offset, prov);
175    }
176
177    /// Removes all provenance inside the given range.
178    /// If there is provenance overlapping with the edges, might result in an error.
179    pub fn clear(&mut self, range: AllocRange, cx: &impl HasDataLayout) {
180        let start = range.start;
181        let end = range.end();
182        // Clear the bytewise part -- this is easy.
183        if let Some(bytes) = self.bytes.as_mut() {
184            bytes.remove_range(start..end);
185        }
186
187        let pointer_size = cx.data_layout().pointer_size();
188
189        // For the ptr-sized part, find the first (inclusive) and last (exclusive) byte of
190        // provenance that overlaps with the given range.
191        let (first, last) = {
192            // Find all provenance overlapping the given range.
193            if self.range_ptrs_is_empty(range, cx) {
194                // No provenance in this range, we are done. This is the common case.
195                return;
196            }
197
198            // This redoes some of the work of `range_get_ptrs_is_empty`, but this path is much
199            // colder than the early return above, so it's worth it.
200            let provenance = self.range_ptrs_get(range, cx);
201            (provenance.first().unwrap().0, provenance.last().unwrap().0 + pointer_size)
202        };
203
204        // We need to handle clearing the provenance from parts of a pointer.
205        if first < start {
206            // Insert the remaining part in the bytewise provenance.
207            let prov = self.ptrs[&first];
208            let bytes = self.bytes.get_or_insert_with(Box::default);
209            for offset in first..start {
210                bytes.insert(offset, (prov, (offset - first).bytes() as u8));
211            }
212        }
213        if last > end {
214            let begin_of_last = last - pointer_size;
215            // Insert the remaining part in the bytewise provenance.
216            let prov = self.ptrs[&begin_of_last];
217            let bytes = self.bytes.get_or_insert_with(Box::default);
218            for offset in end..last {
219                bytes.insert(offset, (prov, (offset - begin_of_last).bytes() as u8));
220            }
221        }
222
223        // Forget all the provenance.
224        // Since provenance do not overlap, we know that removing until `last` (exclusive) is fine,
225        // i.e., this will not remove any other provenance just after the ones we care about.
226        self.ptrs.remove_range(first..last);
227    }
228
229    /// Overwrites all provenance in the given range with wildcard provenance.
230    /// Pointers partially overwritten will have their provenances preserved
231    /// bytewise on their remaining bytes.
232    ///
233    /// Provided for usage in Miri and panics otherwise.
234    pub fn write_wildcards(&mut self, cx: &impl HasDataLayout, range: AllocRange) {
235        let wildcard = Prov::WILDCARD.unwrap();
236
237        let bytes = self.bytes.get_or_insert_with(Box::default);
238
239        // Remove pointer provenances that overlap with the range, then readd the edge ones bytewise.
240        let ptr_range = Self::adjusted_range_ptrs(range, cx);
241        let ptrs = self.ptrs.range(ptr_range.clone());
242        if let Some((offset, prov)) = ptrs.first().copied() {
243            for byte_ofs in offset..range.start {
244                bytes.insert(byte_ofs, (prov, (byte_ofs - offset).bytes() as u8));
245            }
246        }
247        if let Some((offset, prov)) = ptrs.last().copied() {
248            for byte_ofs in range.end()..offset + cx.data_layout().pointer_size() {
249                bytes.insert(byte_ofs, (prov, (byte_ofs - offset).bytes() as u8));
250            }
251        }
252        self.ptrs.remove_range(ptr_range);
253
254        // Overwrite bytewise provenance.
255        for offset in range.start..range.end() {
256            // The fragment index does not matter for wildcard provenance.
257            bytes.insert(offset, (wildcard, 0));
258        }
259    }
260}
261
262/// A partial, owned list of provenance to transfer into another allocation.
263///
264/// Offsets are already adjusted to the destination allocation.
265pub struct ProvenanceCopy<Prov> {
266    dest_ptrs: Option<Box<[(Size, Prov)]>>,
267    dest_bytes: Option<Box<[(Size, (Prov, u8))]>>,
268}
269
270impl<Prov: Provenance> ProvenanceMap<Prov> {
271    pub fn prepare_copy(
272        &self,
273        src: AllocRange,
274        dest: Size,
275        count: u64,
276        cx: &impl HasDataLayout,
277    ) -> ProvenanceCopy<Prov> {
278        let shift_offset = move |idx, offset| {
279            // compute offset for current repetition
280            let dest_offset = dest + src.size * idx; // `Size` operations
281            // shift offsets from source allocation to destination allocation
282            (offset - src.start) + dest_offset // `Size` operations
283        };
284        let ptr_size = cx.data_layout().pointer_size();
285
286        // # Pointer-sized provenances
287        // Get the provenances that are entirely within this range.
288        // (Different from `range_get_ptrs` which asks if they overlap the range.)
289        // Only makes sense if we are copying at least one pointer worth of bytes.
290        let mut dest_ptrs_box = None;
291        if src.size >= ptr_size {
292            let adjusted_end = Size::from_bytes(src.end().bytes() - (ptr_size.bytes() - 1));
293            let ptrs = self.ptrs.range(src.start..adjusted_end);
294            // If `count` is large, this is rather wasteful -- we are allocating a big array here, which
295            // is mostly filled with redundant information since it's just N copies of the same `Prov`s
296            // at slightly adjusted offsets. The reason we do this is so that in `mark_provenance_range`
297            // we can use `insert_presorted`. That wouldn't work with an `Iterator` that just produces
298            // the right sequence of provenance for all N copies.
299            // Basically, this large array would have to be created anyway in the target allocation.
300            let mut dest_ptrs = Vec::with_capacity(ptrs.len() * (count as usize));
301            for i in 0..count {
302                dest_ptrs
303                    .extend(ptrs.iter().map(|&(offset, reloc)| (shift_offset(i, offset), reloc)));
304            }
305            debug_assert_eq!(dest_ptrs.len(), dest_ptrs.capacity());
306            dest_ptrs_box = Some(dest_ptrs.into_boxed_slice());
307        };
308
309        // # Byte-sized provenances
310        // This includes the existing bytewise provenance in the range, and ptr provenance
311        // that overlaps with the begin/end of the range.
312        let mut dest_bytes_box = None;
313        let begin_overlap = self.range_ptrs_get(alloc_range(src.start, Size::ZERO), cx).first();
314        let end_overlap = self.range_ptrs_get(alloc_range(src.end(), Size::ZERO), cx).first();
315        // We only need to go here if there is some overlap or some bytewise provenance.
316        if begin_overlap.is_some() || end_overlap.is_some() || self.bytes.is_some() {
317            let mut bytes: Vec<(Size, (Prov, u8))> = Vec::new();
318            // First, if there is a part of a pointer at the start, add that.
319            if let Some(entry) = begin_overlap {
320                trace!("start overlapping entry: {entry:?}");
321                // For really small copies, make sure we don't run off the end of the `src` range.
322                let entry_end = cmp::min(entry.0 + ptr_size, src.end());
323                for offset in src.start..entry_end {
324                    bytes.push((offset, (entry.1, (offset - entry.0).bytes() as u8)));
325                }
326            } else {
327                trace!("no start overlapping entry");
328            }
329
330            // Then the main part, bytewise provenance from `self.bytes`.
331            bytes.extend(self.range_bytes_get(src));
332
333            // And finally possibly parts of a pointer at the end.
334            if let Some(entry) = end_overlap {
335                trace!("end overlapping entry: {entry:?}");
336                // For really small copies, make sure we don't start before `src` does.
337                let entry_start = cmp::max(entry.0, src.start);
338                for offset in entry_start..src.end() {
339                    if bytes.last().is_none_or(|bytes_entry| bytes_entry.0 < offset) {
340                        // The last entry, if it exists, has a lower offset than us, so we
341                        // can add it at the end and remain sorted.
342                        bytes.push((offset, (entry.1, (offset - entry.0).bytes() as u8)));
343                    } else {
344                        // There already is an entry for this offset in there! This can happen when the
345                        // start and end range checks actually end up hitting the same pointer, so we
346                        // already added this in the "pointer at the start" part above.
347                        assert!(entry.0 <= src.start);
348                    }
349                }
350            } else {
351                trace!("no end overlapping entry");
352            }
353            trace!("byte provenances: {bytes:?}");
354
355            // And again a buffer for the new list on the target side.
356            let mut dest_bytes = Vec::with_capacity(bytes.len() * (count as usize));
357            for i in 0..count {
358                dest_bytes
359                    .extend(bytes.iter().map(|&(offset, reloc)| (shift_offset(i, offset), reloc)));
360            }
361            debug_assert_eq!(dest_bytes.len(), dest_bytes.capacity());
362            dest_bytes_box = Some(dest_bytes.into_boxed_slice());
363        }
364
365        ProvenanceCopy { dest_ptrs: dest_ptrs_box, dest_bytes: dest_bytes_box }
366    }
367
368    /// Applies a provenance copy.
369    /// The affected range, as defined in the parameters to `prepare_copy` is expected
370    /// to be clear of provenance.
371    pub fn apply_copy(&mut self, copy: ProvenanceCopy<Prov>) {
372        if let Some(dest_ptrs) = copy.dest_ptrs {
373            self.ptrs.insert_presorted(dest_ptrs.into());
374        }
375        if let Some(dest_bytes) = copy.dest_bytes
376            && !dest_bytes.is_empty()
377        {
378            self.bytes.get_or_insert_with(Box::default).insert_presorted(dest_bytes.into());
379        }
380    }
381}