Skip to main content

miri/borrow_tracker/tree_borrows/
mod.rs

1#![warn(clippy::arithmetic_side_effects)]
2
3use rustc_abi::Size;
4use rustc_attr_ir::find_attr;
5use rustc_middle::mir::Mutability;
6use rustc_middle::ty::layout::HasTypingEnv;
7use rustc_middle::ty::{self, Ty};
8
9use self::foreign_access_skipping::IdempotentForeignAccess;
10use self::tree::LocationState;
11use crate::borrow_tracker::{AccessKind, GlobalState, GlobalStateInner, ProtectorKind};
12use crate::concurrency::data_race::{NaReadType, NaWriteType};
13use crate::*;
14
15pub mod diagnostics;
16mod foreign_access_skipping;
17mod perms;
18mod tree;
19mod tree_visitor;
20mod unimap;
21mod wildcard;
22
23#[cfg(test)]
24mod exhaustive;
25
26use self::perms::Permission;
27pub use self::tree::Tree;
28
29pub type AllocState = Tree;
30
31impl<'tcx> Tree {
32    /// Create a new allocation, i.e. a new tree
33    pub fn new_allocation(
34        id: AllocId,
35        size: Size,
36        state: &mut GlobalStateInner,
37        _kind: MemoryKind,
38        machine: &MiriMachine<'tcx>,
39    ) -> Self {
40        let tag = state.root_ptr_tag(id, machine); // Fresh tag for the root
41        let span = machine.current_user_relevant_span();
42        Tree::new(tag, size, span)
43    }
44
45    /// Check that an access on the entire range is permitted, and update
46    /// the tree.
47    pub fn before_memory_access(
48        &mut self,
49        access_kind: AccessKind,
50        alloc_id: AllocId,
51        prov: ProvenanceExtra,
52        range: AllocRange,
53        machine: &MiriMachine<'tcx>,
54    ) -> InterpResult<'tcx> {
55        trace!(
56            "{} with tag {:?}: {:?}, size {}",
57            access_kind,
58            prov,
59            interpret::Pointer::new(alloc_id, range.start),
60            range.size.bytes(),
61        );
62        let global = machine.borrow_tracker.as_ref().unwrap();
63        let span = machine.current_user_relevant_span();
64        self.perform_access(
65            prov,
66            range,
67            access_kind,
68            diagnostics::AccessCause::Explicit(access_kind),
69            global,
70            alloc_id,
71            span,
72        )
73    }
74
75    /// Check that this pointer has permission to deallocate this range.
76    pub fn before_memory_deallocation(
77        &mut self,
78        alloc_id: AllocId,
79        prov: ProvenanceExtra,
80        size: Size,
81        machine: &MiriMachine<'tcx>,
82    ) -> InterpResult<'tcx> {
83        let global = machine.borrow_tracker.as_ref().unwrap();
84        let span = machine.current_user_relevant_span();
85        self.dealloc(prov, alloc_range(Size::ZERO, size), global, alloc_id, span)
86    }
87
88    /// A tag just lost its protector.
89    ///
90    /// This emits a special kind of access that is only applied
91    /// to accessed locations, as a protection against other
92    /// tags not having been made aware of the existence of this
93    /// protector.
94    pub fn release_protector(
95        &mut self,
96        machine: &MiriMachine<'tcx>,
97        global: &GlobalState,
98        tag: BorTag,
99        alloc_id: AllocId, // diagnostics
100    ) -> InterpResult<'tcx> {
101        let span = machine.current_user_relevant_span();
102        self.perform_protector_end_access(tag, global, alloc_id, span)?;
103
104        self.update_exposure_for_protector_release(tag);
105
106        interp_ok(())
107    }
108}
109
110/// Policy for a new borrow.
111#[derive(Debug, Clone, Copy)]
112pub struct NewPermission {
113    /// Permission for the frozen part of the range.
114    freeze_perm: Permission,
115    /// Permission for the non-frozen part of the range.
116    nonfreeze_perm: Permission,
117    /// Permission for memory outside the range.
118    outside_perm: Permission,
119    /// Whether this pointer is part of the arguments of a function call.
120    /// `protector` is `Some(_)` for all pointers marked `noalias`.
121    protector: Option<ProtectorKind>,
122}
123
124impl<'tcx> NewPermission {
125    /// Determine NewPermission of the reference/Box from the type of the pointee.
126    ///
127    /// A `ref_mutability` of `None` indicates a `Box` type.
128    fn new(
129        pointee: Ty<'tcx>,
130        ref_mutability: Option<Mutability>,
131        mode: RetagMode,
132        cx: &MiriInterpCx<'tcx>,
133    ) -> Option<Self> {
134        if mode == RetagMode::None {
135            return None;
136        }
137
138        let ty_is_unpin = pointee.is_unpin(*cx.tcx, cx.typing_env())
139            && pointee.is_unsafe_unpin(*cx.tcx, cx.typing_env());
140        let ty_is_freeze = pointee.is_freeze(*cx.tcx, cx.typing_env());
141        let is_protected = mode == RetagMode::FnEntry;
142
143        // Check if the implicit writes feature is globally enabled, using the
144        // `-Zmiri-tree-borrows-implicit-writes` flag, and not locally disabled using the
145        // `#[rustc_no_writable]` attribute. For performance reasons, only performs the lookup if
146        // is_protected is true as implicit writes are only performed for protected references.
147        let implicit_writes_enabled = is_protected && {
148            let implicit_writes = cx.get_tree_borrows_params().implicit_writes;
149            let def_id = cx.frame().instance().def_id();
150            implicit_writes && !find_attr!(cx.tcx, def_id, RustcNoWritable)
151        };
152
153        if matches!(ref_mutability, Some(Mutability::Mut) | None if !ty_is_unpin) {
154            // Mutable reference / Box to pinning type: retagging is a NOP.
155            // FIXME: with `UnsafePinned`, this should do proper per-byte tracking.
156            return None;
157        }
158
159        enum Part {
160            InsideFrozen,
161            InsideUnsafeCell,
162            Outside,
163        }
164        use Part::*;
165
166        let perm = |part: Part| {
167            // Whether we should consider this byte to be frozen.
168            // Outside bytes are frozen only if the entire type is frozen.
169            let frozen = match part {
170                InsideFrozen => true,
171                InsideUnsafeCell => false,
172                Outside => ty_is_freeze,
173            };
174            match ref_mutability {
175                // Shared references
176                Some(Mutability::Not) =>
177                    if frozen {
178                        Permission::new_frozen()
179                    } else {
180                        Permission::new_cell()
181                    },
182                // Mutable references
183                Some(Mutability::Mut) => {
184                    if implicit_writes_enabled && !matches!(part, Outside) {
185                        // We cannot use `Unique` for the outside part.
186                        Permission::new_unique()
187                    } else if is_protected || frozen {
188                        // We also use this for protected `&mut UnsafeCell` as otherwise adding
189                        // `noalias` would not be sound.
190                        Permission::new_reserved_frz()
191                    } else {
192                        Permission::new_reserved_im()
193                    }
194                }
195                // Boxes
196                None => {
197                    if implicit_writes_enabled && !matches!(part, Outside) {
198                        // Boxes are treated the same as mutable references.
199                        Permission::new_unique()
200                    } else if is_protected || frozen {
201                        // We also use this for protected `Box<UnsafeCell>` as otherwise adding
202                        // `noalias` would not be sound.
203                        Permission::new_reserved_frz()
204                    } else {
205                        Permission::new_reserved_im()
206                    }
207                }
208            }
209        };
210
211        Some(NewPermission {
212            freeze_perm: perm(InsideFrozen),
213            nonfreeze_perm: perm(InsideUnsafeCell),
214            outside_perm: perm(Outside),
215            protector: is_protected.then_some(if ref_mutability.is_some() {
216                // Strong protector for references
217                ProtectorKind::StrongProtector
218            } else {
219                // Weak protector for boxes
220                ProtectorKind::WeakProtector
221            }),
222        })
223    }
224}
225
226/// Retagging/reborrowing.
227/// Policy on which permission to grant to each pointer should be left to
228/// the implementation of NewPermission.
229impl<'tcx> EvalContextPrivExt<'tcx> for crate::MiriInterpCx<'tcx> {}
230trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
231    #[track_caller]
232    #[inline]
233    fn get_tree_borrows_params(&self) -> TreeBorrowsParams {
234        let ecx = self.eval_context_ref();
235        let borrow_tracker = ecx.machine.borrow_tracker.as_ref().unwrap().borrow();
236        borrow_tracker.borrow_tracker_method.get_tree_borrows_params()
237    }
238
239    /// Returns the provenance that should be used henceforth.
240    fn tb_reborrow(
241        &mut self,
242        place: &MPlaceTy<'tcx>, // parent tag extracted from here
243        ptr_size: Size,
244        new_perm: NewPermission,
245        new_tag: BorTag,
246    ) -> InterpResult<'tcx, Option<Provenance>> {
247        let ecx = self.eval_context_mut();
248        // Ensure we bail out if the pointer goes out-of-bounds (see miri#1050).
249        ecx.check_ptr_access(place.ptr(), ptr_size, CheckInAllocMsg::Dereferenceable("pointer"))?;
250
251        // It is crucial that this gets called on all code paths, to ensure we track tag creation.
252        let log_creation = |ecx: &MiriInterpCx<'tcx>,
253                            loc: Option<(AllocId, Size, ProvenanceExtra)>| // alloc_id, base_offset, orig_tag
254         -> InterpResult<'tcx> {
255            let global = ecx.machine.borrow_tracker.as_ref().unwrap().borrow();
256            let ty = place.layout.ty;
257            if global.tracked_pointer_tags.contains(&new_tag) {
258                 let ty_is_freeze = ty.is_freeze(*ecx.tcx, ecx.typing_env());
259                 let kind_str =
260                     if ty_is_freeze {
261                         format!("initial state {} (pointee type {ty})", new_perm.freeze_perm)
262                     } else {
263                         format!("initial state {}/{} outside/inside UnsafeCell (pointee type {ty})", new_perm.freeze_perm, new_perm.nonfreeze_perm)
264                     };
265                ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(
266                    new_tag.inner(),
267                    Some(kind_str),
268                    loc.map(|(alloc_id, base_offset, orig_tag)| (alloc_id, alloc_range(base_offset, ptr_size), orig_tag)),
269                ));
270            }
271            drop(global); // don't hold that reference any longer than we have to
272            interp_ok(())
273        };
274
275        trace!("Reborrow of size {:?}", ptr_size);
276        // Unlike SB, we *do* a proper retag for size 0 if can identify the allocation.
277        // After all, the pointer may be lazily initialized outside this initial range.
278        let Ok((alloc_id, base_offset, parent_prov)) = ecx.ptr_try_get_alloc_id(place.ptr(), 0)
279        else {
280            assert_eq!(ptr_size, Size::ZERO); // we did the deref check above, size has to be 0 here
281            // This pointer doesn't come with an AllocId, so there's no
282            // memory to do retagging in.
283            let new_prov = place.ptr().provenance;
284            trace!("reborrow of size 0: reusing {:?} (pointee {})", place.ptr(), place.layout.ty,);
285            log_creation(ecx, None)?;
286            // Keep original provenance.
287            return interp_ok(new_prov);
288        };
289        let new_prov = Provenance::Concrete { alloc_id, tag: new_tag };
290
291        log_creation(ecx, Some((alloc_id, base_offset, parent_prov)))?;
292
293        trace!(
294            "reborrow: reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
295            new_tag,
296            parent_prov,
297            place.layout.ty,
298            interpret::Pointer::new(alloc_id, base_offset),
299            ptr_size.bytes()
300        );
301
302        if let Some(protect) = new_perm.protector {
303            // We register the protection in two different places.
304            // This makes creating a protector slower, but checking whether a tag
305            // is protected faster.
306            ecx.frame_mut()
307                .extra
308                .borrow_tracker
309                .as_mut()
310                .unwrap()
311                .protected_tags
312                .push((alloc_id, new_tag));
313            ecx.machine
314                .borrow_tracker
315                .as_mut()
316                .expect("We should have borrow tracking data")
317                .get_mut()
318                .protected_tags
319                .insert(new_tag, protect);
320        }
321
322        let alloc_kind = ecx.get_alloc_info(alloc_id).kind;
323        if !matches!(alloc_kind, AllocKind::LiveData) {
324            assert_eq!(ptr_size, Size::ZERO); // we did the deref check above, size has to be 0 here
325            // There's not actually any bytes here where accesses could even be tracked.
326            // Just produce the new provenance, nothing else to do.
327            return interp_ok(Some(new_prov));
328        }
329
330        let protected = new_perm.protector.is_some();
331        let precise_interior_mut = ecx.get_tree_borrows_params().precise_interior_mut;
332
333        // Compute initial "inside" permissions.
334        let loc_state = |frozen: bool| -> LocationState {
335            let perm = if frozen { new_perm.freeze_perm } else { new_perm.nonfreeze_perm };
336            let sifa = perm.strongest_idempotent_foreign_access(protected);
337
338            if perm.associated_access().is_some() {
339                LocationState::new_accessed(perm, sifa)
340            } else {
341                LocationState::new_non_accessed(perm, sifa)
342            }
343        };
344        let inside_perms = if !precise_interior_mut {
345            // For `!Freeze` types, just pretend the entire thing is an `UnsafeCell`.
346            let ty_is_freeze = place.layout.ty.is_freeze(*ecx.tcx, ecx.typing_env());
347            DedupRangeMap::new(ptr_size, loc_state(ty_is_freeze))
348        } else {
349            // The initial state will be overwritten by the visitor below.
350            let mut perms_map = DedupRangeMap::new(
351                ptr_size,
352                LocationState::new_accessed(
353                    Permission::new_disabled(),
354                    IdempotentForeignAccess::None,
355                ),
356            );
357            ecx.visit_freeze_sensitive(place, ptr_size, |range, frozen| {
358                let state = loc_state(frozen);
359                for (_loc_range, loc) in perms_map.iter_mut(range.start, range.size) {
360                    *loc = state;
361                }
362                interp_ok(())
363            })?;
364            perms_map
365        };
366
367        let alloc_extra = ecx.get_alloc_extra(alloc_id)?;
368        let mut tree_borrows = alloc_extra.borrow_tracker_tb().borrow_mut();
369
370        for (perm_range, loc_state) in inside_perms.iter_all() {
371            if let Some(access) = loc_state.permission().associated_access() {
372                // Some reborrows incur a read/write access to the parent.
373                // As a write also implies a read, a single write is performed instead of a read and a write.
374
375                // writing to an immutable allocation (static variables) is UB, check this here
376                if access == AccessKind::Write
377                    && ecx.get_alloc_mutability(alloc_id).unwrap().is_not()
378                {
379                    throw_ub!(WriteToReadOnly(alloc_id))
380                }
381
382                // Adjust range to be relative to allocation start (rather than to `place`).
383                let range_in_alloc = AllocRange {
384                    start: Size::from_bytes(perm_range.start) + base_offset,
385                    size: Size::from_bytes(perm_range.end.strict_sub(perm_range.start)),
386                };
387
388                tree_borrows.perform_access(
389                    parent_prov,
390                    range_in_alloc,
391                    access,
392                    diagnostics::AccessCause::Reborrow(access),
393                    ecx.machine.borrow_tracker.as_ref().unwrap(),
394                    alloc_id,
395                    ecx.machine.current_user_relevant_span(),
396                )?;
397
398                // Also inform the data race model (but only if any bytes are actually affected).
399                if range_in_alloc.size.bytes() > 0 {
400                    if let Some(data_race) = alloc_extra.data_race.as_vclocks_ref() {
401                        match access {
402                            AccessKind::Read =>
403                                data_race.read_non_atomic(
404                                    alloc_id,
405                                    range_in_alloc,
406                                    NaReadType::Retag,
407                                    Some(place.layout.ty),
408                                    &ecx.machine,
409                                )?,
410                            AccessKind::Write =>
411                                data_race.write_non_atomic(
412                                    alloc_id,
413                                    range_in_alloc,
414                                    NaWriteType::Retag,
415                                    Some(place.layout.ty),
416                                    &ecx.machine,
417                                )?,
418                        };
419                    }
420                }
421            }
422        }
423
424        // Record the parent-child pair in the tree.
425        tree_borrows.new_child(
426            base_offset,
427            parent_prov,
428            new_tag,
429            inside_perms,
430            new_perm.outside_perm,
431            protected,
432            ecx.machine.current_user_relevant_span(),
433        )?;
434
435        interp_ok(Some(new_prov))
436    }
437
438    fn tb_retag_place(
439        &mut self,
440        place: &MPlaceTy<'tcx>,
441        new_perm: NewPermission,
442    ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
443        let ecx = self.eval_context_mut();
444
445        // Determine the size of the reborrow.
446        // For most types this is the entire size of the place, however
447        // - when `extern type` is involved we use the size of the known prefix,
448        // - if the pointer is not reborrowed (raw pointer) then we override the size
449        //   to do a zero-length reborrow.
450        let reborrow_size =
451            ecx.size_and_align_of_val(place)?.map(|(size, _)| size).unwrap_or(place.layout.size);
452        trace!("Creating new permission: {:?} with size {:?}", new_perm, reborrow_size);
453
454        // This new tag is not guaranteed to actually be used.
455        //
456        // If you run out of tags, consider the following optimization: adjust `tb_reborrow`
457        // so that rather than taking as input a fresh tag and deciding whether it uses this
458        // one or the parent it instead just returns whether a new tag should be created.
459        // This will avoid creating tags than end up never being used.
460        let new_tag = ecx.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr();
461
462        // Compute the actual reborrow.
463        let new_prov = ecx.tb_reborrow(place, reborrow_size, new_perm, new_tag)?;
464
465        // Adjust place.
466        // (If the closure gets called, that means the old provenance was `Some`, and hence the new
467        // one must also be `Some`.)
468        interp_ok(place.clone().map_provenance(|_| new_prov.unwrap()))
469    }
470}
471
472impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
473pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
474    /// Retag a pointer. References are passed to `from_ref_ty` and
475    /// raw pointers are never reborrowed.
476    fn tb_retag_ptr_value(
477        &mut self,
478        val: &ImmTy<'tcx>,
479        ty: Ty<'tcx>,
480        mode: RetagMode,
481    ) -> InterpResult<'tcx, Option<ImmTy<'tcx>>> {
482        let ecx = self.eval_context_mut();
483        let new_perm = match *ty.kind() {
484            _ if ty.is_box_global(*ecx.tcx) => {
485                // The `None` marks this as a Box.
486                NewPermission::new(ty.builtin_deref(true).unwrap(), None, mode, ecx)
487            }
488            ty::Ref(_, pointee, mutability) =>
489                NewPermission::new(pointee, Some(mutability), mode, ecx),
490
491            ty::RawPtr(..) => {
492                assert!(mode == RetagMode::Raw);
493                // We don't give new tags to raw pointers.
494                None
495            }
496            _ if ty.is_box() => {
497                // No retagging for boxes with custom allocators.
498                None
499            }
500            _ => panic!("tb_retag_ptr_value: invalid type {ty}"),
501        };
502        if let Some(new_perm) = new_perm {
503            let place = ecx.imm_ptr_to_mplace(val)?;
504            let new_place = ecx.tb_retag_place(&place, new_perm)?;
505            interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout)))
506        } else {
507            interp_ok(None)
508        }
509    }
510
511    /// Protect a place so that it cannot be used any more for the duration of the current function
512    /// call.
513    ///
514    /// This is used to ensure soundness of in-place function argument/return passing.
515    fn tb_protect_place(&mut self, place: &MPlaceTy<'tcx>) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
516        let ecx = self.eval_context_mut();
517
518        // Retag it. With protection! That is the entire point.
519        let new_perm = NewPermission {
520            // Note: If we are creating a protected Reserved, which can
521            // never be ReservedIM, the value of the `ty_is_freeze`
522            // argument doesn't matter
523            // (`ty_is_freeze || true` in `new_reserved` will always be `true`).
524            freeze_perm: Permission::new_reserved_frz(),
525            nonfreeze_perm: Permission::new_reserved_frz(),
526            outside_perm: Permission::new_reserved_frz(),
527            protector: Some(ProtectorKind::StrongProtector),
528        };
529        ecx.tb_retag_place(place, new_perm)
530    }
531
532    /// Mark the given tag as exposed. It was found on a pointer with the given AllocId.
533    fn tb_expose_tag(&self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> {
534        let ecx = self.eval_context_ref();
535
536        // Function pointers and dead objects don't have an alloc_extra so we ignore them.
537        // This is okay because accessing them is UB anyway, no need for any Tree Borrows checks.
538        // NOT using `get_alloc_extra_mut` since this might be a read-only allocation!
539        let kind = ecx.get_alloc_info(alloc_id).kind;
540        match kind {
541            AllocKind::LiveData => {
542                // This should have alloc_extra data, but `get_alloc_extra` can still fail
543                // if converting this alloc_id from a global to a local one
544                // uncovers a non-supported `extern static`.
545                let alloc_extra = ecx.get_alloc_extra(alloc_id)?;
546                trace!("Tree Borrows tag {tag:?} exposed in {alloc_id:?}");
547
548                let global = ecx.machine.borrow_tracker.as_ref().unwrap();
549                let protected_tags = &global.borrow().protected_tags;
550                let protected = protected_tags.contains_key(&tag);
551                alloc_extra.borrow_tracker_tb().borrow_mut().expose_tag(tag, protected);
552            }
553            AllocKind::Function
554            | AllocKind::VTable
555            | AllocKind::TypeId
556            | AllocKind::Dead
557            | AllocKind::VaList => {
558                // No tree borrows on these allocations.
559            }
560        }
561        interp_ok(())
562    }
563
564    /// Display the tree.
565    fn print_tree(&self, alloc_id: AllocId, show_unnamed: bool) -> InterpResult<'tcx> {
566        let ecx = self.eval_context_ref();
567        let alloc_extra = ecx.get_alloc_extra(alloc_id)?;
568        let tree_borrows = alloc_extra.borrow_tracker_tb().borrow();
569        let borrow_tracker = &ecx.machine.borrow_tracker.as_ref().unwrap().borrow();
570        tree_borrows.print_tree(&borrow_tracker.protected_tags, show_unnamed)
571    }
572
573    /// Give a name to the pointer, usually the name it has in the source code (for debugging).
574    /// The name given is `name` and the pointer that receives it is the `nth_parent`
575    /// of `ptr` (with 0 representing `ptr` itself)
576    fn tb_give_pointer_debug_name(
577        &self,
578        ptr: Pointer,
579        nth_parent: u8,
580        name: &str,
581    ) -> InterpResult<'tcx> {
582        let ecx = self.eval_context_ref();
583        let (tag, alloc_id) = match ptr.provenance {
584            Some(Provenance::Concrete { tag, alloc_id }) => (tag, alloc_id),
585            Some(Provenance::Wildcard) => {
586                eprintln!("Can't give the name {name} to wildcard pointer");
587                return interp_ok(());
588            }
589            None => {
590                eprintln!("Can't give the name {name} to pointer without provenance");
591                return interp_ok(());
592            }
593        };
594        let alloc_extra = ecx.get_alloc_extra(alloc_id)?;
595        let mut tree_borrows = alloc_extra.borrow_tracker_tb().borrow_mut();
596        tree_borrows.give_pointer_debug_name(tag, nth_parent, name)
597    }
598}