]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/machine.rs
1d4ef20d0651f7bd11d7cb466f0290d375ff27d8
[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_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;
15
16 use crate::const_eval::CheckAlignment;
17
18 use super::{
19     AllocId, AllocRange, Allocation, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
20     MemoryKind, OpTy, Operand, PlaceTy, Pointer, Provenance, Scalar, StackPopUnwind,
21 };
22
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
30     /// we're leaving.
31     Normal,
32
33     /// Indicates that we should *not* jump to the return/unwind address, as the callback already
34     /// took care of everything.
35     NoJump,
36 }
37
38 /// Whether this kind of memory is allowed to leak
39 pub trait MayLeak: Copy {
40     fn may_leak(self) -> bool;
41 }
42
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
49     where
50         K: Borrow<Q>;
51
52     /// Inserts a new entry into the map.
53     fn insert(&mut self, k: K, v: V) -> Option<V>;
54
55     /// Removes an entry from the map.
56     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
57     where
58         K: Borrow<Q>;
59
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>;
62
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>;
67
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>;
72
73     /// Read-only lookup.
74     fn get(&self, k: K) -> Option<&V> {
75         self.get_or(k, || Err(())).ok()
76     }
77
78     /// Mutable lookup.
79     fn get_mut(&mut self, k: K) -> Option<&mut V> {
80         self.get_mut_or(k, || Err(())).ok()
81     }
82 }
83
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;
89
90     /// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
91     type Provenance: Provenance + Eq + Hash + 'static;
92
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;
96
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;
101
102     /// Extra data stored in every call frame.
103     type FrameExtra;
104
105     /// Extra data stored in every allocation.
106     type AllocExtra: Debug + Clone + 'static;
107
108     /// Memory's allocation map
109     type MemoryMap: AllocMap<
110             AllocId,
111             (MemoryKind<Self::MemoryKind>, Allocation<Self::Provenance, Self::AllocExtra>),
112         > + Default
113         + Clone;
114
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>;
122
123     /// Should the machine panic on allocation failures?
124     const PANIC_ON_ALLOC_FAIL: bool;
125
126     /// Whether memory accesses should be alignment-checked.
127     fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> CheckAlignment;
128
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.
131     ///
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;
134
135     fn alignment_check_failed(
136         ecx: &InterpCx<'mir, 'tcx, Self>,
137         has: Align,
138         required: Align,
139         check: CheckAlignment,
140     ) -> InterpResult<'tcx, ()>;
141
142     /// Whether to enforce the validity invariant
143     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
144
145     /// Whether function calls should be [ABI](CallAbi)-checked.
146     fn enforce_abi(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
147         true
148     }
149
150     /// Whether CheckedBinOp MIR statements should actually check for overflow.
151     fn checked_binop_checks_overflow(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool;
152
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
155     /// constants, ...
156     fn load_mir(
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))
161     }
162
163     /// Entry point to all function calls.
164     ///
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
172     /// was used.
173     fn find_mir_or_eval_fn(
174         ecx: &mut InterpCx<'mir, 'tcx, Self>,
175         instance: ty::Instance<'tcx>,
176         abi: CallAbi,
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>)>>;
182
183     /// Execute `fn_val`.  It is the hook's responsibility to advance the instruction
184     /// pointer as appropriate.
185     fn call_extra_fn(
186         ecx: &mut InterpCx<'mir, 'tcx, Self>,
187         fn_val: Self::ExtraFnVal,
188         abi: CallAbi,
189         args: &[OpTy<'tcx, Self::Provenance>],
190         destination: &PlaceTy<'tcx, Self::Provenance>,
191         target: Option<mir::BasicBlock>,
192         unwind: StackPopUnwind,
193     ) -> InterpResult<'tcx>;
194
195     /// Directly process an intrinsic without pushing a stack frame. It is the hook's
196     /// responsibility to advance the instruction pointer as appropriate.
197     fn call_intrinsic(
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>;
205
206     /// Called to evaluate `Assert` MIR terminators that trigger a panic.
207     fn assert_panic(
208         ecx: &mut InterpCx<'mir, 'tcx, Self>,
209         msg: &mir::AssertMessage<'tcx>,
210         unwind: Option<mir::BasicBlock>,
211     ) -> InterpResult<'tcx>;
212
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")
216     }
217
218     /// Called for all binary operations where the LHS has pointer type.
219     ///
220     /// Returns a (value, overflowed) pair if the operation succeeded
221     fn binary_ptr_op(
222         ecx: &InterpCx<'mir, 'tcx, Self>,
223         bin_op: mir::BinOp,
224         left: &ImmTy<'tcx, Self::Provenance>,
225         right: &ImmTy<'tcx, Self::Provenance>,
226     ) -> InterpResult<'tcx, (Scalar<Self::Provenance>, bool, Ty<'tcx>)>;
227
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
230     /// for ZST reads.
231     ///
232     /// Due to borrow checker trouble, we indicate the `frame` as an index rather than an `&mut
233     /// Frame`.
234     #[inline]
235     fn access_local_mut<'a>(
236         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
237         frame: usize,
238         local: mir::Local,
239     ) -> InterpResult<'tcx, &'a mut Operand<Self::Provenance>>
240     where
241         'tcx: 'mir,
242     {
243         ecx.stack_mut()[frame].locals[local].access_mut()
244     }
245
246     /// Called before a basic block terminator is executed.
247     /// You can use this to detect endlessly running programs.
248     #[inline]
249     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
250         Ok(())
251     }
252
253     /// Called before a global allocation is accessed.
254     /// `def_id` is `Some` if this is the "lazy" allocation of a static.
255     #[inline]
256     fn before_access_global(
257         _tcx: TyCtxt<'tcx>,
258         _machine: &Self,
259         _alloc_id: AllocId,
260         _allocation: ConstAllocation<'tcx>,
261         _static_def_id: Option<DefId>,
262         _is_write: bool,
263     ) -> InterpResult<'tcx> {
264         Ok(())
265     }
266
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>,
270         def_id: DefId,
271     ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
272         throw_unsup!(ThreadLocalStatic(def_id))
273     }
274
275     /// Return the root pointer for the given `extern static`.
276     fn extern_static_base_pointer(
277         ecx: &InterpCx<'mir, 'tcx, Self>,
278         def_id: DefId,
279     ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
280
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.
283     ///
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>,
287         ptr: Pointer,
288     ) -> Pointer<Self::Provenance>;
289
290     /// "Int-to-pointer cast"
291     fn ptr_from_addr_cast(
292         ecx: &InterpCx<'mir, 'tcx, Self>,
293         addr: u64,
294     ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
295
296     /// Marks a pointer as exposed, allowing it's provenance
297     /// to be recovered. "Pointer-to-int cast"
298     fn expose_ptr(
299         ecx: &mut InterpCx<'mir, 'tcx, Self>,
300         ptr: Pointer<Self::Provenance>,
301     ) -> InterpResult<'tcx>;
302
303     /// Convert a pointer with provenance into an allocation-offset pair
304     /// and extra provenance info.
305     ///
306     /// The returned `AllocId` must be the same as `ptr.provenance.get_alloc_id()`.
307     ///
308     /// When this fails, that means the pointer does not point to a live allocation.
309     fn ptr_get_alloc(
310         ecx: &InterpCx<'mir, 'tcx, Self>,
311         ptr: Pointer<Self::Provenance>,
312     ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
313
314     /// Called to adjust allocations to the Provenance and AllocExtra of this machine.
315     ///
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.
319     ///
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`.
322     ///
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.)
327     ///
328     /// This must only fail if `alloc` contains provenance.
329     fn adjust_allocation<'b>(
330         ecx: &InterpCx<'mir, 'tcx, Self>,
331         id: AllocId,
332         alloc: Cow<'b, Allocation>,
333         kind: Option<MemoryKind<Self::MemoryKind>>,
334     ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>>;
335
336     fn eval_inline_asm(
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")
343     }
344
345     /// Hook for performing extra checks on a memory read access.
346     ///
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
349     /// need to mutate.
350     #[inline(always)]
351     fn before_memory_read(
352         _tcx: TyCtxt<'tcx>,
353         _machine: &Self,
354         _alloc_extra: &Self::AllocExtra,
355         _prov: (AllocId, Self::ProvenanceExtra),
356         _range: AllocRange,
357     ) -> InterpResult<'tcx> {
358         Ok(())
359     }
360
361     /// Hook for performing extra checks on a memory write access.
362     #[inline(always)]
363     fn before_memory_write(
364         _tcx: TyCtxt<'tcx>,
365         _machine: &mut Self,
366         _alloc_extra: &mut Self::AllocExtra,
367         _prov: (AllocId, Self::ProvenanceExtra),
368         _range: AllocRange,
369     ) -> InterpResult<'tcx> {
370         Ok(())
371     }
372
373     /// Hook for performing extra operations on a memory deallocation.
374     #[inline(always)]
375     fn before_memory_deallocation(
376         _tcx: TyCtxt<'tcx>,
377         _machine: &mut Self,
378         _alloc_extra: &mut Self::AllocExtra,
379         _prov: (AllocId, Self::ProvenanceExtra),
380         _range: AllocRange,
381     ) -> InterpResult<'tcx> {
382         Ok(())
383     }
384
385     /// Executes a retagging operation for a single pointer.
386     /// Returns the possibly adjusted pointer.
387     #[inline]
388     fn retag_ptr_value(
389         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
390         _kind: mir::RetagKind,
391         val: &ImmTy<'tcx, Self::Provenance>,
392     ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
393         Ok(val.clone())
394     }
395
396     /// Executes a retagging operation on a compound value.
397     /// Replaces all pointers stored in the given place.
398     #[inline]
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> {
404         Ok(())
405     }
406
407     /// Called immediately before a new stack frame gets pushed.
408     fn init_frame_extra(
409         ecx: &mut InterpCx<'mir, 'tcx, Self>,
410         frame: Frame<'mir, 'tcx, Self::Provenance>,
411     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
412
413     /// Borrow the current thread's stack.
414     fn stack<'a>(
415         ecx: &'a InterpCx<'mir, 'tcx, Self>,
416     ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>];
417
418     /// Mutably borrow the current thread's stack.
419     fn stack_mut<'a>(
420         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
421     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>>;
422
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> {
425         Ok(())
426     }
427
428     /// Called immediately after a stack frame got popped, but before jumping back to the caller.
429     /// The `locals` have already been destroyed!
430     fn after_stack_pop(
431         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
432         _frame: Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,
433         unwinding: bool,
434     ) -> InterpResult<'tcx, StackPopJump> {
435         // By default, we do not support unwinding from panics
436         assert!(!unwinding);
437         Ok(StackPopJump::Normal)
438     }
439 }
440
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 = ();
446
447     type ExtraFnVal = !;
448
449     type MemoryMap =
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
452
453     type AllocExtra = ();
454     type FrameExtra = ();
455
456     #[inline(always)]
457     fn use_addr_for_alignment_check(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
458         // We do not support `use_addr`.
459         false
460     }
461
462     #[inline(always)]
463     fn checked_binop_checks_overflow(_ecx: &InterpCx<$mir, $tcx, Self>) -> bool {
464         true
465     }
466
467     #[inline(always)]
468     fn call_extra_fn(
469         _ecx: &mut InterpCx<$mir, $tcx, Self>,
470         fn_val: !,
471         _abi: CallAbi,
472         _args: &[OpTy<$tcx>],
473         _destination: &PlaceTy<$tcx, Self::Provenance>,
474         _target: Option<mir::BasicBlock>,
475         _unwind: StackPopUnwind,
476     ) -> InterpResult<$tcx> {
477         match fn_val {}
478     }
479
480     #[inline(always)]
481     fn adjust_allocation<'b>(
482         _ecx: &InterpCx<$mir, $tcx, Self>,
483         _id: AllocId,
484         alloc: Cow<'b, Allocation>,
485         _kind: Option<MemoryKind<Self::MemoryKind>>,
486     ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
487         Ok(alloc)
488     }
489
490     fn extern_static_base_pointer(
491         ecx: &InterpCx<$mir, $tcx, Self>,
492         def_id: DefId,
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))
496     }
497
498     #[inline(always)]
499     fn adjust_alloc_base_pointer(
500         _ecx: &InterpCx<$mir, $tcx, Self>,
501         ptr: Pointer<AllocId>,
502     ) -> Pointer<AllocId> {
503         ptr
504     }
505
506     #[inline(always)]
507     fn ptr_from_addr_cast(
508         _ecx: &InterpCx<$mir, $tcx, Self>,
509         addr: u64,
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))
515     }
516
517     #[inline(always)]
518     fn ptr_get_alloc(
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, ()))
525     }
526 }