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