]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
add machine hook tcx parameters
[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::fmt;
7 use std::num::NonZeroU64;
8 use std::time::Instant;
9
10 use rand::rngs::StdRng;
11 use rand::SeedableRng;
12
13 use rustc_ast::ast::Mutability;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_middle::{
16     mir,
17     ty::{
18         self,
19         layout::{LayoutCx, LayoutError, LayoutOf, TyAndLayout},
20         Instance, TyCtxt, TypeAndMut,
21     },
22 };
23 use rustc_span::def_id::{CrateNum, DefId};
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_target::abi::Size;
26 use rustc_target::spec::abi::Abi;
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 pub struct FrameData<'tcx> {
38     /// Extra data for Stacked Borrows.
39     pub call_id: stacked_borrows::CallId,
40
41     /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
42     /// called by `try`). When this frame is popped during unwinding a panic,
43     /// we stop unwinding, use the `CatchUnwindData` to handle catching.
44     pub catch_unwind: Option<CatchUnwindData<'tcx>>,
45
46     /// If `measureme` profiling is enabled, holds timing information
47     /// for the start of this frame. When we finish executing this frame,
48     /// we use this to register a completed event with `measureme`.
49     pub timing: Option<measureme::DetachedTiming>,
50 }
51
52 impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
53     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54         // Omitting `timing`, it does not support `Debug`.
55         let FrameData { call_id, catch_unwind, timing: _ } = self;
56         f.debug_struct("FrameData")
57             .field("call_id", call_id)
58             .field("catch_unwind", catch_unwind)
59             .finish()
60     }
61 }
62
63 /// Extra memory kinds
64 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
65 pub enum MiriMemoryKind {
66     /// `__rust_alloc` memory.
67     Rust,
68     /// `malloc` memory.
69     C,
70     /// Windows `HeapAlloc` memory.
71     WinHeap,
72     /// Memory for args, errno, and other parts of the machine-managed environment.
73     /// This memory may leak.
74     Machine,
75     /// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
76     /// because we clean it up and leak-check it.
77     Runtime,
78     /// Globals copied from `tcx`.
79     /// This memory may leak.
80     Global,
81     /// Memory for extern statics.
82     /// This memory may leak.
83     ExternStatic,
84     /// Memory for thread-local statics.
85     /// This memory may leak.
86     Tls,
87 }
88
89 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
90     #[inline(always)]
91     fn into(self) -> MemoryKind<MiriMemoryKind> {
92         MemoryKind::Machine(self)
93     }
94 }
95
96 impl MayLeak for MiriMemoryKind {
97     #[inline(always)]
98     fn may_leak(self) -> bool {
99         use self::MiriMemoryKind::*;
100         match self {
101             Rust | C | WinHeap | Runtime => false,
102             Machine | Global | ExternStatic | Tls => true,
103         }
104     }
105 }
106
107 impl fmt::Display for MiriMemoryKind {
108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109         use self::MiriMemoryKind::*;
110         match self {
111             Rust => write!(f, "Rust heap"),
112             C => write!(f, "C heap"),
113             WinHeap => write!(f, "Windows heap"),
114             Machine => write!(f, "machine-managed memory"),
115             Runtime => write!(f, "language runtime memory"),
116             Global => write!(f, "global (static or const)"),
117             ExternStatic => write!(f, "extern static"),
118             Tls => write!(f, "thread-local static"),
119         }
120     }
121 }
122
123 /// Pointer provenance (tag).
124 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125 pub struct Tag {
126     pub alloc_id: AllocId,
127     /// Stacked Borrows tag.
128     pub sb: SbTag,
129 }
130
131 impl Provenance for Tag {
132     /// We use absolute addresses in the `offset` of a `Pointer<Tag>`.
133     const OFFSET_IS_ADDR: bool = true;
134
135     /// We cannot err on partial overwrites, it happens too often in practice (due to unions).
136     const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = false;
137
138     fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139         let (tag, addr) = ptr.into_parts(); // address is absolute
140         write!(f, "0x{:x}", addr.bytes())?;
141         // Forward `alternate` flag to `alloc_id` printing.
142         if f.alternate() {
143             write!(f, "[{:#?}]", tag.alloc_id)?;
144         } else {
145             write!(f, "[{:?}]", tag.alloc_id)?;
146         }
147         // Print Stacked Borrows tag.
148         write!(f, "{:?}", tag.sb)
149     }
150
151     fn get_alloc_id(self) -> AllocId {
152         self.alloc_id
153     }
154 }
155
156 /// Extra per-allocation data
157 #[derive(Debug, Clone)]
158 pub struct AllocExtra {
159     /// Stacked Borrows state is only added if it is enabled.
160     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
161     /// Data race detection via the use of a vector-clock,
162     ///  this is only added if it is enabled.
163     pub data_race: Option<data_race::AllocExtra>,
164 }
165
166 /// Precomputed layouts of primitive types
167 pub struct PrimitiveLayouts<'tcx> {
168     pub unit: TyAndLayout<'tcx>,
169     pub i8: TyAndLayout<'tcx>,
170     pub i32: TyAndLayout<'tcx>,
171     pub isize: TyAndLayout<'tcx>,
172     pub u8: TyAndLayout<'tcx>,
173     pub u32: TyAndLayout<'tcx>,
174     pub usize: TyAndLayout<'tcx>,
175     pub bool: TyAndLayout<'tcx>,
176     pub mut_raw_ptr: TyAndLayout<'tcx>,
177 }
178
179 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
180     fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
181         let tcx = layout_cx.tcx;
182         let mut_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
183         Ok(Self {
184             unit: layout_cx.layout_of(tcx.mk_unit())?,
185             i8: layout_cx.layout_of(tcx.types.i8)?,
186             i32: layout_cx.layout_of(tcx.types.i32)?,
187             isize: layout_cx.layout_of(tcx.types.isize)?,
188             u8: layout_cx.layout_of(tcx.types.u8)?,
189             u32: layout_cx.layout_of(tcx.types.u32)?,
190             usize: layout_cx.layout_of(tcx.types.usize)?,
191             bool: layout_cx.layout_of(tcx.types.bool)?,
192             mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
193         })
194     }
195 }
196
197 /// The machine itself.
198 pub struct Evaluator<'mir, 'tcx> {
199     pub stacked_borrows: Option<stacked_borrows::GlobalState>,
200     pub data_race: Option<data_race::GlobalState>,
201     pub intptrcast: intptrcast::GlobalState,
202
203     /// Environment variables set by `setenv`.
204     /// Miri does not expose env vars from the host to the emulated program.
205     pub(crate) env_vars: EnvVars<'tcx>,
206
207     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
208     /// These are *pointers* to argc/argv because macOS.
209     /// We also need the full command line as one string because of Windows.
210     pub(crate) argc: Option<MemPlace<Tag>>,
211     pub(crate) argv: Option<MemPlace<Tag>>,
212     pub(crate) cmd_line: Option<MemPlace<Tag>>,
213
214     /// TLS state.
215     pub(crate) tls: TlsData<'tcx>,
216
217     /// What should Miri do when an op requires communicating with the host,
218     /// such as accessing host env vars, random number generation, and
219     /// file system access.
220     pub(crate) isolated_op: IsolatedOp,
221
222     /// Whether to enforce the validity invariant.
223     pub(crate) validate: bool,
224
225     /// Whether to enforce validity (e.g., initialization) of integers and floats.
226     pub(crate) enforce_number_validity: bool,
227
228     /// Whether to enforce [ABI](Abi) of function calls.
229     pub(crate) enforce_abi: bool,
230
231     pub(crate) file_handler: shims::posix::FileHandler,
232     pub(crate) dir_handler: shims::posix::DirHandler,
233
234     /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
235     pub(crate) time_anchor: Instant,
236
237     /// The set of threads.
238     pub(crate) threads: ThreadManager<'mir, 'tcx>,
239
240     /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
241     pub(crate) layouts: PrimitiveLayouts<'tcx>,
242
243     /// Allocations that are considered roots of static memory (that may leak).
244     pub(crate) static_roots: Vec<AllocId>,
245
246     /// The `measureme` profiler used to record timing information about
247     /// the emulated program.
248     profiler: Option<measureme::Profiler>,
249     /// Used with `profiler` to cache the `StringId`s for event names
250     /// uesd with `measureme`.
251     string_cache: FxHashMap<String, measureme::StringId>,
252
253     /// Cache of `Instance` exported under the given `Symbol` name.
254     /// `None` means no `Instance` exported under the given name is found.
255     pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
256
257     /// Whether to raise a panic in the context of the evaluated process when unsupported
258     /// functionality is encountered. If `false`, an error is propagated in the Miri application context
259     /// instead (default behavior)
260     pub(crate) panic_on_unsupported: bool,
261
262     /// Equivalent setting as RUST_BACKTRACE on encountering an error.
263     pub(crate) backtrace_style: BacktraceStyle,
264
265     /// Crates which are considered local for the purposes of error reporting.
266     pub(crate) local_crates: Vec<CrateNum>,
267
268     /// Mapping extern static names to their base pointer.
269     extern_statics: FxHashMap<Symbol, Pointer<Tag>>,
270
271     /// The random number generator used for resolving non-determinism.
272     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
273     pub(crate) rng: RefCell<StdRng>,
274
275     /// An allocation ID to report when it is being allocated
276     /// (helps for debugging memory leaks and use after free bugs).
277     tracked_alloc_id: Option<AllocId>,
278
279     /// Controls whether alignment of memory accesses is being checked.
280     pub(crate) check_alignment: AlignmentCheck,
281
282     /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
283     pub(crate) cmpxchg_weak_failure_rate: f64,
284 }
285
286 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
287     pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
288         let local_crates = helpers::get_local_crates(&layout_cx.tcx);
289         let layouts =
290             PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
291         let profiler = config.measureme_out.as_ref().map(|out| {
292             measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
293         });
294         let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
295         let stacked_borrows = if config.stacked_borrows {
296             Some(RefCell::new(stacked_borrows::GlobalStateInner::new(
297                 config.tracked_pointer_tag,
298                 config.tracked_call_id,
299                 config.tag_raw,
300             )))
301         } else {
302             None
303         };
304         let data_race =
305             if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
306         Evaluator {
307             stacked_borrows,
308             data_race,
309             intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config)),
310             // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
311             env_vars: EnvVars::default(),
312             argc: None,
313             argv: None,
314             cmd_line: None,
315             tls: TlsData::default(),
316             isolated_op: config.isolated_op,
317             validate: config.validate,
318             enforce_number_validity: config.check_number_validity,
319             enforce_abi: config.check_abi,
320             file_handler: Default::default(),
321             dir_handler: Default::default(),
322             time_anchor: Instant::now(),
323             layouts,
324             threads: ThreadManager::default(),
325             static_roots: Vec::new(),
326             profiler,
327             string_cache: Default::default(),
328             exported_symbols_cache: FxHashMap::default(),
329             panic_on_unsupported: config.panic_on_unsupported,
330             backtrace_style: config.backtrace_style,
331             local_crates,
332             extern_statics: FxHashMap::default(),
333             rng: RefCell::new(rng),
334             tracked_alloc_id: config.tracked_alloc_id,
335             check_alignment: config.check_alignment,
336             cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
337         }
338     }
339
340     pub(crate) fn late_init(
341         this: &mut MiriEvalContext<'mir, 'tcx>,
342         config: &MiriConfig,
343     ) -> InterpResult<'tcx> {
344         EnvVars::init(this, config)?;
345         Evaluator::init_extern_statics(this)?;
346         Ok(())
347     }
348
349     fn add_extern_static(
350         this: &mut MiriEvalContext<'mir, 'tcx>,
351         name: &str,
352         ptr: Pointer<Option<Tag>>,
353     ) {
354         let ptr = ptr.into_pointer_or_addr().unwrap();
355         this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
356     }
357
358     /// Sets up the "extern statics" for this machine.
359     fn init_extern_statics(this: &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx> {
360         match this.tcx.sess.target.os.as_ref() {
361             "linux" => {
362                 // "environ"
363                 Self::add_extern_static(
364                     this,
365                     "environ",
366                     this.machine.env_vars.environ.unwrap().ptr,
367                 );
368                 // A couple zero-initialized pointer-sized extern statics.
369                 // Most of them are for weak symbols, which we all set to null (indicating that the
370                 // symbol is not supported, and triggering fallback code which ends up calling a
371                 // syscall that we do support).
372                 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx"] {
373                     let layout = this.machine.layouts.usize;
374                     let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
375                     this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
376                     Self::add_extern_static(this, name, place.ptr);
377                 }
378             }
379             "windows" => {
380                 // "_tls_used"
381                 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
382                 let layout = this.machine.layouts.u8;
383                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
384                 this.write_scalar(Scalar::from_u8(0), &place.into())?;
385                 Self::add_extern_static(this, "_tls_used", place.ptr);
386             }
387             _ => {} // No "extern statics" supported on this target
388         }
389         Ok(())
390     }
391
392     pub(crate) fn communicate(&self) -> bool {
393         self.isolated_op == IsolatedOp::Allow
394     }
395
396     /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
397     pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
398         let def_id = frame.instance.def_id();
399         def_id.is_local() || self.local_crates.contains(&def_id.krate)
400     }
401 }
402
403 /// A rustc InterpCx for Miri.
404 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
405
406 /// A little trait that's useful to be inherited by extension traits.
407 pub trait MiriEvalContextExt<'mir, 'tcx> {
408     fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
409     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
410 }
411 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
412     #[inline(always)]
413     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
414         self
415     }
416     #[inline(always)]
417     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
418         self
419     }
420 }
421
422 /// Machine hook implementations.
423 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
424     type MemoryKind = MiriMemoryKind;
425
426     type FrameExtra = FrameData<'tcx>;
427     type AllocExtra = AllocExtra;
428     type PointerTag = Tag;
429     type ExtraFnVal = Dlsym;
430
431     type MemoryMap =
432         MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
433
434     const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
435
436     const PANIC_ON_ALLOC_FAIL: bool = false;
437
438     #[inline(always)]
439     fn enforce_alignment(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
440         ecx.machine.check_alignment != AlignmentCheck::None
441     }
442
443     #[inline(always)]
444     fn force_int_for_alignment_check(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
445         ecx.machine.check_alignment == AlignmentCheck::Int
446     }
447
448     #[inline(always)]
449     fn enforce_validity(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
450         ecx.machine.validate
451     }
452
453     #[inline(always)]
454     fn enforce_number_validity(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
455         ecx.machine.enforce_number_validity
456     }
457
458     #[inline(always)]
459     fn enforce_abi(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
460         ecx.machine.enforce_abi
461     }
462
463     #[inline(always)]
464     fn find_mir_or_eval_fn(
465         ecx: &mut MiriEvalContext<'mir, 'tcx>,
466         instance: ty::Instance<'tcx>,
467         abi: Abi,
468         args: &[OpTy<'tcx, Tag>],
469         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
470         unwind: StackPopUnwind,
471     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
472         ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
473     }
474
475     #[inline(always)]
476     fn call_extra_fn(
477         ecx: &mut MiriEvalContext<'mir, 'tcx>,
478         fn_val: Dlsym,
479         abi: Abi,
480         args: &[OpTy<'tcx, Tag>],
481         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
482         _unwind: StackPopUnwind,
483     ) -> InterpResult<'tcx> {
484         ecx.call_dlsym(fn_val, abi, args, ret)
485     }
486
487     #[inline(always)]
488     fn call_intrinsic(
489         ecx: &mut MiriEvalContext<'mir, 'tcx>,
490         instance: ty::Instance<'tcx>,
491         args: &[OpTy<'tcx, Tag>],
492         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
493         unwind: StackPopUnwind,
494     ) -> InterpResult<'tcx> {
495         ecx.call_intrinsic(instance, args, ret, unwind)
496     }
497
498     #[inline(always)]
499     fn assert_panic(
500         ecx: &mut MiriEvalContext<'mir, 'tcx>,
501         msg: &mir::AssertMessage<'tcx>,
502         unwind: Option<mir::BasicBlock>,
503     ) -> InterpResult<'tcx> {
504         ecx.assert_panic(msg, unwind)
505     }
506
507     #[inline(always)]
508     fn abort(_ecx: &mut MiriEvalContext<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
509         throw_machine_stop!(TerminationInfo::Abort(msg))
510     }
511
512     #[inline(always)]
513     fn binary_ptr_op(
514         ecx: &MiriEvalContext<'mir, 'tcx>,
515         bin_op: mir::BinOp,
516         left: &ImmTy<'tcx, Tag>,
517         right: &ImmTy<'tcx, Tag>,
518     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
519         ecx.binary_ptr_op(bin_op, left, right)
520     }
521
522     fn thread_local_static_base_pointer(
523         ecx: &mut MiriEvalContext<'mir, 'tcx>,
524         def_id: DefId,
525     ) -> InterpResult<'tcx, Pointer<Tag>> {
526         ecx.get_or_create_thread_local_alloc(def_id)
527     }
528
529     fn extern_static_base_pointer(
530         ecx: &MiriEvalContext<'mir, 'tcx>,
531         def_id: DefId,
532     ) -> InterpResult<'tcx, Pointer<Tag>> {
533         let attrs = ecx.tcx.get_attrs(def_id);
534         let link_name = match ecx.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
535             Some(name) => name,
536             None => ecx.tcx.item_name(def_id),
537         };
538         if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
539             Ok(ptr)
540         } else {
541             throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
542         }
543     }
544
545     fn init_allocation_extra<'b>(
546         ecx: &MiriEvalContext<'mir, 'tcx>,
547         id: AllocId,
548         alloc: Cow<'b, Allocation>,
549         kind: Option<MemoryKind<Self::MemoryKind>>,
550     ) -> Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>> {
551         if Some(id) == ecx.machine.tracked_alloc_id {
552             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
553         }
554
555         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
556         let alloc = alloc.into_owned();
557         let stacks = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
558             Some(Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind))
559         } else {
560             None
561         };
562         let race_alloc = if let Some(data_race) = &ecx.machine.data_race {
563             Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size(), kind))
564         } else {
565             None
566         };
567         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.convert_tag_add_extra(
568             &ecx.tcx,
569             AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
570             |ptr| Evaluator::tag_alloc_base_pointer(ecx, ptr),
571         );
572         Cow::Owned(alloc)
573     }
574
575     fn tag_alloc_base_pointer(
576         ecx: &MiriEvalContext<'mir, 'tcx>,
577         ptr: Pointer<AllocId>,
578     ) -> Pointer<Tag> {
579         let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr);
580         let sb_tag = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
581             stacked_borrows.borrow_mut().base_tag(ptr.provenance)
582         } else {
583             SbTag::Untagged
584         };
585         Pointer::new(Tag { alloc_id: ptr.provenance, sb: sb_tag }, Size::from_bytes(absolute_addr))
586     }
587
588     #[inline(always)]
589     fn ptr_from_addr(
590         ecx: &MiriEvalContext<'mir, 'tcx>,
591         addr: u64,
592     ) -> Pointer<Option<Self::PointerTag>> {
593         intptrcast::GlobalStateInner::ptr_from_addr(addr, ecx)
594     }
595
596     /// Convert a pointer with provenance into an allocation-offset pair,
597     /// or a `None` with an absolute address if that conversion is not possible.
598     fn ptr_get_alloc(
599         ecx: &MiriEvalContext<'mir, 'tcx>,
600         ptr: Pointer<Self::PointerTag>,
601     ) -> (AllocId, Size) {
602         let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
603         (ptr.provenance.alloc_id, rel)
604     }
605
606     #[inline(always)]
607     fn memory_read(
608         _tcx: TyCtxt<'tcx>,
609         machine: &Self,
610         alloc_extra: &AllocExtra,
611         tag: Tag,
612         range: AllocRange,
613     ) -> InterpResult<'tcx> {
614         if let Some(data_race) = &alloc_extra.data_race {
615             data_race.read(tag.alloc_id, range, machine.data_race.as_ref().unwrap())?;
616         }
617         if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
618             stacked_borrows.memory_read(
619                 tag.alloc_id,
620                 tag.sb,
621                 range,
622                 machine.stacked_borrows.as_ref().unwrap(),
623             )
624         } else {
625             Ok(())
626         }
627     }
628
629     #[inline(always)]
630     fn memory_written(
631         _tcx: TyCtxt<'tcx>,
632         machine: &mut Self,
633         alloc_extra: &mut AllocExtra,
634         tag: Tag,
635         range: AllocRange,
636     ) -> InterpResult<'tcx> {
637         if let Some(data_race) = &mut alloc_extra.data_race {
638             data_race.write(tag.alloc_id, range, machine.data_race.as_mut().unwrap())?;
639         }
640         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
641             stacked_borrows.memory_written(
642                 tag.alloc_id,
643                 tag.sb,
644                 range,
645                 machine.stacked_borrows.as_mut().unwrap(),
646             )
647         } else {
648             Ok(())
649         }
650     }
651
652     #[inline(always)]
653     fn memory_deallocated(
654         _tcx: TyCtxt<'tcx>,
655         machine: &mut Self,
656         alloc_extra: &mut AllocExtra,
657         tag: Tag,
658         range: AllocRange,
659     ) -> InterpResult<'tcx> {
660         if Some(tag.alloc_id) == machine.tracked_alloc_id {
661             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(tag.alloc_id));
662         }
663         if let Some(data_race) = &mut alloc_extra.data_race {
664             data_race.deallocate(tag.alloc_id, range, machine.data_race.as_mut().unwrap())?;
665         }
666         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
667             stacked_borrows.memory_deallocated(
668                 tag.alloc_id,
669                 tag.sb,
670                 range,
671                 machine.stacked_borrows.as_mut().unwrap(),
672             )
673         } else {
674             Ok(())
675         }
676     }
677
678     #[inline(always)]
679     fn retag(
680         ecx: &mut InterpCx<'mir, 'tcx, Self>,
681         kind: mir::RetagKind,
682         place: &PlaceTy<'tcx, Tag>,
683     ) -> InterpResult<'tcx> {
684         if ecx.machine.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
685     }
686
687     #[inline(always)]
688     fn init_frame_extra(
689         ecx: &mut InterpCx<'mir, 'tcx, Self>,
690         frame: Frame<'mir, 'tcx, Tag>,
691     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
692         // Start recording our event before doing anything else
693         let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
694             let fn_name = frame.instance.to_string();
695             let entry = ecx.machine.string_cache.entry(fn_name.clone());
696             let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
697
698             Some(profiler.start_recording_interval_event_detached(
699                 *name,
700                 measureme::EventId::from_label(*name),
701                 ecx.get_active_thread().to_u32(),
702             ))
703         } else {
704             None
705         };
706
707         let stacked_borrows = ecx.machine.stacked_borrows.as_ref();
708         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
709             stacked_borrows.borrow_mut().new_call()
710         });
711
712         let extra = FrameData { call_id, catch_unwind: None, timing };
713         Ok(frame.with_extra(extra))
714     }
715
716     fn stack<'a>(
717         ecx: &'a InterpCx<'mir, 'tcx, Self>,
718     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
719         ecx.active_thread_stack()
720     }
721
722     fn stack_mut<'a>(
723         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
724     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
725         ecx.active_thread_stack_mut()
726     }
727
728     #[inline(always)]
729     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
730         if ecx.machine.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
731     }
732
733     #[inline(always)]
734     fn after_stack_pop(
735         ecx: &mut InterpCx<'mir, 'tcx, Self>,
736         mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
737         unwinding: bool,
738     ) -> InterpResult<'tcx, StackPopJump> {
739         let timing = frame.extra.timing.take();
740         let res = ecx.handle_stack_pop(frame.extra, unwinding);
741         if let Some(profiler) = ecx.machine.profiler.as_ref() {
742             profiler.finish_recording_interval_event(timing.unwrap());
743         }
744         res
745     }
746 }