]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/machine.rs
Point at type parameter in plain path expr
[rust.git] / compiler / rustc_const_eval / src / interpret / machine.rs
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.
4
5 use std::borrow::{Borrow, Cow};
6 use std::fmt::Debug;
7 use std::hash::Hash;
8
9 use rustc_middle::mir;
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;
14
15 use super::{
16     AllocId, AllocRange, Allocation, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
17     MemoryKind, OpTy, Operand, PlaceTy, Pointer, Provenance, Scalar, StackPopUnwind,
18 };
19
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
27     /// we're leaving.
28     Normal,
29
30     /// Indicates that we should *not* jump to the return/unwind address, as the callback already
31     /// took care of everything.
32     NoJump,
33 }
34
35 /// Whether this kind of memory is allowed to leak
36 pub trait MayLeak: Copy {
37     fn may_leak(self) -> bool;
38 }
39
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
46     where
47         K: Borrow<Q>;
48
49     /// Inserts a new entry into the map.
50     fn insert(&mut self, k: K, v: V) -> Option<V>;
51
52     /// Removes an entry from the map.
53     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
54     where
55         K: Borrow<Q>;
56
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>;
59
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>;
64
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>;
69
70     /// Read-only lookup.
71     fn get(&self, k: K) -> Option<&V> {
72         self.get_or(k, || Err(())).ok()
73     }
74
75     /// Mutable lookup.
76     fn get_mut(&mut self, k: K) -> Option<&mut V> {
77         self.get_mut_or(k, || Err(())).ok()
78     }
79 }
80
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;
86
87     /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
88     type Provenance: Provenance + Eq + Hash + 'static;
89
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;
93
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;
98
99     /// Extra data stored in every call frame.
100     type FrameExtra;
101
102     /// Extra data stored in every allocation.
103     type AllocExtra: Debug + Clone + 'static;
104
105     /// Memory's allocation map
106     type MemoryMap: AllocMap<
107             AllocId,
108             (MemoryKind<Self::MemoryKind>, Allocation<Self::Provenance, Self::AllocExtra>),
109         > + Default
110         + Clone;
111
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>;
119
120     /// Should the machine panic on allocation failures?
121     const PANIC_ON_ALLOC_FAIL: bool;
122
123     /// Whether memory accesses should be alignment-checked.
124     fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
125
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.
128     ///
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;
131
132     /// Whether to enforce the validity invariant
133     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
134
135     /// Whether function calls should be [ABI](CallAbi)-checked.
136     fn enforce_abi(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
137         true
138     }
139
140     /// Whether CheckedBinOp MIR statements should actually check for overflow.
141     fn checked_binop_checks_overflow(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
142
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
145     /// constants, ...
146     fn load_mir(
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))
151     }
152
153     /// Entry point to all function calls.
154     ///
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
162     /// was used.
163     fn find_mir_or_eval_fn(
164         ecx: &mut InterpCx<'mir, 'tcx, Self>,
165         instance: ty::Instance<'tcx>,
166         abi: CallAbi,
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>)>>;
172
173     /// Execute `fn_val`.  It is the hook's responsibility to advance the instruction
174     /// pointer as appropriate.
175     fn call_extra_fn(
176         ecx: &mut InterpCx<'mir, 'tcx, Self>,
177         fn_val: Self::ExtraFnVal,
178         abi: CallAbi,
179         args: &[OpTy<'tcx, Self::Provenance>],
180         destination: &PlaceTy<'tcx, Self::Provenance>,
181         target: Option<mir::BasicBlock>,
182         unwind: StackPopUnwind,
183     ) -> InterpResult<'tcx>;
184
185     /// Directly process an intrinsic without pushing a stack frame. It is the hook's
186     /// responsibility to advance the instruction pointer as appropriate.
187     fn call_intrinsic(
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>;
195
196     /// Called to evaluate `Assert` MIR terminators that trigger a panic.
197     fn assert_panic(
198         ecx: &mut InterpCx<'mir, 'tcx, Self>,
199         msg: &mir::AssertMessage<'tcx>,
200         unwind: Option<mir::BasicBlock>,
201     ) -> InterpResult<'tcx>;
202
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")
206     }
207
208     /// Called for all binary operations where the LHS has pointer type.
209     ///
210     /// Returns a (value, overflowed) pair if the operation succeeded
211     fn binary_ptr_op(
212         ecx: &InterpCx<'mir, 'tcx, Self>,
213         bin_op: mir::BinOp,
214         left: &ImmTy<'tcx, Self::Provenance>,
215         right: &ImmTy<'tcx, Self::Provenance>,
216     ) -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool, Ty<'tcx>)>;
217
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
220     /// for ZST reads.
221     ///
222     /// Due to borrow checker trouble, we indicate the `frame` as an index rather than an `&mut
223     /// Frame`.
224     #[inline]
225     fn access_local_mut<'a>(
226         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
227         frame: usize,
228         local: mir::Local,
229     ) -> InterpResult<'tcx, &'a mut Operand<Self::Provenance>>
230     where
231         'tcx: 'mir,
232     {
233         ecx.stack_mut()[frame].locals[local].access_mut()
234     }
235
236     /// Called before a basic block terminator is executed.
237     /// You can use this to detect endlessly running programs.
238     #[inline]
239     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
240         Ok(())
241     }
242
243     /// Called before a global allocation is accessed.
244     /// `def_id` is `Some` if this is the "lazy" allocation of a static.
245     #[inline]
246     fn before_access_global(
247         _tcx: TyCtxt<'tcx>,
248         _machine: &Self,
249         _alloc_id: AllocId,
250         _allocation: ConstAllocation<'tcx>,
251         _static_def_id: Option<DefId>,
252         _is_write: bool,
253     ) -> InterpResult<'tcx> {
254         Ok(())
255     }
256
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>,
260         def_id: DefId,
261     ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
262         throw_unsup!(ThreadLocalStatic(def_id))
263     }
264
265     /// Return the root pointer for the given `extern static`.
266     fn extern_static_base_pointer(
267         ecx: &InterpCx<'mir, 'tcx, Self>,
268         def_id: DefId,
269     ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
270
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.
273     ///
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>,
277         ptr: Pointer,
278     ) -> Pointer<Self::Provenance>;
279
280     /// "Int-to-pointer cast"
281     fn ptr_from_addr_cast(
282         ecx: &InterpCx<'mir, 'tcx, Self>,
283         addr: u64,
284     ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
285
286     /// Marks a pointer as exposed, allowing it's provenance
287     /// to be recovered. "Pointer-to-int cast"
288     fn expose_ptr(
289         ecx: &mut InterpCx<'mir, 'tcx, Self>,
290         ptr: Pointer<Self::Provenance>,
291     ) -> InterpResult<'tcx>;
292
293     /// Convert a pointer with provenance into an allocation-offset pair
294     /// and extra provenance info.
295     ///
296     /// The returned `AllocId` must be the same as `ptr.provenance.get_alloc_id()`.
297     ///
298     /// When this fails, that means the pointer does not point to a live allocation.
299     fn ptr_get_alloc(
300         ecx: &InterpCx<'mir, 'tcx, Self>,
301         ptr: Pointer<Self::Provenance>,
302     ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
303
304     /// Called to adjust allocations to the Provenance and AllocExtra of this machine.
305     ///
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.
309     ///
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`.
312     ///
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.)
317     ///
318     /// This must only fail if `alloc` contains provenance.
319     fn adjust_allocation<'b>(
320         ecx: &InterpCx<'mir, 'tcx, Self>,
321         id: AllocId,
322         alloc: Cow<'b, Allocation>,
323         kind: Option<MemoryKind<Self::MemoryKind>>,
324     ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>>;
325
326     /// Hook for performing extra checks on a memory read access.
327     ///
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
330     /// need to mutate.
331     #[inline(always)]
332     fn before_memory_read(
333         _tcx: TyCtxt<'tcx>,
334         _machine: &Self,
335         _alloc_extra: &Self::AllocExtra,
336         _prov: (AllocId, Self::ProvenanceExtra),
337         _range: AllocRange,
338     ) -> InterpResult<'tcx> {
339         Ok(())
340     }
341
342     /// Hook for performing extra checks on a memory write access.
343     #[inline(always)]
344     fn before_memory_write(
345         _tcx: TyCtxt<'tcx>,
346         _machine: &mut Self,
347         _alloc_extra: &mut Self::AllocExtra,
348         _prov: (AllocId, Self::ProvenanceExtra),
349         _range: AllocRange,
350     ) -> InterpResult<'tcx> {
351         Ok(())
352     }
353
354     /// Hook for performing extra operations on a memory deallocation.
355     #[inline(always)]
356     fn before_memory_deallocation(
357         _tcx: TyCtxt<'tcx>,
358         _machine: &mut Self,
359         _alloc_extra: &mut Self::AllocExtra,
360         _prov: (AllocId, Self::ProvenanceExtra),
361         _range: AllocRange,
362     ) -> InterpResult<'tcx> {
363         Ok(())
364     }
365
366     /// Executes a retagging operation.
367     #[inline]
368     fn retag(
369         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
370         _kind: mir::RetagKind,
371         _place: &PlaceTy<'tcx, Self::Provenance>,
372     ) -> InterpResult<'tcx> {
373         Ok(())
374     }
375
376     /// Called immediately before a new stack frame gets pushed.
377     fn init_frame_extra(
378         ecx: &mut InterpCx<'mir, 'tcx, Self>,
379         frame: Frame<'mir, 'tcx, Self::Provenance>,
380     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
381
382     /// Borrow the current thread's stack.
383     fn stack<'a>(
384         ecx: &'a InterpCx<'mir, 'tcx, Self>,
385     ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>];
386
387     /// Mutably borrow the current thread's stack.
388     fn stack_mut<'a>(
389         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
390     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
391
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> {
394         Ok(())
395     }
396
397     /// Called immediately after a stack frame got popped, but before jumping back to the caller.
398     /// The `locals` have already been destroyed!
399     fn after_stack_pop(
400         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
401         _frame: Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,
402         unwinding: bool,
403     ) -> InterpResult<'tcx, StackPopJump> {
404         // By default, we do not support unwinding from panics
405         assert!(!unwinding);
406         Ok(StackPopJump::Normal)
407     }
408 }
409
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 = ();
415
416     type ExtraFnVal = !;
417
418     type MemoryMap =
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
421
422     type AllocExtra = ();
423     type FrameExtra = ();
424
425     #[inline(always)]
426     fn use_addr_for_alignment_check(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
427         // We do not support `use_addr`.
428         false
429     }
430
431     #[inline(always)]
432     fn checked_binop_checks_overflow(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
433         true
434     }
435
436     #[inline(always)]
437     fn call_extra_fn(
438         _ecx: &mut InterpCx<$mir, $tcx, Self>,
439         fn_val: !,
440         _abi: CallAbi,
441         _args: &[OpTy<$tcx>],
442         _destination: &PlaceTy<$tcx, Self::Provenance>,
443         _target: Option<mir::BasicBlock>,
444         _unwind: StackPopUnwind,
445     ) -> InterpResult<$tcx> {
446         match fn_val {}
447     }
448
449     #[inline(always)]
450     fn adjust_allocation<'b>(
451         _ecx: &InterpCx<$mir, $tcx, Self>,
452         _id: AllocId,
453         alloc: Cow<'b, Allocation>,
454         _kind: Option<MemoryKind<Self::MemoryKind>>,
455     ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
456         Ok(alloc)
457     }
458
459     fn extern_static_base_pointer(
460         ecx: &InterpCx<$mir, $tcx, Self>,
461         def_id: DefId,
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))
465     }
466
467     #[inline(always)]
468     fn adjust_alloc_base_pointer(
469         _ecx: &InterpCx<$mir, $tcx, Self>,
470         ptr: Pointer<AllocId>,
471     ) -> Pointer<AllocId> {
472         ptr
473     }
474
475     #[inline(always)]
476     fn ptr_from_addr_cast(
477         _ecx: &InterpCx<$mir, $tcx, Self>,
478         addr: u64,
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))
484     }
485
486     #[inline(always)]
487     fn ptr_get_alloc(
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, ()))
494     }
495 }