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.
5 use std::borrow::{Borrow, Cow};
9 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10 use rustc_middle::mir;
11 use rustc_middle::ty::{self, Ty, TyCtxt};
12 use rustc_span::def_id::DefId;
13 use rustc_target::abi::{Align, Size};
14 use rustc_target::spec::abi::Abi as CallAbi;
16 use crate::const_eval::CheckAlignment;
19 AllocId, AllocRange, Allocation, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
20 MemoryKind, OpTy, Operand, PlaceTy, Pointer, Provenance, Scalar, StackPopUnwind,
23 /// Data returned by Machine::stack_pop,
24 /// to provide further control over the popping of the stack frame
25 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
26 pub enum StackPopJump {
27 /// Indicates that no special handling should be
28 /// done - we'll either return normally or unwind
29 /// based on the terminator for the function
33 /// Indicates that we should *not* jump to the return/unwind address, as the callback already
34 /// took care of everything.
38 /// Whether this kind of memory is allowed to leak
39 pub trait MayLeak: Copy {
40 fn may_leak(self) -> bool;
43 /// The functionality needed by memory to manage its allocations
44 pub trait AllocMap<K: Hash + Eq, V> {
45 /// Tests if the map contains the given key.
46 /// Deliberately takes `&mut` because that is sufficient, and some implementations
47 /// can be more efficient then (using `RefCell::get_mut`).
48 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
52 /// Inserts a new entry into the map.
53 fn insert(&mut self, k: K, v: V) -> Option<V>;
55 /// Removes an entry from the map.
56 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
60 /// Returns data based on the keys and values in the map.
61 fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
63 /// Returns a reference to entry `k`. If no such entry exists, call
64 /// `vacant` and either forward its error, or add its result to the map
65 /// and return a reference to *that*.
66 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
68 /// Returns a mutable reference to entry `k`. If no such entry exists, call
69 /// `vacant` and either forward its error, or add its result to the map
70 /// and return a reference to *that*.
71 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
74 fn get(&self, k: K) -> Option<&V> {
75 self.get_or(k, || Err(())).ok()
79 fn get_mut(&mut self, k: K) -> Option<&mut V> {
80 self.get_mut_or(k, || Err(())).ok()
84 /// Methods of this trait signifies a point where CTFE evaluation would fail
85 /// and some use case dependent behaviour can instead be applied.
86 pub trait Machine<'mir, 'tcx>: Sized {
87 /// Additional memory kinds a machine wishes to distinguish from the builtin ones
88 type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
90 /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
91 type Provenance: Provenance + Eq + Hash + 'static;
93 /// When getting the AllocId of a pointer, some extra data is also obtained from the provenance
94 /// that is passed to memory access hooks so they can do things with it.
95 type ProvenanceExtra: Copy + 'static;
97 /// Machines can define extra (non-instance) things that represent values of function pointers.
98 /// For example, Miri uses this to return a function pointer from `dlsym`
99 /// that can later be called to execute the right thing.
100 type ExtraFnVal: Debug + Copy;
102 /// Extra data stored in every call frame.
105 /// Extra data stored in every allocation.
106 type AllocExtra: Debug + Clone + 'static;
108 /// Memory's allocation map
109 type MemoryMap: AllocMap<
111 (MemoryKind<Self::MemoryKind>, Allocation<Self::Provenance, Self::AllocExtra>),
115 /// The memory kind to use for copied global memory (held in `tcx`) --
116 /// or None if such memory should not be mutated and thus any such attempt will cause
117 /// a `ModifiedStatic` error to be raised.
118 /// Statics are copied under two circumstances: When they are mutated, and when
119 /// `adjust_allocation` (see below) returns an owned allocation
120 /// that is added to the memory so that the work is not done twice.
121 const GLOBAL_KIND: Option<Self::MemoryKind>;
123 /// Should the machine panic on allocation failures?
124 const PANIC_ON_ALLOC_FAIL: bool;
126 /// Whether memory accesses should be alignment-checked.
127 fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> CheckAlignment;
129 /// Whether, when checking alignment, we should look at the actual address and thus support
130 /// custom alignment logic based on whatever the integer address happens to be.
132 /// If this returns true, Provenance::OFFSET_IS_ADDR must be true.
133 fn use_addr_for_alignment_check(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
135 fn alignment_check_failed(
136 ecx: &InterpCx<'mir, 'tcx, Self>,
139 check: CheckAlignment,
140 ) -> InterpResult<'tcx, ()>;
142 /// Whether to enforce the validity invariant
143 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
145 /// Whether function calls should be [ABI](CallAbi)-checked.
146 fn enforce_abi(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
150 /// Whether CheckedBinOp MIR statements should actually check for overflow.
151 fn checked_binop_checks_overflow(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
153 /// Entry point for obtaining the MIR of anything that should get evaluated.
154 /// So not just functions and shims, but also const/static initializers, anonymous
157 ecx: &InterpCx<'mir, 'tcx, Self>,
158 instance: ty::InstanceDef<'tcx>,
159 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
160 Ok(ecx.tcx.instance_mir(instance))
163 /// Entry point to all function calls.
165 /// Returns either the mir to use for the call, or `None` if execution should
166 /// just proceed (which usually means this hook did all the work that the
167 /// called function should usually have done). In the latter case, it is
168 /// this hook's responsibility to advance the instruction pointer!
169 /// (This is to support functions like `__rust_maybe_catch_panic` that neither find a MIR
170 /// nor just jump to `ret`, but instead push their own stack frame.)
171 /// Passing `dest`and `ret` in the same `Option` proved very annoying when only one of them
173 fn find_mir_or_eval_fn(
174 ecx: &mut InterpCx<'mir, 'tcx, Self>,
175 instance: ty::Instance<'tcx>,
177 args: &[OpTy<'tcx, Self::Provenance>],
178 destination: &PlaceTy<'tcx, Self::Provenance>,
179 target: Option<mir::BasicBlock>,
180 unwind: StackPopUnwind,
181 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>>;
183 /// Execute `fn_val`. It is the hook's responsibility to advance the instruction
184 /// pointer as appropriate.
186 ecx: &mut InterpCx<'mir, 'tcx, Self>,
187 fn_val: Self::ExtraFnVal,
189 args: &[OpTy<'tcx, Self::Provenance>],
190 destination: &PlaceTy<'tcx, Self::Provenance>,
191 target: Option<mir::BasicBlock>,
192 unwind: StackPopUnwind,
193 ) -> InterpResult<'tcx>;
195 /// Directly process an intrinsic without pushing a stack frame. It is the hook's
196 /// responsibility to advance the instruction pointer as appropriate.
198 ecx: &mut InterpCx<'mir, 'tcx, Self>,
199 instance: ty::Instance<'tcx>,
200 args: &[OpTy<'tcx, Self::Provenance>],
201 destination: &PlaceTy<'tcx, Self::Provenance>,
202 target: Option<mir::BasicBlock>,
203 unwind: StackPopUnwind,
204 ) -> InterpResult<'tcx>;
206 /// Called to evaluate `Assert` MIR terminators that trigger a panic.
208 ecx: &mut InterpCx<'mir, 'tcx, Self>,
209 msg: &mir::AssertMessage<'tcx>,
210 unwind: Option<mir::BasicBlock>,
211 ) -> InterpResult<'tcx>;
213 /// Called to evaluate `Abort` MIR terminator.
214 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, _msg: String) -> InterpResult<'tcx, !> {
215 throw_unsup_format!("aborting execution is not supported")
218 /// Called for all binary operations where the LHS has pointer type.
220 /// Returns a (value, overflowed) pair if the operation succeeded
222 ecx: &InterpCx<'mir, 'tcx, Self>,
224 left: &ImmTy<'tcx, Self::Provenance>,
225 right: &ImmTy<'tcx, Self::Provenance>,
226 ) -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool, Ty<'tcx>)>;
228 /// Called to write the specified `local` from the `frame`.
229 /// Since writing a ZST is not actually accessing memory or locals, this is never invoked
232 /// Due to borrow checker trouble, we indicate the `frame` as an index rather than an `&mut
235 fn access_local_mut<'a>(
236 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
239 ) -> InterpResult<'tcx, &'a mut Operand<Self::Provenance>>
243 ecx.stack_mut()[frame].locals[local].access_mut()
246 /// Called before a basic block terminator is executed.
247 /// You can use this to detect endlessly running programs.
249 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
253 /// Called before a global allocation is accessed.
254 /// `def_id` is `Some` if this is the "lazy" allocation of a static.
256 fn before_access_global(
260 _allocation: ConstAllocation<'tcx>,
261 _static_def_id: Option<DefId>,
263 ) -> InterpResult<'tcx> {
267 /// Return the `AllocId` for the given thread-local static in the current thread.
268 fn thread_local_static_base_pointer(
269 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
271 ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
272 throw_unsup!(ThreadLocalStatic(def_id))
275 /// Return the root pointer for the given `extern static`.
276 fn extern_static_base_pointer(
277 ecx: &InterpCx<'mir, 'tcx, Self>,
279 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
281 /// Return a "base" pointer for the given allocation: the one that is used for direct
282 /// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
284 /// Not called on `extern` or thread-local statics (those use the methods above).
285 fn adjust_alloc_base_pointer(
286 ecx: &InterpCx<'mir, 'tcx, Self>,
288 ) -> Pointer<Self::Provenance>;
290 /// "Int-to-pointer cast"
291 fn ptr_from_addr_cast(
292 ecx: &InterpCx<'mir, 'tcx, Self>,
294 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
296 /// Marks a pointer as exposed, allowing it's provenance
297 /// to be recovered. "Pointer-to-int cast"
299 ecx: &mut InterpCx<'mir, 'tcx, Self>,
300 ptr: Pointer<Self::Provenance>,
301 ) -> InterpResult<'tcx>;
303 /// Convert a pointer with provenance into an allocation-offset pair
304 /// and extra provenance info.
306 /// The returned `AllocId` must be the same as `ptr.provenance.get_alloc_id()`.
308 /// When this fails, that means the pointer does not point to a live allocation.
310 ecx: &InterpCx<'mir, 'tcx, Self>,
311 ptr: Pointer<Self::Provenance>,
312 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
314 /// Called to adjust allocations to the Provenance and AllocExtra of this machine.
316 /// The way we construct allocations is to always first construct it without extra and then add
317 /// the extra. This keeps uniform code paths for handling both allocations created by CTFE for
318 /// globals, and allocations created by Miri during evaluation.
320 /// `kind` is the kind of the allocation being adjusted; it can be `None` when
321 /// it's a global and `GLOBAL_KIND` is `None`.
323 /// This should avoid copying if no work has to be done! If this returns an owned
324 /// allocation (because a copy had to be done to adjust things), machine memory will
325 /// cache the result. (This relies on `AllocMap::get_or` being able to add the
326 /// owned allocation to the map even when the map is shared.)
328 /// This must only fail if `alloc` contains provenance.
329 fn adjust_allocation<'b>(
330 ecx: &InterpCx<'mir, 'tcx, Self>,
332 alloc: Cow<'b, Allocation>,
333 kind: Option<MemoryKind<Self::MemoryKind>>,
334 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>>;
337 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
338 _template: &'tcx [InlineAsmTemplatePiece],
339 _operands: &[mir::InlineAsmOperand<'tcx>],
340 _options: InlineAsmOptions,
341 ) -> InterpResult<'tcx> {
342 throw_unsup_format!("inline assembly is not supported")
345 /// Hook for performing extra checks on a memory read access.
347 /// Takes read-only access to the allocation so we can keep all the memory read
348 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
351 fn before_memory_read(
354 _alloc_extra: &Self::AllocExtra,
355 _prov: (AllocId, Self::ProvenanceExtra),
357 ) -> InterpResult<'tcx> {
361 /// Hook for performing extra checks on a memory write access.
363 fn before_memory_write(
366 _alloc_extra: &mut Self::AllocExtra,
367 _prov: (AllocId, Self::ProvenanceExtra),
369 ) -> InterpResult<'tcx> {
373 /// Hook for performing extra operations on a memory deallocation.
375 fn before_memory_deallocation(
378 _alloc_extra: &mut Self::AllocExtra,
379 _prov: (AllocId, Self::ProvenanceExtra),
381 ) -> InterpResult<'tcx> {
385 /// Executes a retagging operation for a single pointer.
386 /// Returns the possibly adjusted pointer.
389 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
390 _kind: mir::RetagKind,
391 val: &ImmTy<'tcx, Self::Provenance>,
392 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
396 /// Executes a retagging operation on a compound value.
397 /// Replaces all pointers stored in the given place.
399 fn retag_place_contents(
400 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
401 _kind: mir::RetagKind,
402 _place: &PlaceTy<'tcx, Self::Provenance>,
403 ) -> InterpResult<'tcx> {
407 /// Called immediately before a new stack frame gets pushed.
409 ecx: &mut InterpCx<'mir, 'tcx, Self>,
410 frame: Frame<'mir, 'tcx, Self::Provenance>,
411 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
413 /// Borrow the current thread's stack.
415 ecx: &'a InterpCx<'mir, 'tcx, Self>,
416 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>];
418 /// Mutably borrow the current thread's stack.
420 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
421 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
423 /// Called immediately after a stack frame got pushed and its locals got initialized.
424 fn after_stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
428 /// Called immediately after a stack frame got popped, but before jumping back to the caller.
429 /// The `locals` have already been destroyed!
431 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
432 _frame: Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,
434 ) -> InterpResult<'tcx, StackPopJump> {
435 // By default, we do not support unwinding from panics
437 Ok(StackPopJump::Normal)
441 /// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
442 /// (CTFE and ConstProp) use the same instance. Here, we share that code.
443 pub macro compile_time_machine(<$mir: lifetime, $tcx: lifetime>) {
444 type Provenance = AllocId;
445 type ProvenanceExtra = ();
450 rustc_data_structures::fx::FxIndexMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
451 const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
453 type AllocExtra = ();
454 type FrameExtra = ();
457 fn use_addr_for_alignment_check(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
458 // We do not support `use_addr`.
463 fn checked_binop_checks_overflow(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
469 _ecx: &mut InterpCx<$mir, $tcx, Self>,
472 _args: &[OpTy<$tcx>],
473 _destination: &PlaceTy<$tcx, Self::Provenance>,
474 _target: Option<mir::BasicBlock>,
475 _unwind: StackPopUnwind,
476 ) -> InterpResult<$tcx> {
481 fn adjust_allocation<'b>(
482 _ecx: &InterpCx<$mir, $tcx, Self>,
484 alloc: Cow<'b, Allocation>,
485 _kind: Option<MemoryKind<Self::MemoryKind>>,
486 ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
490 fn extern_static_base_pointer(
491 ecx: &InterpCx<$mir, $tcx, Self>,
493 ) -> InterpResult<$tcx, Pointer> {
494 // Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
495 Ok(Pointer::new(ecx.tcx.create_static_alloc(def_id), Size::ZERO))
499 fn adjust_alloc_base_pointer(
500 _ecx: &InterpCx<$mir, $tcx, Self>,
501 ptr: Pointer<AllocId>,
502 ) -> Pointer<AllocId> {
507 fn ptr_from_addr_cast(
508 _ecx: &InterpCx<$mir, $tcx, Self>,
510 ) -> InterpResult<$tcx, Pointer<Option<AllocId>>> {
511 // Allow these casts, but make the pointer not dereferenceable.
512 // (I.e., they behave like transmutation.)
513 // This is correct because no pointers can ever be exposed in compile-time evaluation.
514 Ok(Pointer::from_addr(addr))
519 _ecx: &InterpCx<$mir, $tcx, Self>,
520 ptr: Pointer<AllocId>,
521 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
522 // We know `offset` is relative to the allocation, so we can use `into_parts`.
523 let (alloc_id, offset) = ptr.into_parts();
524 Some((alloc_id, offset, ()))