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