]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
fix diagnostics printing when triggered during TLS dtor scheduling
[rust.git] / src / machine.rs
1 //! Global machine state as well as implementation of the interpreter engine
2 //! `Machine` trait.
3
4 use std::borrow::Cow;
5 use std::cell::RefCell;
6 use std::num::NonZeroU64;
7 use std::rc::Rc;
8 use std::time::Instant;
9 use std::fmt;
10
11 use log::trace;
12 use rand::rngs::StdRng;
13
14 use rustc_ast::attr;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_middle::{
17     mir,
18     ty::{
19         self,
20         layout::{LayoutCx, LayoutError, TyAndLayout},
21         TyCtxt,
22     },
23 };
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_span::def_id::DefId;
26 use rustc_target::abi::{LayoutOf, Size};
27
28 use crate::*;
29
30 // Some global facts about the emulated machine.
31 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
32 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
33 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
34 pub const NUM_CPUS: u64 = 1;
35
36 /// Extra data stored with each stack frame
37 #[derive(Debug)]
38 pub struct FrameData<'tcx> {
39     /// Extra data for Stacked Borrows.
40     pub call_id: stacked_borrows::CallId,
41
42     /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
43     /// called by `try`). When this frame is popped during unwinding a panic,
44     /// we stop unwinding, use the `CatchUnwindData` to handle catching.
45     pub catch_unwind: Option<CatchUnwindData<'tcx>>,
46 }
47
48 /// Extra memory kinds
49 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
50 pub enum MiriMemoryKind {
51     /// `__rust_alloc` memory.
52     Rust,
53     /// `malloc` memory.
54     C,
55     /// Windows `HeapAlloc` memory.
56     WinHeap,
57     /// Memory for args, errno, and other parts of the machine-managed environment.
58     /// This memory may leak.
59     Machine,
60     /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
61     Env,
62     /// Globals copied from `tcx`.
63     /// This memory may leak.
64     Global,
65     /// Memory for extern statics.
66     /// This memory may leak.
67     ExternStatic,
68     /// Memory for thread-local statics.
69     /// This memory may leak.
70     Tls,
71 }
72
73 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
74     #[inline(always)]
75     fn into(self) -> MemoryKind<MiriMemoryKind> {
76         MemoryKind::Machine(self)
77     }
78 }
79
80 impl MayLeak for MiriMemoryKind {
81     #[inline(always)]
82     fn may_leak(self) -> bool {
83         use self::MiriMemoryKind::*;
84         match self {
85             Rust | C | WinHeap | Env => false,
86             Machine | Global | ExternStatic | Tls => true,
87         }
88     }
89 }
90
91 impl fmt::Display for MiriMemoryKind {
92     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93         use self::MiriMemoryKind::*;
94         match self {
95             Rust => write!(f, "Rust heap"),
96             C => write!(f, "C heap"),
97             WinHeap => write!(f, "Windows heap"),
98             Machine => write!(f, "machine-managed memory"),
99             Env => write!(f, "environment variable"),
100             Global => write!(f, "global (static or const)"),
101             ExternStatic => write!(f, "extern static"),
102             Tls =>  write!(f, "thread-local static"),
103         }
104     }
105 }
106
107 /// Extra per-allocation data
108 #[derive(Debug, Clone)]
109 pub struct AllocExtra {
110     /// Stacked Borrows state is only added if it is enabled.
111     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
112 }
113
114 /// Extra global memory data
115 #[derive(Clone, Debug)]
116 pub struct MemoryExtra {
117     pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
118     pub intptrcast: intptrcast::MemoryExtra,
119
120     /// Mapping extern static names to their canonical allocation.
121     extern_statics: FxHashMap<Symbol, AllocId>,
122
123     /// The random number generator used for resolving non-determinism.
124     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
125     pub(crate) rng: RefCell<StdRng>,
126
127     /// An allocation ID to report when it is being allocated
128     /// (helps for debugging memory leaks and use after free bugs).
129     tracked_alloc_id: Option<AllocId>,
130
131     /// Controls whether alignment of memory accesses is being checked.
132     check_alignment: bool,
133 }
134
135 impl MemoryExtra {
136     pub fn new(
137         rng: StdRng,
138         stacked_borrows: bool,
139         tracked_pointer_tag: Option<PtrId>,
140         tracked_call_id: Option<CallId>,
141         tracked_alloc_id: Option<AllocId>,
142         check_alignment: bool,
143     ) -> Self {
144         let stacked_borrows = if stacked_borrows {
145             Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag, tracked_call_id))))
146         } else {
147             None
148         };
149         MemoryExtra {
150             stacked_borrows,
151             intptrcast: Default::default(),
152             extern_statics: FxHashMap::default(),
153             rng: RefCell::new(rng),
154             tracked_alloc_id,
155             check_alignment,
156         }
157     }
158
159     fn add_extern_static<'tcx, 'mir>(
160         this: &mut MiriEvalContext<'mir, 'tcx>,
161         name: &str,
162         ptr: Scalar<Tag>,
163     ) {
164         let ptr = ptr.assert_ptr();
165         assert_eq!(ptr.offset, Size::ZERO);
166         this.memory
167             .extra
168             .extern_statics
169             .insert(Symbol::intern(name), ptr.alloc_id)
170             .unwrap_none();
171     }
172
173     /// Sets up the "extern statics" for this machine.
174     pub fn init_extern_statics<'tcx, 'mir>(
175         this: &mut MiriEvalContext<'mir, 'tcx>,
176     ) -> InterpResult<'tcx> {
177         match this.tcx.sess.target.target.target_os.as_str() {
178             "linux" => {
179                 // "__cxa_thread_atexit_impl"
180                 // This should be all-zero, pointer-sized.
181                 let layout = this.machine.layouts.usize;
182                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
183                 this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
184                 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
185                 // "environ"
186                 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
187             }
188             "windows" => {
189                 // "_tls_used"
190                 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
191                 let layout = this.machine.layouts.u8;
192                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
193                 this.write_scalar(Scalar::from_u8(0), place.into())?;
194                 Self::add_extern_static(this, "_tls_used", place.ptr);
195             }
196             _ => {} // No "extern statics" supported on this target
197         }
198         Ok(())
199     }
200 }
201
202 /// Precomputed layouts of primitive types
203 pub struct PrimitiveLayouts<'tcx> {
204     pub unit: TyAndLayout<'tcx>,
205     pub i8: TyAndLayout<'tcx>,
206     pub i32: TyAndLayout<'tcx>,
207     pub isize: TyAndLayout<'tcx>,
208     pub u8: TyAndLayout<'tcx>,
209     pub u32: TyAndLayout<'tcx>,
210     pub usize: TyAndLayout<'tcx>,
211 }
212
213 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
214     fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
215         Ok(Self {
216             unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
217             i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
218             i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
219             isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
220             u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
221             u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
222             usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
223         })
224     }
225 }
226
227 /// The machine itself.
228 pub struct Evaluator<'mir, 'tcx> {
229     /// Environment variables set by `setenv`.
230     /// Miri does not expose env vars from the host to the emulated program.
231     pub(crate) env_vars: EnvVars<'tcx>,
232
233     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
234     /// These are *pointers* to argc/argv because macOS.
235     /// We also need the full command line as one string because of Windows.
236     pub(crate) argc: Option<Scalar<Tag>>,
237     pub(crate) argv: Option<Scalar<Tag>>,
238     pub(crate) cmd_line: Option<Scalar<Tag>>,
239
240     /// Last OS error location in memory. It is a 32-bit integer.
241     pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
242
243     /// TLS state.
244     pub(crate) tls: TlsData<'tcx>,
245
246     /// If enabled, the `env_vars` field is populated with the host env vars during initialization
247     /// and random number generation is delegated to the host.
248     pub(crate) communicate: bool,
249
250     /// Whether to enforce the validity invariant.
251     pub(crate) validate: bool,
252
253     pub(crate) file_handler: shims::posix::FileHandler,
254     pub(crate) dir_handler: shims::posix::DirHandler,
255
256     /// The temporary used for storing the argument of
257     /// the call to `miri_start_panic` (the panic payload) when unwinding.
258     /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
259     pub(crate) panic_payload: Option<Scalar<Tag>>,
260
261     /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
262     pub(crate) time_anchor: Instant,
263
264     /// The set of threads.
265     pub(crate) threads: ThreadManager<'mir, 'tcx>,
266
267     /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
268     pub(crate) layouts: PrimitiveLayouts<'tcx>,
269
270     /// Allocations that are considered roots of static memory (that may leak).
271     pub(crate) static_roots: Vec<AllocId>,
272 }
273
274 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
275     pub(crate) fn new(
276         communicate: bool,
277         validate: bool,
278         layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
279     ) -> Self {
280         let layouts = PrimitiveLayouts::new(layout_cx)
281             .expect("Couldn't get layouts of primitive types");
282         Evaluator {
283             // `env_vars` could be initialized properly here if `Memory` were available before
284             // calling this method.
285             env_vars: EnvVars::default(),
286             argc: None,
287             argv: None,
288             cmd_line: None,
289             last_error: None,
290             tls: TlsData::default(),
291             communicate,
292             validate,
293             file_handler: Default::default(),
294             dir_handler: Default::default(),
295             panic_payload: None,
296             time_anchor: Instant::now(),
297             layouts,
298             threads: ThreadManager::default(),
299             static_roots: Vec::new(),
300         }
301     }
302 }
303
304 /// A rustc InterpCx for Miri.
305 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
306
307 /// A little trait that's useful to be inherited by extension traits.
308 pub trait MiriEvalContextExt<'mir, 'tcx> {
309     fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
310     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
311 }
312 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
313     #[inline(always)]
314     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
315         self
316     }
317     #[inline(always)]
318     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
319         self
320     }
321 }
322
323 /// Machine hook implementations.
324 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
325     type MemoryKind = MiriMemoryKind;
326
327     type FrameExtra = FrameData<'tcx>;
328     type MemoryExtra = MemoryExtra;
329     type AllocExtra = AllocExtra;
330     type PointerTag = Tag;
331     type ExtraFnVal = Dlsym;
332
333     type MemoryMap =
334         MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
335
336     const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
337
338     #[inline(always)]
339     fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
340         memory_extra.check_alignment
341     }
342
343     #[inline(always)]
344     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
345         ecx.machine.validate
346     }
347
348     #[inline(always)]
349     fn find_mir_or_eval_fn(
350         ecx: &mut InterpCx<'mir, 'tcx, Self>,
351         instance: ty::Instance<'tcx>,
352         args: &[OpTy<'tcx, Tag>],
353         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
354         unwind: Option<mir::BasicBlock>,
355     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
356         ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
357     }
358
359     #[inline(always)]
360     fn call_extra_fn(
361         ecx: &mut InterpCx<'mir, 'tcx, Self>,
362         fn_val: Dlsym,
363         args: &[OpTy<'tcx, Tag>],
364         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
365         _unwind: Option<mir::BasicBlock>,
366     ) -> InterpResult<'tcx> {
367         ecx.call_dlsym(fn_val, args, ret)
368     }
369
370     #[inline(always)]
371     fn call_intrinsic(
372         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
373         instance: ty::Instance<'tcx>,
374         args: &[OpTy<'tcx, Tag>],
375         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
376         unwind: Option<mir::BasicBlock>,
377     ) -> InterpResult<'tcx> {
378         ecx.call_intrinsic(instance, args, ret, unwind)
379     }
380
381     #[inline(always)]
382     fn assert_panic(
383         ecx: &mut InterpCx<'mir, 'tcx, Self>,
384         msg: &mir::AssertMessage<'tcx>,
385         unwind: Option<mir::BasicBlock>,
386     ) -> InterpResult<'tcx> {
387         ecx.assert_panic(msg, unwind)
388     }
389
390     #[inline(always)]
391     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
392         throw_machine_stop!(TerminationInfo::Abort(None))
393     }
394
395     #[inline(always)]
396     fn binary_ptr_op(
397         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
398         bin_op: mir::BinOp,
399         left: ImmTy<'tcx, Tag>,
400         right: ImmTy<'tcx, Tag>,
401     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
402         ecx.binary_ptr_op(bin_op, left, right)
403     }
404
405     fn box_alloc(
406         ecx: &mut InterpCx<'mir, 'tcx, Self>,
407         dest: PlaceTy<'tcx, Tag>,
408     ) -> InterpResult<'tcx> {
409         trace!("box_alloc for {:?}", dest.layout.ty);
410         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
411         // First argument: `size`.
412         // (`0` is allowed here -- this is expected to be handled by the lang item).
413         let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
414
415         // Second argument: `align`.
416         let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
417
418         // Call the `exchange_malloc` lang item.
419         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
420         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
421         ecx.call_function(
422             malloc,
423             &[size.into(), align.into()],
424             Some(dest),
425             // Don't do anything when we are done. The `statement()` function will increment
426             // the old stack frame's stmt counter to the next statement, which means that when
427             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
428             StackPopCleanup::None { cleanup: true },
429         )?;
430         Ok(())
431     }
432
433     fn thread_local_static_alloc_id(
434         ecx: &mut InterpCx<'mir, 'tcx, Self>,
435         def_id: DefId,
436     ) -> InterpResult<'tcx, AllocId> {
437         ecx.get_or_create_thread_local_alloc_id(def_id)
438     }
439
440     fn extern_static_alloc_id(
441         memory: &Memory<'mir, 'tcx, Self>,
442         def_id: DefId,
443     ) -> InterpResult<'tcx, AllocId> {
444         let attrs = memory.tcx.get_attrs(def_id);
445         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
446             Some(name) => name,
447             None => memory.tcx.item_name(def_id),
448         };
449         if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
450             Ok(id)
451         } else {
452             throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
453         }
454     }
455
456     fn init_allocation_extra<'b>(
457         memory_extra: &MemoryExtra,
458         id: AllocId,
459         alloc: Cow<'b, Allocation>,
460         kind: Option<MemoryKind<Self::MemoryKind>>,
461     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
462         if Some(id) == memory_extra.tracked_alloc_id {
463             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
464         }
465
466         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
467         let alloc = alloc.into_owned();
468         let (stacks, base_tag) =
469             if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
470                 let (stacks, base_tag) =
471                     Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
472                 (Some(stacks), base_tag)
473             } else {
474                 // No stacks, no tag.
475                 (None, Tag::Untagged)
476             };
477         let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
478         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
479             |alloc| {
480                 if let Some(stacked_borrows) = &mut stacked_borrows {
481                     // Only globals may already contain pointers at this point
482                     assert_eq!(kind, MiriMemoryKind::Global.into());
483                     stacked_borrows.global_base_ptr(alloc)
484                 } else {
485                     Tag::Untagged
486                 }
487             },
488             AllocExtra { stacked_borrows: stacks },
489         );
490         (Cow::Owned(alloc), base_tag)
491     }
492
493     #[inline(always)]
494     fn before_deallocation(
495         memory_extra: &mut Self::MemoryExtra,
496         id: AllocId,
497     ) -> InterpResult<'tcx> {
498         if Some(id) == memory_extra.tracked_alloc_id {
499             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
500         }
501
502         Ok(())
503     }
504
505     #[inline(always)]
506     fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
507         if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
508             stacked_borrows.borrow_mut().global_base_ptr(id)
509         } else {
510             Tag::Untagged
511         }
512     }
513
514     #[inline(always)]
515     fn retag(
516         ecx: &mut InterpCx<'mir, 'tcx, Self>,
517         kind: mir::RetagKind,
518         place: PlaceTy<'tcx, Tag>,
519     ) -> InterpResult<'tcx> {
520         if ecx.memory.extra.stacked_borrows.is_some() {
521             ecx.retag(kind, place)
522         } else {
523             Ok(())
524         }
525     }
526
527     #[inline(always)]
528     fn init_frame_extra(
529         ecx: &mut InterpCx<'mir, 'tcx, Self>,
530         frame: Frame<'mir, 'tcx, Tag>,
531     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
532         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
533         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
534             stacked_borrows.borrow_mut().new_call()
535         });
536         let extra = FrameData { call_id, catch_unwind: None };
537         Ok(frame.with_extra(extra))
538     }
539
540     fn stack<'a>(
541         ecx: &'a InterpCx<'mir, 'tcx, Self>
542     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
543         ecx.active_thread_stack()
544     }
545
546     fn stack_mut<'a>(
547         ecx: &'a mut InterpCx<'mir, 'tcx, Self>
548     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
549         ecx.active_thread_stack_mut()
550     }
551
552     #[inline(always)]
553     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
554         if ecx.memory.extra.stacked_borrows.is_some() {
555             ecx.retag_return_place()
556         } else {
557             Ok(())
558         }
559     }
560
561     #[inline(always)]
562     fn after_stack_pop(
563         ecx: &mut InterpCx<'mir, 'tcx, Self>,
564         frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
565         unwinding: bool,
566     ) -> InterpResult<'tcx, StackPopJump> {
567         ecx.handle_stack_pop(frame.extra, unwinding)
568     }
569
570     #[inline(always)]
571     fn int_to_ptr(
572         memory: &Memory<'mir, 'tcx, Self>,
573         int: u64,
574     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
575         intptrcast::GlobalState::int_to_ptr(int, memory)
576     }
577
578     #[inline(always)]
579     fn ptr_to_int(
580         memory: &Memory<'mir, 'tcx, Self>,
581         ptr: Pointer<Self::PointerTag>,
582     ) -> InterpResult<'tcx, u64> {
583         intptrcast::GlobalState::ptr_to_int(ptr, memory)
584     }
585 }
586
587 impl AllocationExtra<Tag> for AllocExtra {
588     #[inline(always)]
589     fn memory_read<'tcx>(
590         alloc: &Allocation<Tag, AllocExtra>,
591         ptr: Pointer<Tag>,
592         size: Size,
593     ) -> InterpResult<'tcx> {
594         if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
595             stacked_borrows.memory_read(ptr, size)
596         } else {
597             Ok(())
598         }
599     }
600
601     #[inline(always)]
602     fn memory_written<'tcx>(
603         alloc: &mut Allocation<Tag, AllocExtra>,
604         ptr: Pointer<Tag>,
605         size: Size,
606     ) -> InterpResult<'tcx> {
607         if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
608             stacked_borrows.memory_written(ptr, size)
609         } else {
610             Ok(())
611         }
612     }
613
614     #[inline(always)]
615     fn memory_deallocated<'tcx>(
616         alloc: &mut Allocation<Tag, AllocExtra>,
617         ptr: Pointer<Tag>,
618         size: Size,
619     ) -> InterpResult<'tcx> {
620         if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
621             stacked_borrows.memory_deallocated(ptr, size)
622         } else {
623             Ok(())
624         }
625     }
626 }