1//! This module contains everything needed to instantiate an interpreter.
2//! This separation exists to ensure that no fancy miri features like
3//! interpreting common C functions leak into CTFE.
45use std::borrow::{Borrow, Cow};
6use std::fmt::Debug;
7use std::hash::Hash;
89use rustc_abi::{Align, Size};
10use rustc_apfloat::{Float, FloatConvert};
11use rustc_middle::query::TyCtxtAt;
12use rustc_middle::ty::layout::TyAndLayout;
13use rustc_middle::ty::{AtomicOrdering, Ty};
14use rustc_middle::{mir, ty};
15use rustc_span::def_id::DefId;
16use rustc_target::callconv::FnAbi;
1718use super::{
19AllocBytes, AllocId, AllocKind, AllocRange, Allocation, AtomicRmwOp, CTFE_ALLOC_SALT,
20ConstAllocation, CtfeProvenance, EnteredTraceSpan, FnArg, Frame, ImmTy, InterpCx, InterpResult,
21MPlaceTy, MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, Scalar,
22interp_ok, throw_unsup,
23};
2425/// Data returned by [`Machine::after_stack_pop`], and consumed by
26/// [`InterpCx::return_from_current_stack_frame`] to determine what actions should be done when
27/// returning from a stack frame.
28#[derive(#[automatically_derived]
impl ::core::cmp::Eq for ReturnAction {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ReturnAction { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ReturnAction {
#[inline]
fn eq(&self, other: &ReturnAction) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ReturnAction {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ReturnAction::Normal => "Normal",
ReturnAction::NoJump => "NoJump",
ReturnAction::NoCleanup => "NoCleanup",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReturnAction { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ReturnAction { }
#[automatically_derived]
impl ::core::clone::Clone for ReturnAction {
#[inline]
fn clone(&self) -> ReturnAction { *self }
}Clone)]
29pub enum ReturnAction {
30/// Indicates that no special handling should be
31 /// done - we'll either return normally or unwind
32 /// based on the terminator for the function
33 /// we're leaving.
34Normal,
3536/// Indicates that we should *not* jump to the return/unwind address, as the callback already
37 /// took care of everything.
38NoJump,
3940/// Returned by [`InterpCx::pop_stack_frame_raw`] when no cleanup should be done.
41NoCleanup,
42}
4344/// The currently active retagging mode.
45#[derive(#[automatically_derived]
impl ::core::cmp::Eq for RetagMode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RetagMode { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RetagMode {
#[inline]
fn eq(&self, other: &RetagMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for RetagMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RetagMode::Default => "Default",
RetagMode::TwoPhase => "TwoPhase",
RetagMode::FnEntry => "FnEntry",
RetagMode::Raw => "Raw",
RetagMode::None => "None",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RetagMode { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RetagMode { }
#[automatically_derived]
impl ::core::clone::Clone for RetagMode {
#[inline]
fn clone(&self) -> RetagMode { *self }
}Clone)]
46pub enum RetagMode {
47/// A regular retag.
48Default,
49/// Retag preparing for a two-phase borrow.
50TwoPhase,
51/// The initial retag of arguments when entering a function.
52FnEntry,
53/// Retagging for reference-to-raw-pointer cast.
54Raw,
55/// No retagging.
56None,
57}
5859/// Whether this kind of memory is allowed to leak
60pub trait MayLeak: Copy {
61fn may_leak(self) -> bool;
62}
6364/// The functionality needed by memory to manage its allocations
65pub trait AllocMap<K: Hash + Eq, V> {
66/// Tests if the map contains the given key.
67 /// Deliberately takes `&mut` because that is sufficient, and some implementations
68 /// can be more efficient then (using `RefCell::get_mut`).
69fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool70where
71K: Borrow<Q>;
7273/// Callers should prefer [`AllocMap::contains_key`] when it is possible to call because it may
74 /// be more efficient. This function exists for callers that only have a shared reference
75 /// (which might make it slightly less efficient than `contains_key`, e.g. if
76 /// the data is stored inside a `RefCell`).
77fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool78where
79K: Borrow<Q>;
8081/// Inserts a new entry into the map.
82fn insert(&mut self, k: K, v: V) -> Option<V>;
8384/// Removes an entry from the map.
85fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
86where
87K: Borrow<Q>;
8889/// Returns data based on the keys and values in the map.
90fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
9192/// Returns a reference to entry `k`. If no such entry exists, call
93 /// `vacant` and either forward its error, or add its result to the map
94 /// and return a reference to *that*.
95fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
9697/// Returns a mutable reference to entry `k`. If no such entry exists, call
98 /// `vacant` and either forward its error, or add its result to the map
99 /// and return a reference to *that*.
100fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
101102/// Read-only lookup.
103fn get(&self, k: K) -> Option<&V> {
104self.get_or(k, || Err(())).ok()
105 }
106107/// Mutable lookup.
108fn get_mut(&mut self, k: K) -> Option<&mut V> {
109self.get_mut_or(k, || Err(())).ok()
110 }
111}
112113/// Methods of this trait signifies a point where CTFE evaluation would fail
114/// and some use case dependent behaviour can instead be applied.
115pub trait Machine<'tcx>: Sized {
116/// Additional memory kinds a machine wishes to distinguish from the builtin ones
117type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
118119/// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
120type Provenance: Provenance + Eq + Hash + 'static;
121122/// When getting the AllocId of a pointer, some extra data is also obtained from the provenance
123 /// that is passed to memory access hooks so they can do things with it.
124type ProvenanceExtra: Copy + 'static;
125126/// Machines can define extra (non-instance) things that represent values of function pointers.
127 /// For example, Miri uses this to return a function pointer from `dlsym`
128 /// that can later be called to execute the right thing.
129type ExtraFnVal: Debug + Copy;
130131/// Extra data stored in every call frame.
132type FrameExtra;
133134/// Extra data stored in every allocation.
135type AllocExtra: Debug + Clone + 'tcx;
136137/// Type for the bytes of the allocation.
138type Bytes: AllocBytes + 'static;
139140/// Memory's allocation map
141type MemoryMap: AllocMap<
142AllocId,
143 (
144MemoryKind<Self::MemoryKind>,
145Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>,
146 ),
147 > + Default148 + Clone;
149150/// The memory kind to use for copied global memory (held in `tcx`) --
151 /// or None if such memory should not be mutated and thus any such attempt will cause
152 /// a `ModifiedStatic` error to be raised.
153 /// Statics are copied under two circumstances: When they are mutated, and when
154 /// `adjust_allocation` (see below) returns an owned allocation
155 /// that is added to the memory so that the work is not done twice.
156const GLOBAL_KIND: Option<Self::MemoryKind>;
157158/// Should the machine panic on allocation failures?
159const PANIC_ON_ALLOC_FAIL: bool;
160161/// Determines whether `eval_mir_constant` can never fail because all required consts have
162 /// already been checked before.
163const ALL_CONSTS_ARE_PRECHECKED: bool = true;
164165/// Whether memory accesses should be alignment-checked.
166fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool;
167168/// Gives the machine a chance to detect more misalignment than the built-in checks would catch.
169#[inline(always)]
170fn alignment_check(
171 _ecx: &InterpCx<'tcx, Self>,
172 _alloc_id: AllocId,
173 _alloc_align: Align,
174 _alloc_kind: AllocKind,
175 _offset: Size,
176 _align: Align,
177 ) -> Option<Misalignment> {
178None179 }
180181/// Whether to enforce the validity invariant for a specific layout.
182fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool;
183/// Whether to enforce the validity invariant *recursively*.
184fn enforce_validity_recursively(
185 _ecx: &InterpCx<'tcx, Self>,
186 _layout: TyAndLayout<'tcx>,
187 ) -> bool {
188false
189}
190191/// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
192 /// check for overflow.
193fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool;
194195/// Entry point for obtaining the MIR of anything that should get evaluated.
196 /// So not just functions and shims, but also const/static initializers, anonymous
197 /// constants, ...
198fn load_mir(
199 ecx: &InterpCx<'tcx, Self>,
200 instance: ty::InstanceKind<'tcx>,
201 ) -> &'tcx mir::Body<'tcx> {
202ecx.tcx.instance_mir(instance)
203 }
204205/// Entry point to all function calls.
206 ///
207 /// Returns either the mir to use for the call, or `None` if execution should
208 /// just proceed (which usually means this hook did all the work that the
209 /// called function should usually have done). In the latter case, it is
210 /// this hook's responsibility to advance the instruction pointer!
211 /// (This is to support functions like `__rust_maybe_catch_panic` that neither find a MIR
212 /// nor just jump to `ret`, but instead push their own stack frame.)
213 /// Passing `dest`and `ret` in the same `Option` proved very annoying when only one of them
214 /// was used.
215fn find_mir_or_eval_fn(
216 ecx: &mut InterpCx<'tcx, Self>,
217 instance: ty::Instance<'tcx>,
218 abi: &FnAbi<'tcx, Ty<'tcx>>,
219 args: &[FnArg<'tcx, Self::Provenance>],
220 destination: &PlaceTy<'tcx, Self::Provenance>,
221 target: Option<mir::BasicBlock>,
222 unwind: mir::UnwindAction,
223 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>>;
224225/// Execute `fn_val`. It is the hook's responsibility to advance the instruction
226 /// pointer as appropriate.
227fn call_extra_fn(
228 ecx: &mut InterpCx<'tcx, Self>,
229 fn_val: Self::ExtraFnVal,
230 abi: &FnAbi<'tcx, Ty<'tcx>>,
231 args: &[FnArg<'tcx, Self::Provenance>],
232 destination: &PlaceTy<'tcx, Self::Provenance>,
233 target: Option<mir::BasicBlock>,
234 unwind: mir::UnwindAction,
235 ) -> InterpResult<'tcx>;
236237/// Directly process an intrinsic without pushing a stack frame. It is the hook's
238 /// responsibility to advance the instruction pointer as appropriate.
239 ///
240 /// Returns `None` if the intrinsic was fully handled.
241 /// Otherwise, returns an `Instance` of the function that implements the intrinsic.
242fn call_intrinsic(
243 ecx: &mut InterpCx<'tcx, Self>,
244 instance: ty::Instance<'tcx>,
245 args: &[OpTy<'tcx, Self::Provenance>],
246 destination: &PlaceTy<'tcx, Self::Provenance>,
247 target: Option<mir::BasicBlock>,
248 unwind: mir::UnwindAction,
249 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>>;
250251/// Directly process an LLVM intrinsic without pushing a stack frame. It is the hook's
252 /// responsibility to advance the instruction pointer as appropriate.
253fn call_llvm_intrinsic(
254 ecx: &mut InterpCx<'tcx, Self>,
255 instance: ty::Instance<'tcx>,
256 args: &[OpTy<'tcx, Self::Provenance>],
257 destination: &PlaceTy<'tcx, Self::Provenance>,
258 target: Option<mir::BasicBlock>,
259 ) -> InterpResult<'tcx>;
260261/// Check whether the given function may be executed on the current machine, in terms of the
262 /// target features is requires.
263fn check_fn_target_features(
264 _ecx: &InterpCx<'tcx, Self>,
265 _instance: ty::Instance<'tcx>,
266 ) -> InterpResult<'tcx>;
267268/// Called to evaluate `Assert` MIR terminators that trigger a panic.
269fn assert_panic(
270 ecx: &mut InterpCx<'tcx, Self>,
271 msg: &mir::AssertMessage<'tcx>,
272 unwind: mir::UnwindAction,
273 ) -> InterpResult<'tcx>;
274275/// Called to trigger a non-unwinding panic.
276fn panic_nounwind(_ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx>;
277278/// Called when unwinding reached a state where execution should be terminated.
279fn unwind_terminate(
280 ecx: &mut InterpCx<'tcx, Self>,
281 reason: mir::UnwindTerminateReason,
282 ) -> InterpResult<'tcx>;
283284/// Called for all binary operations where the LHS has pointer type.
285fn binary_ptr_op(
286 ecx: &InterpCx<'tcx, Self>,
287 bin_op: mir::BinOp,
288 left: &ImmTy<'tcx, Self::Provenance>,
289 right: &ImmTy<'tcx, Self::Provenance>,
290 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>>;
291292/// Generate the NaN returned by a float operation, given the list of inputs.
293 /// (This is all inputs, not just NaN inputs!)
294fn generate_nan<F1: Float + FloatConvert<F2>, F2: Float>(
295 _ecx: &InterpCx<'tcx, Self>,
296 _inputs: &[F1],
297 ) -> F2 {
298// By default we always return the preferred NaN.
299F2::NAN300 }
301302/// Apply non-determinism to float operations that do not return a precise result.
303fn apply_float_nondet(
304 _ecx: &mut InterpCx<'tcx, Self>,
305 val: ImmTy<'tcx, Self::Provenance>,
306 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
307interp_ok(val)
308 }
309310/// Determines the result of `min`/`max` on floats when the arguments are equal.
311fn equal_float_min_max<F: Float>(_ecx: &InterpCx<'tcx, Self>, a: F, _b: F) -> F {
312// By default, we pick the left argument.
313a314 }
315316/// Determines whether the `fmuladd` intrinsics fuse the multiply-add or use separate operations.
317fn float_fuse_mul_add(ecx: &InterpCx<'tcx, Self>) -> bool;
318319fn atomic_load(
320 ecx: &InterpCx<'tcx, Self>,
321 place: &MPlaceTy<'tcx, Self::Provenance>,
322 ordering: AtomicOrdering,
323 ) -> InterpResult<'tcx, Scalar<Self::Provenance>>;
324325fn atomic_store(
326 ecx: &mut InterpCx<'tcx, Self>,
327 place: &MPlaceTy<'tcx, Self::Provenance>,
328 val: &ImmTy<'tcx, Self::Provenance>,
329 ordering: AtomicOrdering,
330 ) -> InterpResult<'tcx>;
331332/// Returns the old value.
333fn atomic_rmw(
334 ecx: &mut InterpCx<'tcx, Self>,
335 place: &MPlaceTy<'tcx, Self::Provenance>,
336 op: AtomicRmwOp,
337 operand: &ImmTy<'tcx, Self::Provenance>,
338 ordering: AtomicOrdering,
339 ) -> InterpResult<'tcx, Scalar<Self::Provenance>>;
340341/// Returns a pair of the old value and a boolean indicating whether the update happened.
342fn atomic_compare_exchange(
343 ecx: &mut InterpCx<'tcx, Self>,
344 place: &MPlaceTy<'tcx, Self::Provenance>,
345 expected_old: &ImmTy<'tcx, Self::Provenance>,
346 new: &ImmTy<'tcx, Self::Provenance>,
347 can_fail_spuriously: bool,
348 success_ordering: AtomicOrdering,
349 failure_ordering: AtomicOrdering,
350 ) -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool)>;
351352fn atomic_fence(
353 ecx: &InterpCx<'tcx, Self>,
354 ordering: AtomicOrdering,
355 singlethread: bool,
356 ) -> InterpResult<'tcx>;
357358/// Called before a basic block terminator is executed.
359#[inline]
360fn before_terminator(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
361interp_ok(())
362 }
363364/// Determines the result of a `Operand::RuntimeChecks` invocation.
365fn runtime_checks(
366 _ecx: &InterpCx<'tcx, Self>,
367 r: mir::RuntimeChecks,
368 ) -> InterpResult<'tcx, bool>;
369370/// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
371 /// You can use this to detect long or endlessly running programs.
372#[inline]
373fn increment_const_eval_counter(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
374interp_ok(())
375 }
376377/// Called before a global allocation is accessed.
378 /// `def_id` is `Some` if this is the "lazy" allocation of a static.
379#[inline]
380fn before_access_global(
381 _tcx: TyCtxtAt<'tcx>,
382 _machine: &Self,
383 _alloc_id: AllocId,
384 _allocation: ConstAllocation<'tcx>,
385 _static_def_id: Option<DefId>,
386 _is_write: bool,
387 ) -> InterpResult<'tcx> {
388interp_ok(())
389 }
390391/// Return the `AllocId` for the given thread-local static in the current thread.
392fn thread_local_static_pointer(
393 _ecx: &mut InterpCx<'tcx, Self>,
394 def_id: DefId,
395 ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
396do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ThreadLocalStatic(def_id))throw_unsup!(ThreadLocalStatic(def_id))397 }
398399/// Return the `AllocId` for the given `extern static`.
400fn extern_static_pointer(
401 ecx: &InterpCx<'tcx, Self>,
402 def_id: DefId,
403 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
404405/// "Int-to-pointer cast"
406fn ptr_from_addr_cast(
407 ecx: &InterpCx<'tcx, Self>,
408 addr: u64,
409 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
410411/// Marks a pointer as exposed, allowing its provenance
412 /// to be recovered. "Pointer-to-int cast"
413fn expose_provenance(
414 ecx: &InterpCx<'tcx, Self>,
415 provenance: Self::Provenance,
416 ) -> InterpResult<'tcx>;
417418/// Convert a pointer with provenance into an allocation-offset pair and extra provenance info.
419 /// `size` says how many bytes of memory are expected at that pointer. The *sign* of `size` can
420 /// be used to disambiguate situations where a wildcard pointer sits right in between two
421 /// allocations.
422 ///
423 /// If `ptr.provenance.get_alloc_id()` is `Some(p)`, the returned `AllocId` must be `p`.
424 /// The resulting `AllocId` will just be used for that one step and the forgotten again
425 /// (i.e., we'll never turn the data returned here back into a `Pointer` that might be
426 /// stored in machine state).
427 ///
428 /// When this fails, that means the pointer does not point to a live allocation.
429fn ptr_get_alloc(
430 ecx: &InterpCx<'tcx, Self>,
431 ptr: Pointer<Self::Provenance>,
432 size: i64,
433 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
434435/// Return a "root" pointer for the given allocation: the one that is used for direct
436 /// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
437 ///
438 /// Not called on `extern` or thread-local statics (those use the methods above).
439 ///
440 /// `kind` is the kind of the allocation the pointer points to; it can be `None` when
441 /// it's a global and `GLOBAL_KIND` is `None`.
442fn adjust_alloc_root_pointer(
443 ecx: &InterpCx<'tcx, Self>,
444 ptr: Pointer,
445 kind: Option<MemoryKind<Self::MemoryKind>>,
446 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
447448/// Called to adjust global allocations to the Provenance and AllocExtra of this machine.
449 ///
450 /// If `alloc` contains pointers, then they are all pointing to globals.
451 ///
452 /// This should avoid copying if no work has to be done! If this returns an owned
453 /// allocation (because a copy had to be done to adjust things), machine memory will
454 /// cache the result. (This relies on `AllocMap::get_or` being able to add the
455 /// owned allocation to the map even when the map is shared.)
456fn adjust_global_allocation<'b>(
457 ecx: &InterpCx<'tcx, Self>,
458 id: AllocId,
459 alloc: &'b Allocation,
460 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>;
461462/// Initialize the extra state of an allocation local to this machine.
463 ///
464 /// This is guaranteed to be called exactly once on all allocations local to this machine.
465 /// It will not be called automatically for global allocations; `adjust_global_allocation`
466 /// has to do that itself if that is desired.
467fn init_local_allocation(
468 ecx: &InterpCx<'tcx, Self>,
469 id: AllocId,
470 kind: MemoryKind<Self::MemoryKind>,
471 size: Size,
472 align: Align,
473 ) -> InterpResult<'tcx, Self::AllocExtra>;
474475/// Hook for performing extra checks on a memory read access.
476 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
477 /// `range`.
478 ///
479 /// This will *not* be called during validation!
480 ///
481 /// Takes read-only access to the allocation so we can keep all the memory read
482 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
483 /// need to mutate.
484 ///
485 /// This is not invoked for ZST accesses, as no read actually happens.
486#[inline(always)]
487fn before_memory_read(
488 _tcx: TyCtxtAt<'tcx>,
489 _machine: &Self,
490 _alloc_extra: &Self::AllocExtra,
491 _ptr: Pointer<Option<Self::Provenance>>,
492 _prov: (AllocId, Self::ProvenanceExtra),
493 _range: AllocRange,
494 ) -> InterpResult<'tcx> {
495interp_ok(())
496 }
497498/// Hook for performing extra checks on any memory read access,
499 /// that involves an allocation, even ZST reads.
500 ///
501 /// This will *not* be called during validation!
502 ///
503 /// Used to prevent statics from self-initializing by reading from their own memory
504 /// as it is being initialized.
505fn before_alloc_access(
506 _tcx: TyCtxtAt<'tcx>,
507 _machine: &Self,
508 _alloc_id: AllocId,
509 ) -> InterpResult<'tcx> {
510interp_ok(())
511 }
512513/// Hook for performing extra checks on a memory write access.
514 /// This is not invoked for ZST accesses, as no write actually happens.
515 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
516 /// `range`.
517#[inline(always)]
518fn before_memory_write(
519 _tcx: TyCtxtAt<'tcx>,
520 _machine: &mut Self,
521 _alloc_extra: &mut Self::AllocExtra,
522 _ptr: Pointer<Option<Self::Provenance>>,
523 _prov: (AllocId, Self::ProvenanceExtra),
524 _range: AllocRange,
525 ) -> InterpResult<'tcx> {
526interp_ok(())
527 }
528529/// Hook for performing extra operations on a memory deallocation.
530 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
531 /// the allocation.
532#[inline(always)]
533fn before_memory_deallocation(
534 _tcx: TyCtxtAt<'tcx>,
535 _machine: &mut Self,
536 _alloc_extra: &mut Self::AllocExtra,
537 _ptr: Pointer<Option<Self::Provenance>>,
538 _prov: (AllocId, Self::ProvenanceExtra),
539 _size: Size,
540 _align: Align,
541 _kind: MemoryKind<Self::MemoryKind>,
542 ) -> InterpResult<'tcx> {
543interp_ok(())
544 }
545546/// Executes a retagging operation for a single pointer.
547 /// Returns the possibly adjusted pointer. Return `None` if the pointer
548 /// was left unchanged.
549 ///
550 /// `ty` is the full type of the pointer. This is not the same as `val.layout.ty` for boxes
551 /// where `val` is just the inner raw pointer, but `ty` is the entire `Box` type.
552#[inline]
553fn retag_ptr_value(
554 _ecx: &mut InterpCx<'tcx, Self>,
555 _val: &ImmTy<'tcx, Self::Provenance>,
556 _ty: Ty<'tcx>,
557 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, Self::Provenance>>> {
558interp_ok(None)
559 }
560561/// Invoke `f` in a state where calls to `retag_ptr_value` will use the given retag mode.
562#[inline(always)]
563fn with_retag_mode<T>(
564 ecx: &mut InterpCx<'tcx, Self>,
565 _mode: RetagMode,
566 f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
567 ) -> InterpResult<'tcx, T> {
568f(ecx)
569 }
570571/// Called on places used for in-place function argument and return value handling.
572 ///
573 /// These places need to be protected to make sure the program cannot tell whether the
574 /// argument/return value was actually copied or passed in-place..
575fn protect_in_place_function_argument(
576 ecx: &mut InterpCx<'tcx, Self>,
577 mplace: &MPlaceTy<'tcx, Self::Provenance>,
578 ) -> InterpResult<'tcx> {
579// Without an aliasing model, all we can do is put `Uninit` into the place.
580 // Conveniently this also ensures that the place actually points to suitable memory.
581ecx.write_uninit(mplace)
582 }
583584/// Called immediately before a new stack frame gets pushed.
585fn init_frame(
586 ecx: &mut InterpCx<'tcx, Self>,
587 frame: Frame<'tcx, Self::Provenance>,
588 ) -> InterpResult<'tcx, Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
589590/// Borrow the current thread's stack.
591fn stack<'a>(
592 ecx: &'a InterpCx<'tcx, Self>,
593 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>];
594595/// Mutably borrow the current thread's stack.
596fn stack_mut<'a>(
597 ecx: &'a mut InterpCx<'tcx, Self>,
598 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
599600/// Called immediately after a stack frame got pushed and its locals got initialized.
601fn after_stack_push(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
602interp_ok(())
603 }
604605/// Called just before the frame is removed from the stack (followed by return value copy and
606 /// local cleanup).
607fn before_stack_pop(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
608interp_ok(())
609 }
610611/// Called immediately after a stack frame got popped, but before jumping back to the caller.
612 /// The `locals` have already been destroyed!
613#[inline(always)]
614fn after_stack_pop(
615 _ecx: &mut InterpCx<'tcx, Self>,
616 _frame: Frame<'tcx, Self::Provenance, Self::FrameExtra>,
617 unwinding: bool,
618 ) -> InterpResult<'tcx, ReturnAction> {
619// By default, we do not support unwinding from panics
620if !!unwinding { ::core::panicking::panic("assertion failed: !unwinding") };assert!(!unwinding);
621interp_ok(ReturnAction::Normal)
622 }
623624/// Called immediately after an "immediate" local variable is read
625 /// (i.e., this is called for reads that do not end up accessing addressable memory).
626#[inline(always)]
627fn after_local_read(_ecx: &InterpCx<'tcx, Self>, _local: mir::Local) -> InterpResult<'tcx> {
628interp_ok(())
629 }
630631/// Called immediately after an "immediate" local variable is assigned a new value
632 /// (i.e., this is called for writes that do not end up in memory).
633 /// `storage_live` indicates whether this is the initial write upon `StorageLive`.
634#[inline(always)]
635fn after_local_write(
636 _ecx: &mut InterpCx<'tcx, Self>,
637 _local: mir::Local,
638 _storage_live: bool,
639 ) -> InterpResult<'tcx> {
640interp_ok(())
641 }
642643/// Called immediately after actual memory was allocated for a local
644 /// but before the local's stack frame is updated to point to that memory.
645#[inline(always)]
646fn after_local_moved_to_memory(
647 _ecx: &mut InterpCx<'tcx, Self>,
648 _local: mir::Local,
649 _mplace: &MPlaceTy<'tcx, Self::Provenance>,
650 ) -> InterpResult<'tcx> {
651interp_ok(())
652 }
653654/// Returns the salt to be used for a deduplicated global alloation.
655 /// If the allocation is for a function, the instance is provided as well
656 /// (this lets Miri ensure unique addresses for some functions).
657fn get_global_alloc_salt(
658 ecx: &InterpCx<'tcx, Self>,
659 instance: Option<ty::Instance<'tcx>>,
660 ) -> usize;
661662fn cached_union_data_range<'e>(
663 _ecx: &'e mut InterpCx<'tcx, Self>,
664 _ty: Ty<'tcx>,
665 compute_range: impl FnOnce() -> RangeSet,
666 ) -> Cow<'e, RangeSet> {
667// Default to no caching.
668Cow::Owned(compute_range())
669 }
670671/// Compute the value passed to the constructors of the `AllocBytes` type for
672 /// abstract machine allocations.
673fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams;
674675/// Allows enabling/disabling tracing calls from within `rustc_const_eval` at compile time, by
676 /// delegating the entering of [tracing::Span]s to implementors of the [Machine] trait. The
677 /// default implementation corresponds to tracing being disabled, meaning the tracing calls will
678 /// supposedly be optimized out completely. To enable tracing, override this trait method and
679 /// return `span.entered()`. Also see [crate::enter_trace_span].
680#[must_use]
681 #[inline(always)]
682fn enter_trace_span(_span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan {
683 ()
684 }
685}
686687/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
688/// (CTFE and ConstProp) use the same instance. Here, we share that code.
689pub macro compile_time_machine(<$tcx: lifetime>) {
690type Provenance = CtfeProvenance;
691type ProvenanceExtra = bool; // the "immutable" flag
692693type ExtraFnVal = !;
694695type MemoryKind = $crate::const_eval::MemoryKind;
696type MemoryMap =
697 rustc_data_structures::fx::FxIndexMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
698const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
699700type AllocExtra = ();
701type FrameExtra = ();
702type Bytes = Box<[u8]>;
703704#[inline(always)]
705fn ignore_optional_overflow_checks(_ecx: &InterpCx<$tcx, Self>) -> bool {
706false
707}
708709#[inline(always)]
710fn unwind_terminate(
711 _ecx: &mut InterpCx<$tcx, Self>,
712 _reason: mir::UnwindTerminateReason,
713 ) -> InterpResult<$tcx> {
714unreachable!("unwinding cannot happen during compile-time evaluation")
715 }
716717#[inline(always)]
718fn check_fn_target_features(
719 _ecx: &InterpCx<$tcx, Self>,
720 _instance: ty::Instance<$tcx>,
721 ) -> InterpResult<$tcx> {
722// For now we don't do any checking here. We can't use `tcx.sess` because that can differ
723 // between crates, and we need to ensure that const-eval always behaves the same.
724interp_ok(())
725 }
726727#[inline(always)]
728fn call_extra_fn(
729 _ecx: &mut InterpCx<$tcx, Self>,
730 fn_val: !,
731 _abi: &FnAbi<$tcx, Ty<$tcx>>,
732 _args: &[FnArg<$tcx>],
733 _destination: &PlaceTy<$tcx, Self::Provenance>,
734 _target: Option<mir::BasicBlock>,
735 _unwind: mir::UnwindAction,
736 ) -> InterpResult<$tcx> {
737match fn_val {}
738 }
739740#[inline(always)]
741fn float_fuse_mul_add(_ecx: &InterpCx<$tcx, Self>) -> bool {
742true
743}
744745#[inline(always)]
746fn atomic_load(
747 ecx: &InterpCx<$tcx, Self>,
748 place: &MPlaceTy<$tcx, Self::Provenance>,
749 _ordering: AtomicOrdering,
750 ) -> InterpResult<$tcx, Scalar<Self::Provenance>> {
751// Compile-time machines are single-threaded so this is like a regular load.
752ecx.read_scalar(place)
753 }
754755#[inline(always)]
756fn atomic_store(
757 ecx: &mut InterpCx<$tcx, Self>,
758 place: &MPlaceTy<$tcx, Self::Provenance>,
759 val: &ImmTy<$tcx, Self::Provenance>,
760 _ordering: AtomicOrdering,
761 ) -> InterpResult<$tcx> {
762// Compile-time machines are single-threaded so this is like a regular store.
763ecx.write_scalar(val.to_scalar(), place)
764 }
765766fn atomic_rmw(
767 ecx: &mut InterpCx<$tcx, Self>,
768 place: &MPlaceTy<$tcx, Self::Provenance>,
769 op: AtomicRmwOp,
770 operand: &ImmTy<$tcx, Self::Provenance>,
771 _ordering: AtomicOrdering,
772 ) -> InterpResult<$tcx, Scalar<Self::Provenance>> {
773// Compile-time machines are single-threaded so we ignore the ordering.
774let old_val = ecx.read_immediate(place)?;
775let new_val = ecx.atomic_rmw_op(op, &old_val, operand)?;
776 ecx.write_immediate(*new_val, place)?;
777 interp_ok(old_val.to_scalar())
778 }
779780fn atomic_compare_exchange(
781 ecx: &mut InterpCx<$tcx, Self>,
782 place: &MPlaceTy<$tcx, Self::Provenance>,
783 expected_old: &ImmTy<$tcx, Self::Provenance>,
784 new: &ImmTy<$tcx, Self::Provenance>,
785 _can_fail_spuriously: bool,
786 _success_ordering: AtomicOrdering,
787 _failure_ordering: AtomicOrdering,
788 ) -> InterpResult<$tcx, (Scalar<Self::Provenance>, bool)> {
789// Compile-time machines are single-threaded so we ignore the ordering.
790 // They are also deterministic so we do not fail spuriously.
791let actual_old = ecx.read_immediate(place)?;
792let eq = ecx.binary_op(mir::BinOp::Eq, &actual_old, expected_old)?.to_scalar().to_bool()?;
793if eq {
794 ecx.write_immediate(**new, place)?;
795 }
796 interp_ok((actual_old.to_scalar(), eq))
797 }
798799#[inline(always)]
800fn atomic_fence(
801 _ecx: &InterpCx<$tcx, Self>,
802 _ordering: AtomicOrdering,
803 _singlethread: bool,
804 ) -> InterpResult<$tcx> {
805// Compile-time machines are single-threaded so this is a NOP.
806interp_ok(())
807 }
808809#[inline(always)]
810fn adjust_global_allocation<'b>(
811 _ecx: &InterpCx<$tcx, Self>,
812 _id: AllocId,
813 alloc: &'b Allocation,
814 ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
815// Overwrite default implementation: no need to adjust anything.
816interp_ok(Cow::Borrowed(alloc))
817 }
818819fn init_local_allocation(
820 _ecx: &InterpCx<$tcx, Self>,
821 _id: AllocId,
822 _kind: MemoryKind<Self::MemoryKind>,
823 _size: Size,
824 _align: Align,
825 ) -> InterpResult<$tcx, Self::AllocExtra> {
826 interp_ok(())
827 }
828829fn extern_static_pointer(
830 ecx: &InterpCx<$tcx, Self>,
831 def_id: DefId,
832 ) -> InterpResult<$tcx, Pointer> {
833// Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
834interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(), Size::ZERO))
835 }
836837#[inline(always)]
838fn adjust_alloc_root_pointer(
839 _ecx: &InterpCx<$tcx, Self>,
840 ptr: Pointer<CtfeProvenance>,
841 _kind: Option<MemoryKind<Self::MemoryKind>>,
842 ) -> InterpResult<$tcx, Pointer<CtfeProvenance>> {
843 interp_ok(ptr)
844 }
845846#[inline(always)]
847fn ptr_from_addr_cast(
848 _ecx: &InterpCx<$tcx, Self>,
849 addr: u64,
850 ) -> InterpResult<$tcx, Pointer<Option<CtfeProvenance>>> {
851// Allow these casts, but make the pointer not dereferenceable.
852 // (I.e., they behave like transmutation.)
853 // This is correct because no pointers can ever be exposed in compile-time evaluation.
854interp_ok(Pointer::without_provenance(addr))
855 }
856857#[inline(always)]
858fn ptr_get_alloc(
859 _ecx: &InterpCx<$tcx, Self>,
860 ptr: Pointer<CtfeProvenance>,
861 _size: i64,
862 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
863let (prov, offset) = ptr.prov_and_relative_offset();
864Some((prov.alloc_id(), offset, prov.immutable()))
865 }
866867#[inline(always)]
868fn get_global_alloc_salt(
869 _ecx: &InterpCx<$tcx, Self>,
870 _instance: Option<ty::Instance<$tcx>>,
871 ) -> usize {
872 CTFE_ALLOC_SALT
873 }
874}