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};
10 use rustc_middle::ty::{self, Ty, TyCtxt};
11 use rustc_span::def_id::DefId;
12 use rustc_target::abi::Size;
13 use rustc_target::spec::abi::Abi as CallAbi;
16 AllocId, AllocRange, Allocation, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
17 MemoryKind, OpTy, Operand, PlaceTy, Pointer, Provenance, Scalar, StackPopUnwind,
20 /// Data returned by Machine::stack_pop,
21 /// to provide further control over the popping of the stack frame
22 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
23 pub enum StackPopJump {
24 /// Indicates that no special handling should be
25 /// done - we'll either return normally or unwind
26 /// based on the terminator for the function
30 /// Indicates that we should *not* jump to the return/unwind address, as the callback already
31 /// took care of everything.
35 /// Whether this kind of memory is allowed to leak
36 pub trait MayLeak: Copy {
37 fn may_leak(self) -> bool;
40 /// The functionality needed by memory to manage its allocations
41 pub trait AllocMap<K: Hash + Eq, V> {
42 /// Tests if the map contains the given key.
43 /// Deliberately takes `&mut` because that is sufficient, and some implementations
44 /// can be more efficient then (using `RefCell::get_mut`).
45 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
49 /// Inserts a new entry into the map.
50 fn insert(&mut self, k: K, v: V) -> Option<V>;
52 /// Removes an entry from the map.
53 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
57 /// Returns data based on the keys and values in the map.
58 fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
60 /// Returns a reference to entry `k`. If no such entry exists, call
61 /// `vacant` and either forward its error, or add its result to the map
62 /// and return a reference to *that*.
63 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
65 /// Returns a mutable reference to entry `k`. If no such entry exists, call
66 /// `vacant` and either forward its error, or add its result to the map
67 /// and return a reference to *that*.
68 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
71 fn get(&self, k: K) -> Option<&V> {
72 self.get_or(k, || Err(())).ok()
76 fn get_mut(&mut self, k: K) -> Option<&mut V> {
77 self.get_mut_or(k, || Err(())).ok()
81 /// Methods of this trait signifies a point where CTFE evaluation would fail
82 /// and some use case dependent behaviour can instead be applied.
83 pub trait Machine<'mir, 'tcx>: Sized {
84 /// Additional memory kinds a machine wishes to distinguish from the builtin ones
85 type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
87 /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
88 type Provenance: Provenance + Eq + Hash + 'static;
90 /// When getting the AllocId of a pointer, some extra data is also obtained from the provenance
91 /// that is passed to memory access hooks so they can do things with it.
92 type ProvenanceExtra: Copy + 'static;
94 /// Machines can define extra (non-instance) things that represent values of function pointers.
95 /// For example, Miri uses this to return a function pointer from `dlsym`
96 /// that can later be called to execute the right thing.
97 type ExtraFnVal: Debug + Copy;
99 /// Extra data stored in every call frame.
102 /// Extra data stored in every allocation.
103 type AllocExtra: Debug + Clone + 'static;
105 /// Memory's allocation map
106 type MemoryMap: AllocMap<
108 (MemoryKind<Self::MemoryKind>, Allocation<Self::Provenance, Self::AllocExtra>),
112 /// The memory kind to use for copied global memory (held in `tcx`) --
113 /// or None if such memory should not be mutated and thus any such attempt will cause
114 /// a `ModifiedStatic` error to be raised.
115 /// Statics are copied under two circumstances: When they are mutated, and when
116 /// `adjust_allocation` (see below) returns an owned allocation
117 /// that is added to the memory so that the work is not done twice.
118 const GLOBAL_KIND: Option<Self::MemoryKind>;
120 /// Should the machine panic on allocation failures?
121 const PANIC_ON_ALLOC_FAIL: bool;
123 /// Whether memory accesses should be alignment-checked.
124 fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
126 /// Whether, when checking alignment, we should look at the actual address and thus support
127 /// custom alignment logic based on whatever the integer address happens to be.
129 /// If this returns true, Provenance::OFFSET_IS_ADDR must be true.
130 fn use_addr_for_alignment_check(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
132 /// Whether to enforce the validity invariant
133 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
135 /// Whether function calls should be [ABI](CallAbi)-checked.
136 fn enforce_abi(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
140 /// Whether CheckedBinOp MIR statements should actually check for overflow.
141 fn checked_binop_checks_overflow(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
143 /// Entry point for obtaining the MIR of anything that should get evaluated.
144 /// So not just functions and shims, but also const/static initializers, anonymous
147 ecx: &InterpCx<'mir, 'tcx, Self>,
148 instance: ty::InstanceDef<'tcx>,
149 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
150 Ok(ecx.tcx.instance_mir(instance))
153 /// Entry point to all function calls.
155 /// Returns either the mir to use for the call, or `None` if execution should
156 /// just proceed (which usually means this hook did all the work that the
157 /// called function should usually have done). In the latter case, it is
158 /// this hook's responsibility to advance the instruction pointer!
159 /// (This is to support functions like `__rust_maybe_catch_panic` that neither find a MIR
160 /// nor just jump to `ret`, but instead push their own stack frame.)
161 /// Passing `dest`and `ret` in the same `Option` proved very annoying when only one of them
163 fn find_mir_or_eval_fn(
164 ecx: &mut InterpCx<'mir, 'tcx, Self>,
165 instance: ty::Instance<'tcx>,
167 args: &[OpTy<'tcx, Self::Provenance>],
168 destination: &PlaceTy<'tcx, Self::Provenance>,
169 target: Option<mir::BasicBlock>,
170 unwind: StackPopUnwind,
171 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>>;
173 /// Execute `fn_val`. It is the hook's responsibility to advance the instruction
174 /// pointer as appropriate.
176 ecx: &mut InterpCx<'mir, 'tcx, Self>,
177 fn_val: Self::ExtraFnVal,
179 args: &[OpTy<'tcx, Self::Provenance>],
180 destination: &PlaceTy<'tcx, Self::Provenance>,
181 target: Option<mir::BasicBlock>,
182 unwind: StackPopUnwind,
183 ) -> InterpResult<'tcx>;
185 /// Directly process an intrinsic without pushing a stack frame. It is the hook's
186 /// responsibility to advance the instruction pointer as appropriate.
188 ecx: &mut InterpCx<'mir, 'tcx, Self>,
189 instance: ty::Instance<'tcx>,
190 args: &[OpTy<'tcx, Self::Provenance>],
191 destination: &PlaceTy<'tcx, Self::Provenance>,
192 target: Option<mir::BasicBlock>,
193 unwind: StackPopUnwind,
194 ) -> InterpResult<'tcx>;
196 /// Called to evaluate `Assert` MIR terminators that trigger a panic.
198 ecx: &mut InterpCx<'mir, 'tcx, Self>,
199 msg: &mir::AssertMessage<'tcx>,
200 unwind: Option<mir::BasicBlock>,
201 ) -> InterpResult<'tcx>;
203 /// Called to evaluate `Abort` MIR terminator.
204 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, _msg: String) -> InterpResult<'tcx, !> {
205 throw_unsup_format!("aborting execution is not supported")
208 /// Called for all binary operations where the LHS has pointer type.
210 /// Returns a (value, overflowed) pair if the operation succeeded
212 ecx: &InterpCx<'mir, 'tcx, Self>,
214 left: &ImmTy<'tcx, Self::Provenance>,
215 right: &ImmTy<'tcx, Self::Provenance>,
216 ) -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool, Ty<'tcx>)>;
218 /// Called to write the specified `local` from the `frame`.
219 /// Since writing a ZST is not actually accessing memory or locals, this is never invoked
222 /// Due to borrow checker trouble, we indicate the `frame` as an index rather than an `&mut
225 fn access_local_mut<'a>(
226 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
229 ) -> InterpResult<'tcx, &'a mut Operand<Self::Provenance>>
233 ecx.stack_mut()[frame].locals[local].access_mut()
236 /// Called before a basic block terminator is executed.
237 /// You can use this to detect endlessly running programs.
239 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
243 /// Called before a global allocation is accessed.
244 /// `def_id` is `Some` if this is the "lazy" allocation of a static.
246 fn before_access_global(
250 _allocation: ConstAllocation<'tcx>,
251 _static_def_id: Option<DefId>,
253 ) -> InterpResult<'tcx> {
257 /// Return the `AllocId` for the given thread-local static in the current thread.
258 fn thread_local_static_base_pointer(
259 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
261 ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
262 throw_unsup!(ThreadLocalStatic(def_id))
265 /// Return the root pointer for the given `extern static`.
266 fn extern_static_base_pointer(
267 ecx: &InterpCx<'mir, 'tcx, Self>,
269 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
271 /// Return a "base" pointer for the given allocation: the one that is used for direct
272 /// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
274 /// Not called on `extern` or thread-local statics (those use the methods above).
275 fn adjust_alloc_base_pointer(
276 ecx: &InterpCx<'mir, 'tcx, Self>,
278 ) -> Pointer<Self::Provenance>;
280 /// "Int-to-pointer cast"
281 fn ptr_from_addr_cast(
282 ecx: &InterpCx<'mir, 'tcx, Self>,
284 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
286 /// Marks a pointer as exposed, allowing it's provenance
287 /// to be recovered. "Pointer-to-int cast"
289 ecx: &mut InterpCx<'mir, 'tcx, Self>,
290 ptr: Pointer<Self::Provenance>,
291 ) -> InterpResult<'tcx>;
293 /// Convert a pointer with provenance into an allocation-offset pair
294 /// and extra provenance info.
296 /// The returned `AllocId` must be the same as `ptr.provenance.get_alloc_id()`.
298 /// When this fails, that means the pointer does not point to a live allocation.
300 ecx: &InterpCx<'mir, 'tcx, Self>,
301 ptr: Pointer<Self::Provenance>,
302 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
304 /// Called to adjust allocations to the Provenance and AllocExtra of this machine.
306 /// The way we construct allocations is to always first construct it without extra and then add
307 /// the extra. This keeps uniform code paths for handling both allocations created by CTFE for
308 /// globals, and allocations created by Miri during evaluation.
310 /// `kind` is the kind of the allocation being adjusted; it can be `None` when
311 /// it's a global and `GLOBAL_KIND` is `None`.
313 /// This should avoid copying if no work has to be done! If this returns an owned
314 /// allocation (because a copy had to be done to adjust things), machine memory will
315 /// cache the result. (This relies on `AllocMap::get_or` being able to add the
316 /// owned allocation to the map even when the map is shared.)
318 /// This must only fail if `alloc` contains provenance.
319 fn adjust_allocation<'b>(
320 ecx: &InterpCx<'mir, 'tcx, Self>,
322 alloc: Cow<'b, Allocation>,
323 kind: Option<MemoryKind<Self::MemoryKind>>,
324 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>>;
326 /// Hook for performing extra checks on a memory read access.
328 /// Takes read-only access to the allocation so we can keep all the memory read
329 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
332 fn before_memory_read(
335 _alloc_extra: &Self::AllocExtra,
336 _prov: (AllocId, Self::ProvenanceExtra),
338 ) -> InterpResult<'tcx> {
342 /// Hook for performing extra checks on a memory write access.
344 fn before_memory_write(
347 _alloc_extra: &mut Self::AllocExtra,
348 _prov: (AllocId, Self::ProvenanceExtra),
350 ) -> InterpResult<'tcx> {
354 /// Hook for performing extra operations on a memory deallocation.
356 fn before_memory_deallocation(
359 _alloc_extra: &mut Self::AllocExtra,
360 _prov: (AllocId, Self::ProvenanceExtra),
362 ) -> InterpResult<'tcx> {
366 /// Executes a retagging operation.
369 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
370 _kind: mir::RetagKind,
371 _place: &PlaceTy<'tcx, Self::Provenance>,
372 ) -> InterpResult<'tcx> {
376 /// Called immediately before a new stack frame gets pushed.
378 ecx: &mut InterpCx<'mir, 'tcx, Self>,
379 frame: Frame<'mir, 'tcx, Self::Provenance>,
380 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
382 /// Borrow the current thread's stack.
384 ecx: &'a InterpCx<'mir, 'tcx, Self>,
385 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>];
387 /// Mutably borrow the current thread's stack.
389 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
390 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
392 /// Called immediately after a stack frame got pushed and its locals got initialized.
393 fn after_stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
397 /// Called immediately after a stack frame got popped, but before jumping back to the caller.
398 /// The `locals` have already been destroyed!
400 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
401 _frame: Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,
403 ) -> InterpResult<'tcx, StackPopJump> {
404 // By default, we do not support unwinding from panics
406 Ok(StackPopJump::Normal)
410 // A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
411 // (CTFE and ConstProp) use the same instance. Here, we share that code.
412 pub macro compile_time_machine(<$mir: lifetime, $tcx: lifetime>) {
413 type Provenance = AllocId;
414 type ProvenanceExtra = ();
419 rustc_data_structures::fx::FxHashMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
420 const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
422 type AllocExtra = ();
423 type FrameExtra = ();
426 fn use_addr_for_alignment_check(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
427 // We do not support `use_addr`.
432 fn checked_binop_checks_overflow(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
438 _ecx: &mut InterpCx<$mir, $tcx, Self>,
441 _args: &[OpTy<$tcx>],
442 _destination: &PlaceTy<$tcx, Self::Provenance>,
443 _target: Option<mir::BasicBlock>,
444 _unwind: StackPopUnwind,
445 ) -> InterpResult<$tcx> {
450 fn adjust_allocation<'b>(
451 _ecx: &InterpCx<$mir, $tcx, Self>,
453 alloc: Cow<'b, Allocation>,
454 _kind: Option<MemoryKind<Self::MemoryKind>>,
455 ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
459 fn extern_static_base_pointer(
460 ecx: &InterpCx<$mir, $tcx, Self>,
462 ) -> InterpResult<$tcx, Pointer> {
463 // Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
464 Ok(Pointer::new(ecx.tcx.create_static_alloc(def_id), Size::ZERO))
468 fn adjust_alloc_base_pointer(
469 _ecx: &InterpCx<$mir, $tcx, Self>,
470 ptr: Pointer<AllocId>,
471 ) -> Pointer<AllocId> {
476 fn ptr_from_addr_cast(
477 _ecx: &InterpCx<$mir, $tcx, Self>,
479 ) -> InterpResult<$tcx, Pointer<Option<AllocId>>> {
480 // Allow these casts, but make the pointer not dereferenceable.
481 // (I.e., they behave like transmutation.)
482 // This is correct because no pointers can ever be exposed in compile-time evaluation.
483 Ok(Pointer::from_addr(addr))
488 _ecx: &InterpCx<$mir, $tcx, Self>,
489 ptr: Pointer<AllocId>,
490 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
491 // We know `offset` is relative to the allocation, so we can use `into_parts`.
492 let (alloc_id, offset) = ptr.into_parts();
493 Some((alloc_id, offset, ()))