]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Fix the problem of sending pointed to thread local statics. Add a regression test.
[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 access_local(
437         ecx: &InterpCx<'mir, 'tcx, Self>,
438         frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
439         local: mir::Local,
440     ) -> InterpResult<'tcx, Operand<Self::PointerTag>> {
441         match frame.body.local_decls[local].local_info {
442             mir::LocalInfo::StaticRef { def_id, is_thread_local: true } => {
443                 let static_alloc_id = ecx.tcx.alloc_map.lock().create_static_alloc(def_id);
444                 let alloc_id = ecx.memory.extra.tls.get_or_register_allocation(*ecx.memory.tcx, static_alloc_id);
445                 let tag = Self::tag_global_base_pointer(&ecx.memory.extra, alloc_id);
446                 let pointer: Pointer = alloc_id.into();
447                 let pointer = pointer.with_tag(tag);
448                 let scalar: Scalar<_> = pointer.into();
449                 let scalar: ScalarMaybeUndef<_> = scalar.into();
450                 let immediate: Immediate<_> = scalar.into();
451                 Ok(
452                     Operand::Immediate(immediate)
453                 )
454             },
455             _ => frame.locals[local].access(),
456         }
457     }
458
459     fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
460         let tcx = mem.tcx;
461         let alloc = tcx.alloc_map.lock().get(id);
462         match alloc {
463             Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => {
464                 // Figure out if this is an extern static, and if yes, which one.
465                 let attrs = tcx.get_attrs(def_id);
466                 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
467                     Some(name) => name,
468                     None => tcx.item_name(def_id),
469                 };
470                 // Check if we know this one.
471                 if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
472                     trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
473                     *canonical_id
474                 } else {
475                     // Return original id; `Memory::get_static_alloc` will throw an error.
476                     id
477                 }
478             },
479             Some(GlobalAlloc::Static(def_id)) if tcx.has_attr(def_id, sym::thread_local) => {
480                 // We have a thread local, so we need to get a unique allocation id for it.
481                 mem.extra.tls.get_or_register_allocation(*tcx, id)
482             },
483             _ => {
484                 // No need to canonicalize anything.
485                 id
486             }
487         }
488     }
489
490     #[inline(always)]
491     fn resolve_maybe_global_alloc(
492         tcx: ty::query::TyCtxtAt<'tcx>,
493         extra: &Self::MemoryExtra,
494         id: AllocId,
495     ) -> Option<mir::interpret::GlobalAlloc<'tcx>> {
496         extra.tls.resolve_allocation(*tcx, id)
497     }
498
499     fn init_allocation_extra<'b>(
500         memory_extra: &MemoryExtra,
501         id: AllocId,
502         alloc: Cow<'b, Allocation>,
503         kind: Option<MemoryKind<Self::MemoryKind>>,
504     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
505         if Some(id) == memory_extra.tracked_alloc_id {
506             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
507         }
508
509         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
510         let alloc = alloc.into_owned();
511         let (stacks, base_tag) =
512             if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
513                 let (stacks, base_tag) =
514                     Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
515                 (Some(stacks), base_tag)
516             } else {
517                 // No stacks, no tag.
518                 (None, Tag::Untagged)
519             };
520         let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
521         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
522             |alloc| {
523                 if let Some(stacked_borrows) = &mut stacked_borrows {
524                     // Only globals may already contain pointers at this point
525                     assert_eq!(kind, MiriMemoryKind::Global.into());
526                     stacked_borrows.global_base_ptr(alloc)
527                 } else {
528                     Tag::Untagged
529                 }
530             },
531             AllocExtra { stacked_borrows: stacks },
532         );
533         (Cow::Owned(alloc), base_tag)
534     }
535
536     #[inline(always)]
537     fn before_deallocation(
538         memory_extra: &mut Self::MemoryExtra,
539         id: AllocId,
540     ) -> InterpResult<'tcx> {
541         if Some(id) == memory_extra.tracked_alloc_id {
542             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
543         }
544         
545         Ok(())
546     }
547
548     #[inline(always)]
549     fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
550         if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
551             stacked_borrows.borrow_mut().global_base_ptr(id)
552         } else {
553             Tag::Untagged
554         }
555     }
556
557     #[inline(always)]
558     fn retag(
559         ecx: &mut InterpCx<'mir, 'tcx, Self>,
560         kind: mir::RetagKind,
561         place: PlaceTy<'tcx, Tag>,
562     ) -> InterpResult<'tcx> {
563         if ecx.memory.extra.stacked_borrows.is_some() {
564             ecx.retag(kind, place)
565         } else {
566             Ok(())
567         }
568     }
569
570     #[inline(always)]
571     fn init_frame_extra(
572         ecx: &mut InterpCx<'mir, 'tcx, Self>,
573         frame: Frame<'mir, 'tcx, Tag>,
574     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
575         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
576         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
577             stacked_borrows.borrow_mut().new_call()
578         });
579         let extra = FrameData { call_id, catch_unwind: None };
580         Ok(frame.with_extra(extra))
581     }
582
583     #[inline(always)]
584     fn stack<'a>(
585         ecx: &'a InterpCx<'mir, 'tcx, Self>,
586     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
587         &ecx.machine.stack
588     }
589
590     #[inline(always)]
591     fn stack_mut<'a>(
592         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
593     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
594         &mut ecx.machine.stack
595     }
596
597     #[inline(always)]
598     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
599         if ecx.memory.extra.stacked_borrows.is_some() {
600             ecx.retag_return_place()
601         } else {
602             Ok(())
603         }
604     }
605
606     #[inline(always)]
607     fn after_stack_pop(
608         ecx: &mut InterpCx<'mir, 'tcx, Self>,
609         frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
610         unwinding: bool,
611     ) -> InterpResult<'tcx, StackPopJump> {
612         ecx.handle_stack_pop(frame.extra, unwinding)
613     }
614
615     #[inline(always)]
616     fn int_to_ptr(
617         memory: &Memory<'mir, 'tcx, Self>,
618         int: u64,
619     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
620         intptrcast::GlobalState::int_to_ptr(int, memory)
621     }
622
623     #[inline(always)]
624     fn ptr_to_int(
625         memory: &Memory<'mir, 'tcx, Self>,
626         ptr: Pointer<Self::PointerTag>,
627     ) -> InterpResult<'tcx, u64> {
628         intptrcast::GlobalState::ptr_to_int(ptr, memory)
629     }
630 }
631
632 impl AllocationExtra<Tag> for AllocExtra {
633     #[inline(always)]
634     fn memory_read<'tcx>(
635         alloc: &Allocation<Tag, AllocExtra>,
636         ptr: Pointer<Tag>,
637         size: Size,
638     ) -> InterpResult<'tcx> {
639         if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
640             stacked_borrows.memory_read(ptr, size)
641         } else {
642             Ok(())
643         }
644     }
645
646     #[inline(always)]
647     fn memory_written<'tcx>(
648         alloc: &mut Allocation<Tag, AllocExtra>,
649         ptr: Pointer<Tag>,
650         size: Size,
651     ) -> InterpResult<'tcx> {
652         if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
653             stacked_borrows.memory_written(ptr, size)
654         } else {
655             Ok(())
656         }
657     }
658
659     #[inline(always)]
660     fn memory_deallocated<'tcx>(
661         alloc: &mut Allocation<Tag, AllocExtra>,
662         ptr: Pointer<Tag>,
663         size: Size,
664     ) -> InterpResult<'tcx> {
665         if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
666             stacked_borrows.memory_deallocated(ptr, size)
667         } else {
668             Ok(())
669         }
670     }
671 }