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