Skip to main content

miri/
provenance_gc.rs

1use std::collections::BTreeMap;
2use std::net::SocketAddr;
3use std::rc::Rc;
4
5use rustc_data_structures::either::Either;
6use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_span::Symbol;
8
9use crate::*;
10
11pub type VisitWith<'a> = dyn FnMut(Option<AllocId>, Option<BorTag>) + 'a;
12
13pub trait VisitProvenance {
14    fn visit_provenance(&self, visit: &mut VisitWith<'_>);
15}
16
17// Trivial impls for types that do not contain any provenance
18macro_rules! no_provenance {
19    ($($ty:ident)+) => {
20        $(
21            impl VisitProvenance for $ty {
22                fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
23            }
24        )+
25    }
26}
27no_provenance!(i8 i16 i32 i64 isize u8 u16 u32 u64 usize bool ThreadId Deadline Symbol SocketAddr);
28
29impl VisitProvenance for &'static str {
30    fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {}
31}
32
33impl<T: VisitProvenance> VisitProvenance for Option<T> {
34    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
35        if let Some(x) = self {
36            x.visit_provenance(visit);
37        }
38    }
39}
40
41impl<A, B> VisitProvenance for (A, B)
42where
43    A: VisitProvenance,
44    B: VisitProvenance,
45{
46    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
47        self.0.visit_provenance(visit);
48        self.1.visit_provenance(visit);
49    }
50}
51
52impl<T: ?Sized + VisitProvenance> VisitProvenance for Box<T> {
53    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
54        (**self).visit_provenance(visit);
55    }
56}
57
58impl<T: ?Sized + VisitProvenance> VisitProvenance for Rc<T> {
59    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
60        (**self).visit_provenance(visit);
61    }
62}
63
64impl<T: VisitProvenance> VisitProvenance for Vec<T> {
65    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
66        self.iter().for_each(|el| el.visit_provenance(visit));
67    }
68}
69
70impl<K: VisitProvenance, V: VisitProvenance> VisitProvenance for BTreeMap<K, V> {
71    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
72        self.iter().for_each(|(key, value)| {
73            key.visit_provenance(visit);
74            value.visit_provenance(visit);
75        });
76    }
77}
78
79impl<K: VisitProvenance, V: VisitProvenance> VisitProvenance for FxHashMap<K, V> {
80    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
81        self.iter().for_each(|(key, value)| {
82            key.visit_provenance(visit);
83            value.visit_provenance(visit);
84        });
85    }
86}
87
88impl<T: VisitProvenance> VisitProvenance for std::cell::RefCell<T> {
89    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
90        self.borrow().visit_provenance(visit)
91    }
92}
93
94impl VisitProvenance for BorTag {
95    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
96        visit(None, Some(*self))
97    }
98}
99
100impl VisitProvenance for AllocId {
101    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
102        visit(Some(*self), None)
103    }
104}
105
106impl VisitProvenance for Provenance {
107    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
108        if let Provenance::Concrete { alloc_id, tag, .. } = self {
109            visit(Some(*alloc_id), Some(*tag));
110        }
111    }
112}
113
114impl VisitProvenance for StrictPointer {
115    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
116        self.provenance.visit_provenance(visit);
117    }
118}
119
120impl VisitProvenance for Pointer {
121    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
122        self.provenance.visit_provenance(visit);
123    }
124}
125
126impl VisitProvenance for Scalar {
127    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
128        match self {
129            Scalar::Ptr(ptr, _) => ptr.visit_provenance(visit),
130            Scalar::Int(_) => (),
131        }
132    }
133}
134
135impl VisitProvenance for IoError {
136    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
137        use crate::shims::io_error::IoError::*;
138        match self {
139            LibcError(_name) => (),
140            WindowsError(_name) => (),
141            HostError(_io_error) => (),
142            Raw(scalar) => scalar.visit_provenance(visit),
143        }
144    }
145}
146
147impl VisitProvenance for Immediate<Provenance> {
148    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
149        match self {
150            Immediate::Scalar(s) => {
151                s.visit_provenance(visit);
152            }
153            Immediate::ScalarPair(s1, s2) => {
154                s1.visit_provenance(visit);
155                s2.visit_provenance(visit);
156            }
157            Immediate::Uninit => {}
158        }
159    }
160}
161
162impl VisitProvenance for MemPlaceMeta<Provenance> {
163    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
164        match self {
165            MemPlaceMeta::Meta(m) => m.visit_provenance(visit),
166            MemPlaceMeta::None => {}
167        }
168    }
169}
170
171impl VisitProvenance for ImmTy<'_> {
172    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
173        (**self).visit_provenance(visit)
174    }
175}
176
177impl VisitProvenance for MPlaceTy<'_> {
178    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
179        self.ptr().visit_provenance(visit);
180        self.meta().visit_provenance(visit);
181    }
182}
183
184impl VisitProvenance for PlaceTy<'_> {
185    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
186        match self.as_mplace_or_local() {
187            Either::Left(mplace) => mplace.visit_provenance(visit),
188            Either::Right(_) => (),
189        }
190    }
191}
192
193impl VisitProvenance for OpTy<'_> {
194    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
195        match self.as_mplace_or_imm() {
196            Either::Left(mplace) => mplace.visit_provenance(visit),
197            Either::Right(imm) => imm.visit_provenance(visit),
198        }
199    }
200}
201
202impl VisitProvenance for Allocation<Provenance, AllocExtra<'_>, MiriAllocBytes> {
203    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
204        for prov in self.provenance().provenances() {
205            prov.visit_provenance(visit);
206        }
207
208        self.extra.visit_provenance(visit);
209    }
210}
211
212impl VisitProvenance for crate::MiriInterpCx<'_> {
213    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
214        // Visit the contents of the allocations and the IDs themselves, to account for all
215        // live allocation IDs and all provenance in the allocation bytes, even if they are leaked.
216        // We do *not* visit all the `AllocId` of the live allocations; we tried that and adding
217        // them all to the live set is too expensive. Instead we later do liveness check by
218        // checking both "is this alloc id live" and "is it mentioned anywhere else in
219        // the interpreter state".
220        self.memory.alloc_map().iter(|it| {
221            for (_id, (_kind, alloc)) in it {
222                alloc.visit_provenance(visit);
223            }
224        });
225        // And all the other machine values.
226        self.machine.visit_provenance(visit);
227    }
228}
229
230pub struct LiveAllocs<'a, 'tcx> {
231    collected: FxHashSet<AllocId>,
232    ecx: &'a MiriInterpCx<'tcx>,
233}
234
235impl LiveAllocs<'_, '_> {
236    pub fn is_live(&self, id: AllocId) -> bool {
237        self.collected.contains(&id) || self.ecx.is_alloc_live(id)
238    }
239}
240
241fn remove_unreachable_tags<'tcx>(ecx: &mut MiriInterpCx<'tcx>, tags: FxHashSet<BorTag>) {
242    // Avoid iterating all allocations if there's no borrow tracker anyway.
243    if ecx.machine.borrow_tracker.is_some() {
244        ecx.memory.alloc_map().iter(|it| {
245            for (_id, (_kind, alloc)) in it {
246                alloc.extra.borrow_tracker.as_ref().unwrap().remove_unreachable_tags(&tags);
247            }
248        });
249    }
250}
251
252fn remove_unreachable_allocs<'tcx>(ecx: &mut MiriInterpCx<'tcx>, allocs: FxHashSet<AllocId>) {
253    let allocs = LiveAllocs { ecx, collected: allocs };
254    ecx.machine.allocation_spans.borrow_mut().retain(|id, _| allocs.is_live(*id));
255    ecx.machine.symbolic_alignment.borrow_mut().retain(|id, _| allocs.is_live(*id));
256    ecx.machine.alloc_addresses.borrow_mut().remove_unreachable_allocs(&allocs);
257    if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
258        borrow_tracker.borrow_mut().remove_unreachable_allocs(&allocs);
259    }
260    // Clean up core (non-Miri-specific) state.
261    ecx.remove_unreachable_allocs(&allocs.collected);
262}
263
264impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
265pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> {
266    fn run_provenance_gc(&mut self) {
267        let ecx = self.eval_context_mut();
268
269        // We collect all tags and AllocId from every part of the interpreter.
270        let mut tags = FxHashSet::default();
271        let mut alloc_ids = FxHashSet::default();
272        ecx.visit_provenance(&mut |id, tag| {
273            if let Some(id) = id {
274                alloc_ids.insert(id);
275            }
276            if let Some(tag) = tag {
277                tags.insert(tag);
278            }
279        });
280
281        // Based on this, clean up the interpreter state.
282        remove_unreachable_tags(ecx, tags);
283        remove_unreachable_allocs(ecx, alloc_ids);
284    }
285}