]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Generate thread local allocations in eval_maybe_thread_local_static_const.
[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     middle::codegen_fn_attrs::CodegenFnAttrFlags,
18     mir,
19     ty::{
20         self,
21         Instance,
22         layout::{LayoutCx, LayoutError, TyAndLayout},
23         TyCtxt,
24     },
25 };
26 use rustc_span::symbol::{sym, Symbol};
27 use rustc_target::abi::{LayoutOf, Size};
28
29 use crate::*;
30
31 pub use crate::threads::{ThreadId, ThreadManager, ThreadState};
32
33 // Some global facts about the emulated machine.
34 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
35 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
36 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
37 pub const NUM_CPUS: u64 = 1;
38
39 /// Extra data stored with each stack frame
40 #[derive(Debug)]
41 pub struct FrameData<'tcx> {
42     /// Extra data for Stacked Borrows.
43     pub call_id: stacked_borrows::CallId,
44
45     /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
46     /// called by `try`). When this frame is popped during unwinding a panic,
47     /// we stop unwinding, use the `CatchUnwindData` to handle catching.
48     pub catch_unwind: Option<CatchUnwindData<'tcx>>,
49 }
50
51 /// Extra memory kinds
52 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
53 pub enum MiriMemoryKind {
54     /// `__rust_alloc` memory.
55     Rust,
56     /// `malloc` memory.
57     C,
58     /// Windows `HeapAlloc` memory.
59     WinHeap,
60     /// Memory for args, errno, extern statics and other parts of the machine-managed environment.
61     /// This memory may leak.
62     Machine,
63     /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
64     Env,
65     /// Globals copied from `tcx`.
66     /// This memory may leak.
67     Global,
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 => 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         }
99     }
100 }
101
102 /// Extra per-allocation data
103 #[derive(Debug, Clone)]
104 pub struct AllocExtra {
105     /// Stacked Borrows state is only added if it is enabled.
106     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
107 }
108
109 /// Extra global memory data
110 #[derive(Clone, Debug)]
111 pub struct MemoryExtra {
112     pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
113     pub intptrcast: intptrcast::MemoryExtra,
114
115     /// Mapping extern static names to their canonical allocation.
116     extern_statics: FxHashMap<Symbol, AllocId>,
117
118     /// The random number generator used for resolving non-determinism.
119     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
120     pub(crate) rng: RefCell<StdRng>,
121
122     /// An allocation ID to report when it is being allocated
123     /// (helps for debugging memory leaks and use after free bugs).
124     tracked_alloc_id: Option<AllocId>,
125
126     /// Controls whether alignment of memory accesses is being checked.
127     check_alignment: bool,
128 }
129
130 impl MemoryExtra {
131     pub fn new(
132         rng: StdRng,
133         stacked_borrows: bool,
134         tracked_pointer_tag: Option<PtrId>,
135         tracked_alloc_id: Option<AllocId>,
136         check_alignment: bool,
137     ) -> Self {
138         let stacked_borrows = if stacked_borrows {
139             Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
140         } else {
141             None
142         };
143         MemoryExtra {
144             stacked_borrows,
145             intptrcast: Default::default(),
146             extern_statics: FxHashMap::default(),
147             rng: RefCell::new(rng),
148             tracked_alloc_id,
149             check_alignment,
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: ThreadManager<'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 enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
335         ecx.machine.validate
336     }
337
338     #[inline(always)]
339     fn find_mir_or_eval_fn(
340         ecx: &mut InterpCx<'mir, 'tcx, Self>,
341         instance: ty::Instance<'tcx>,
342         args: &[OpTy<'tcx, Tag>],
343         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
344         unwind: Option<mir::BasicBlock>,
345     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
346         ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
347     }
348
349     #[inline(always)]
350     fn call_extra_fn(
351         ecx: &mut InterpCx<'mir, 'tcx, Self>,
352         fn_val: Dlsym,
353         args: &[OpTy<'tcx, Tag>],
354         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
355         _unwind: Option<mir::BasicBlock>,
356     ) -> InterpResult<'tcx> {
357         ecx.call_dlsym(fn_val, args, ret)
358     }
359
360     #[inline(always)]
361     fn call_intrinsic(
362         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
363         instance: ty::Instance<'tcx>,
364         args: &[OpTy<'tcx, Tag>],
365         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
366         unwind: Option<mir::BasicBlock>,
367     ) -> InterpResult<'tcx> {
368         ecx.call_intrinsic(instance, args, ret, unwind)
369     }
370
371     #[inline(always)]
372     fn assert_panic(
373         ecx: &mut InterpCx<'mir, 'tcx, Self>,
374         msg: &mir::AssertMessage<'tcx>,
375         unwind: Option<mir::BasicBlock>,
376     ) -> InterpResult<'tcx> {
377         ecx.assert_panic(msg, unwind)
378     }
379
380     #[inline(always)]
381     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
382         throw_machine_stop!(TerminationInfo::Abort(None))
383     }
384
385     #[inline(always)]
386     fn binary_ptr_op(
387         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
388         bin_op: mir::BinOp,
389         left: ImmTy<'tcx, Tag>,
390         right: ImmTy<'tcx, Tag>,
391     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
392         ecx.binary_ptr_op(bin_op, left, right)
393     }
394
395     fn box_alloc(
396         ecx: &mut InterpCx<'mir, 'tcx, Self>,
397         dest: PlaceTy<'tcx, Tag>,
398     ) -> InterpResult<'tcx> {
399         trace!("box_alloc for {:?}", dest.layout.ty);
400         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
401         // First argument: `size`.
402         // (`0` is allowed here -- this is expected to be handled by the lang item).
403         let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
404
405         // Second argument: `align`.
406         let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
407
408         // Call the `exchange_malloc` lang item.
409         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
410         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
411         ecx.call_function(
412             malloc,
413             &[size.into(), align.into()],
414             Some(dest),
415             // Don't do anything when we are done. The `statement()` function will increment
416             // the old stack frame's stmt counter to the next statement, which means that when
417             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
418             StackPopCleanup::None { cleanup: true },
419         )?;
420         Ok(())
421     }
422
423     fn eval_maybe_thread_local_static_const(
424         ecx: &InterpCx<'mir, 'tcx, Self>,
425         mut val: mir::interpret::ConstValue<'tcx>,
426     ) -> InterpResult<'tcx, mir::interpret::ConstValue<'tcx>> {
427         match &mut val {
428             mir::interpret::ConstValue::Scalar(Scalar::Ptr(ptr)) => {
429                 let alloc_id = ptr.alloc_id;
430                 let alloc = ecx.tcx.alloc_map.lock().get(alloc_id);
431                 match alloc {
432                     Some(GlobalAlloc::Static(def_id))
433                         if ecx
434                             .tcx
435                             .codegen_fn_attrs(def_id)
436                             .flags
437                             .contains(CodegenFnAttrFlags::THREAD_LOCAL) =>
438                     {
439                         // We have a thread-local static.
440                         let new_alloc_id = if let Some(new_alloc_id) =
441                             ecx.get_thread_local_alloc_id(alloc_id)
442                         {
443                             new_alloc_id
444                         } else {
445                             if ecx.tcx.is_foreign_item(def_id) {
446                                 throw_unsup_format!(
447                                     "Foreign thread-local statics are not supported."
448                                 )
449                             }
450                             let instance = Instance::mono(ecx.tcx.tcx, def_id);
451                             let gid = GlobalId { instance, promoted: None };
452                             let raw_const = ecx
453                                 .tcx
454                                 .const_eval_raw(ty::ParamEnv::reveal_all().and(gid))
455                                 .map_err(|err| {
456                                     // no need to report anything, the const_eval call takes care of that
457                                     // for statics
458                                     assert!(ecx.tcx.is_static(def_id));
459                                     match err {
460                                         ErrorHandled::Reported => err_inval!(ReferencedConstant),
461                                         ErrorHandled::TooGeneric => err_inval!(TooGeneric),
462                                     }
463                                 })?;
464                             let id = raw_const.alloc_id;
465                             let mut alloc_map = ecx.tcx.alloc_map.lock();
466                             let allocation = alloc_map.unwrap_memory(id);
467                             let new_alloc_id = alloc_map.create_memory_alloc(allocation);
468                             ecx.set_thread_local_alloc_id(alloc_id, new_alloc_id);
469                             new_alloc_id
470                         };
471                         ptr.alloc_id = new_alloc_id;
472                     }
473                     _ => {}
474                 }
475             }
476             _ => {}
477         }
478         Ok(val)
479     }
480
481     fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
482         let tcx = mem.tcx;
483         // Figure out if this is an extern static, and if yes, which one.
484         let def_id = match tcx.alloc_map.lock().get(id) {
485             Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => def_id,
486             _ => {
487                 // No need to canonicalize anything.
488                 return id;
489             }
490         };
491         let attrs = tcx.get_attrs(def_id);
492         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
493             Some(name) => name,
494             None => tcx.item_name(def_id),
495         };
496         // Check if we know this one.
497         if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
498             trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
499             *canonical_id
500         } else {
501             // Return original id; `Memory::get_static_alloc` will throw an error.
502             id
503         }
504     }
505
506     fn init_allocation_extra<'b>(
507         memory_extra: &MemoryExtra,
508         id: AllocId,
509         alloc: Cow<'b, Allocation>,
510         kind: Option<MemoryKind<Self::MemoryKind>>,
511     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
512         if Some(id) == memory_extra.tracked_alloc_id {
513             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
514         }
515
516         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
517         let alloc = alloc.into_owned();
518         let (stacks, base_tag) =
519             if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
520                 let (stacks, base_tag) =
521                     Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
522                 (Some(stacks), base_tag)
523             } else {
524                 // No stacks, no tag.
525                 (None, Tag::Untagged)
526             };
527         let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
528         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
529             |alloc| {
530                 if let Some(stacked_borrows) = &mut stacked_borrows {
531                     // Only globals may already contain pointers at this point
532                     assert_eq!(kind, MiriMemoryKind::Global.into());
533                     stacked_borrows.global_base_ptr(alloc)
534                 } else {
535                     Tag::Untagged
536                 }
537             },
538             AllocExtra { stacked_borrows: stacks },
539         );
540         (Cow::Owned(alloc), base_tag)
541     }
542
543     #[inline(always)]
544     fn before_deallocation(
545         memory_extra: &mut Self::MemoryExtra,
546         id: AllocId,
547     ) -> InterpResult<'tcx> {
548         if Some(id) == memory_extra.tracked_alloc_id {
549             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
550         }
551         
552         Ok(())
553     }
554
555     #[inline(always)]
556     fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
557         if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
558             stacked_borrows.borrow_mut().global_base_ptr(id)
559         } else {
560             Tag::Untagged
561         }
562     }
563
564     #[inline(always)]
565     fn retag(
566         ecx: &mut InterpCx<'mir, 'tcx, Self>,
567         kind: mir::RetagKind,
568         place: PlaceTy<'tcx, Tag>,
569     ) -> InterpResult<'tcx> {
570         if ecx.memory.extra.stacked_borrows.is_some() {
571             ecx.retag(kind, place)
572         } else {
573             Ok(())
574         }
575     }
576
577     #[inline(always)]
578     fn init_frame_extra(
579         ecx: &mut InterpCx<'mir, 'tcx, Self>,
580         frame: Frame<'mir, 'tcx, Tag>,
581     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
582         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
583         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
584             stacked_borrows.borrow_mut().new_call()
585         });
586         let extra = FrameData { call_id, catch_unwind: None };
587         Ok(frame.with_extra(extra))
588     }
589
590     fn stack<'a>(
591         ecx: &'a InterpCx<'mir, 'tcx, Self>
592     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
593         ecx.active_thread_stack()
594     }
595
596     fn stack_mut<'a>(
597         ecx: &'a mut InterpCx<'mir, 'tcx, Self>
598     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
599         ecx.active_thread_stack_mut()
600     }
601
602     #[inline(always)]
603     fn stack<'a>(
604         ecx: &'a InterpCx<'mir, 'tcx, Self>,
605     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
606         &ecx.machine.stack
607     }
608
609     #[inline(always)]
610     fn stack_mut<'a>(
611         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
612     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
613         &mut ecx.machine.stack
614     }
615
616     #[inline(always)]
617     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
618         if ecx.memory.extra.stacked_borrows.is_some() {
619             ecx.retag_return_place()
620         } else {
621             Ok(())
622         }
623     }
624
625     #[inline(always)]
626     fn after_stack_pop(
627         ecx: &mut InterpCx<'mir, 'tcx, Self>,
628         frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
629         unwinding: bool,
630     ) -> InterpResult<'tcx, StackPopJump> {
631         ecx.handle_stack_pop(frame.extra, unwinding)
632     }
633
634     #[inline(always)]
635     fn int_to_ptr(
636         memory: &Memory<'mir, 'tcx, Self>,
637         int: u64,
638     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
639         intptrcast::GlobalState::int_to_ptr(int, memory)
640     }
641
642     #[inline(always)]
643     fn ptr_to_int(
644         memory: &Memory<'mir, 'tcx, Self>,
645         ptr: Pointer<Self::PointerTag>,
646     ) -> InterpResult<'tcx, u64> {
647         intptrcast::GlobalState::ptr_to_int(ptr, memory)
648     }
649 }
650
651 impl AllocationExtra<Tag> for AllocExtra {
652     #[inline(always)]
653     fn memory_read<'tcx>(
654         alloc: &Allocation<Tag, AllocExtra>,
655         ptr: Pointer<Tag>,
656         size: Size,
657     ) -> InterpResult<'tcx> {
658         if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
659             stacked_borrows.memory_read(ptr, size)
660         } else {
661             Ok(())
662         }
663     }
664
665     #[inline(always)]
666     fn memory_written<'tcx>(
667         alloc: &mut Allocation<Tag, AllocExtra>,
668         ptr: Pointer<Tag>,
669         size: Size,
670     ) -> InterpResult<'tcx> {
671         if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
672             stacked_borrows.memory_written(ptr, size)
673         } else {
674             Ok(())
675         }
676     }
677
678     #[inline(always)]
679     fn memory_deallocated<'tcx>(
680         alloc: &mut Allocation<Tag, AllocExtra>,
681         ptr: Pointer<Tag>,
682         size: Size,
683     ) -> InterpResult<'tcx> {
684         if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
685             stacked_borrows.memory_deallocated(ptr, size)
686         } else {
687             Ok(())
688         }
689     }
690 }