]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/const_eval/machine.rs
Rollup merge of #106823 - m-ou-se:format-args-as-str-guarantees, r=dtolnay
[rust.git] / compiler / rustc_const_eval / src / const_eval / machine.rs
1 use rustc_hir::def::DefKind;
2 use rustc_hir::{LangItem, CRATE_HIR_ID};
3 use rustc_middle::mir;
4 use rustc_middle::mir::interpret::PointerArithmetic;
5 use rustc_middle::ty::layout::FnAbiOf;
6 use rustc_middle::ty::{self, Ty, TyCtxt};
7 use rustc_session::lint::builtin::INVALID_ALIGNMENT;
8 use std::borrow::Borrow;
9 use std::hash::Hash;
10 use std::ops::ControlFlow;
11
12 use rustc_data_structures::fx::FxIndexMap;
13 use rustc_data_structures::fx::IndexEntry;
14 use std::fmt;
15
16 use rustc_ast::Mutability;
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::mir::AssertMessage;
19 use rustc_session::Limit;
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_target::abi::{Align, Size};
22 use rustc_target::spec::abi::Abi as CallAbi;
23
24 use crate::interpret::{
25     self, compile_time_machine, AllocId, ConstAllocation, FnVal, Frame, ImmTy, InterpCx,
26     InterpResult, OpTy, PlaceTy, Pointer, Scalar, StackPopUnwind,
27 };
28
29 use super::error::*;
30
31 /// Extra machine state for CTFE, and the Machine instance
32 pub struct CompileTimeInterpreter<'mir, 'tcx> {
33     /// For now, the number of terminators that can be evaluated before we throw a resource
34     /// exhaustion error.
35     ///
36     /// Setting this to `0` disables the limit and allows the interpreter to run forever.
37     pub(super) steps_remaining: usize,
38
39     /// The virtual call stack.
40     pub(super) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
41
42     /// We need to make sure consts never point to anything mutable, even recursively. That is
43     /// relied on for pattern matching on consts with references.
44     /// To achieve this, two pieces have to work together:
45     /// * Interning makes everything outside of statics immutable.
46     /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
47     /// This boolean here controls the second part.
48     pub(super) can_access_statics: bool,
49
50     /// Whether to check alignment during evaluation.
51     pub(super) check_alignment: CheckAlignment,
52 }
53
54 #[derive(Copy, Clone)]
55 pub enum CheckAlignment {
56     /// Ignore alignment when following relocations.
57     /// This is mainly used in interning.
58     No,
59     /// Hard error when dereferencing a misaligned pointer.
60     Error,
61     /// Emit a future incompat lint when dereferencing a misaligned pointer.
62     FutureIncompat,
63 }
64
65 impl CheckAlignment {
66     pub fn should_check(&self) -> bool {
67         match self {
68             CheckAlignment::No => false,
69             CheckAlignment::Error | CheckAlignment::FutureIncompat => true,
70         }
71     }
72 }
73
74 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
75     pub(crate) fn new(
76         const_eval_limit: Limit,
77         can_access_statics: bool,
78         check_alignment: CheckAlignment,
79     ) -> Self {
80         CompileTimeInterpreter {
81             steps_remaining: const_eval_limit.0,
82             stack: Vec::new(),
83             can_access_statics,
84             check_alignment,
85         }
86     }
87 }
88
89 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
90     #[inline(always)]
91     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
92     where
93         K: Borrow<Q>,
94     {
95         FxIndexMap::contains_key(self, k)
96     }
97
98     #[inline(always)]
99     fn insert(&mut self, k: K, v: V) -> Option<V> {
100         FxIndexMap::insert(self, k, v)
101     }
102
103     #[inline(always)]
104     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
105     where
106         K: Borrow<Q>,
107     {
108         FxIndexMap::remove(self, k)
109     }
110
111     #[inline(always)]
112     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
113         self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
114     }
115
116     #[inline(always)]
117     fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
118         match self.get(&k) {
119             Some(v) => Ok(v),
120             None => {
121                 vacant()?;
122                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
123             }
124         }
125     }
126
127     #[inline(always)]
128     fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
129         match self.entry(k) {
130             IndexEntry::Occupied(e) => Ok(e.into_mut()),
131             IndexEntry::Vacant(e) => {
132                 let v = vacant()?;
133                 Ok(e.insert(v))
134             }
135         }
136     }
137 }
138
139 pub(crate) type CompileTimeEvalContext<'mir, 'tcx> =
140     InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
141
142 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
143 pub enum MemoryKind {
144     Heap,
145 }
146
147 impl fmt::Display for MemoryKind {
148     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149         match self {
150             MemoryKind::Heap => write!(f, "heap allocation"),
151         }
152     }
153 }
154
155 impl interpret::MayLeak for MemoryKind {
156     #[inline(always)]
157     fn may_leak(self) -> bool {
158         match self {
159             MemoryKind::Heap => false,
160         }
161     }
162 }
163
164 impl interpret::MayLeak for ! {
165     #[inline(always)]
166     fn may_leak(self) -> bool {
167         // `self` is uninhabited
168         self
169     }
170 }
171
172 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
173     /// "Intercept" a function call, because we have something special to do for it.
174     /// All `#[rustc_do_not_const_check]` functions should be hooked here.
175     /// If this returns `Some` function, which may be `instance` or a different function with
176     /// compatible arguments, then evaluation should continue with that function.
177     /// If this returns `None`, the function call has been handled and the function has returned.
178     fn hook_special_const_fn(
179         &mut self,
180         instance: ty::Instance<'tcx>,
181         args: &[OpTy<'tcx>],
182         dest: &PlaceTy<'tcx>,
183         ret: Option<mir::BasicBlock>,
184     ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
185         let def_id = instance.def_id();
186
187         if Some(def_id) == self.tcx.lang_items().panic_display()
188             || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
189         {
190             // &str or &&str
191             assert!(args.len() == 1);
192
193             let mut msg_place = self.deref_operand(&args[0])?;
194             while msg_place.layout.ty.is_ref() {
195                 msg_place = self.deref_operand(&msg_place.into())?;
196             }
197
198             let msg = Symbol::intern(self.read_str(&msg_place)?);
199             let span = self.find_closest_untracked_caller_location();
200             let (file, line, col) = self.location_triple_for_span(span);
201             return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
202         } else if Some(def_id) == self.tcx.lang_items().panic_fmt() {
203             // For panic_fmt, call const_panic_fmt instead.
204             let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, None);
205             let new_instance = ty::Instance::resolve(
206                 *self.tcx,
207                 ty::ParamEnv::reveal_all(),
208                 const_def_id,
209                 instance.substs,
210             )
211             .unwrap()
212             .unwrap();
213
214             return Ok(Some(new_instance));
215         } else if Some(def_id) == self.tcx.lang_items().align_offset_fn() {
216             // For align_offset, we replace the function call if the pointer has no address.
217             match self.align_offset(instance, args, dest, ret)? {
218                 ControlFlow::Continue(()) => return Ok(Some(instance)),
219                 ControlFlow::Break(()) => return Ok(None),
220             }
221         }
222         Ok(Some(instance))
223     }
224
225     /// `align_offset(ptr, target_align)` needs special handling in const eval, because the pointer
226     /// may not have an address.
227     ///
228     /// If `ptr` does have a known address, then we return `Continue(())` and the function call should
229     /// proceed as normal.
230     ///
231     /// If `ptr` doesn't have an address, but its underlying allocation's alignment is at most
232     /// `target_align`, then we call the function again with an dummy address relative to the
233     /// allocation.
234     ///
235     /// If `ptr` doesn't have an address and `target_align` is stricter than the underlying
236     /// allocation's alignment, then we return `usize::MAX` immediately.
237     fn align_offset(
238         &mut self,
239         instance: ty::Instance<'tcx>,
240         args: &[OpTy<'tcx>],
241         dest: &PlaceTy<'tcx>,
242         ret: Option<mir::BasicBlock>,
243     ) -> InterpResult<'tcx, ControlFlow<()>> {
244         assert_eq!(args.len(), 2);
245
246         let ptr = self.read_pointer(&args[0])?;
247         let target_align = self.read_scalar(&args[1])?.to_machine_usize(self)?;
248
249         if !target_align.is_power_of_two() {
250             throw_ub_format!("`align_offset` called with non-power-of-two align: {}", target_align);
251         }
252
253         match self.ptr_try_get_alloc_id(ptr) {
254             Ok((alloc_id, offset, _extra)) => {
255                 let (_size, alloc_align, _kind) = self.get_alloc_info(alloc_id);
256
257                 if target_align <= alloc_align.bytes() {
258                     // Extract the address relative to the allocation base that is definitely
259                     // sufficiently aligned and call `align_offset` again.
260                     let addr = ImmTy::from_uint(offset.bytes(), args[0].layout).into();
261                     let align = ImmTy::from_uint(target_align, args[1].layout).into();
262                     let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty())?;
263
264                     // We replace the entire function call with a "tail call".
265                     // Note that this happens before the frame of the original function
266                     // is pushed on the stack.
267                     self.eval_fn_call(
268                         FnVal::Instance(instance),
269                         (CallAbi::Rust, fn_abi),
270                         &[addr, align],
271                         /* with_caller_location = */ false,
272                         dest,
273                         ret,
274                         StackPopUnwind::NotAllowed,
275                     )?;
276                     Ok(ControlFlow::Break(()))
277                 } else {
278                     // Not alignable in const, return `usize::MAX`.
279                     let usize_max = Scalar::from_machine_usize(self.machine_usize_max(), self);
280                     self.write_scalar(usize_max, dest)?;
281                     self.return_to_block(ret)?;
282                     Ok(ControlFlow::Break(()))
283                 }
284             }
285             Err(_addr) => {
286                 // The pointer has an address, continue with function call.
287                 Ok(ControlFlow::Continue(()))
288             }
289         }
290     }
291
292     /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
293     fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
294         Ok(match (a, b) {
295             // Comparisons between integers are always known.
296             (Scalar::Int { .. }, Scalar::Int { .. }) => {
297                 if a == b {
298                     1
299                 } else {
300                     0
301                 }
302             }
303             // Comparisons of abstract pointers with null pointers are known if the pointer
304             // is in bounds, because if they are in bounds, the pointer can't be null.
305             // Inequality with integers other than null can never be known for sure.
306             (Scalar::Int(int), ptr @ Scalar::Ptr(..))
307             | (ptr @ Scalar::Ptr(..), Scalar::Int(int))
308                 if int.is_null() && !self.scalar_may_be_null(ptr)? =>
309             {
310                 0
311             }
312             // Equality with integers can never be known for sure.
313             (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => 2,
314             // FIXME: return a `1` for when both sides are the same pointer, *except* that
315             // some things (like functions and vtables) do not have stable addresses
316             // so we need to be careful around them (see e.g. #73722).
317             // FIXME: return `0` for at least some comparisons where we can reliably
318             // determine the result of runtime inequality tests at compile-time.
319             // Examples include comparison of addresses in different static items.
320             (Scalar::Ptr(..), Scalar::Ptr(..)) => 2,
321         })
322     }
323 }
324
325 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
326     compile_time_machine!(<'mir, 'tcx>);
327
328     type MemoryKind = MemoryKind;
329
330     const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
331
332     #[inline(always)]
333     fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> CheckAlignment {
334         ecx.machine.check_alignment
335     }
336
337     #[inline(always)]
338     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
339         ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks
340     }
341
342     fn alignment_check_failed(
343         ecx: &InterpCx<'mir, 'tcx, Self>,
344         has: Align,
345         required: Align,
346         check: CheckAlignment,
347     ) -> InterpResult<'tcx, ()> {
348         let err = err_ub!(AlignmentCheckFailed { has, required }).into();
349         match check {
350             CheckAlignment::Error => Err(err),
351             CheckAlignment::No => span_bug!(
352                 ecx.cur_span(),
353                 "`alignment_check_failed` called when no alignment check requested"
354             ),
355             CheckAlignment::FutureIncompat => {
356                 let err = ConstEvalErr::new(ecx, err, None);
357                 ecx.tcx.struct_span_lint_hir(
358                     INVALID_ALIGNMENT,
359                     ecx.stack().iter().find_map(|frame| frame.lint_root()).unwrap_or(CRATE_HIR_ID),
360                     err.span,
361                     err.error.to_string(),
362                     |db| {
363                         err.decorate(db, |_| {});
364                         db
365                     },
366                 );
367                 Ok(())
368             }
369         }
370     }
371
372     fn load_mir(
373         ecx: &InterpCx<'mir, 'tcx, Self>,
374         instance: ty::InstanceDef<'tcx>,
375     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
376         match instance {
377             ty::InstanceDef::Item(def) => {
378                 if ecx.tcx.is_ctfe_mir_available(def.did) {
379                     Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
380                 } else if ecx.tcx.def_kind(def.did) == DefKind::AssocConst {
381                     let guar = ecx.tcx.sess.delay_span_bug(
382                         rustc_span::DUMMY_SP,
383                         "This is likely a const item that is missing from its impl",
384                     );
385                     throw_inval!(AlreadyReported(guar));
386                 } else {
387                     // `find_mir_or_eval_fn` checks that this is a const fn before even calling us,
388                     // so this should be unreachable.
389                     let path = ecx.tcx.def_path_str(def.did);
390                     bug!("trying to call extern function `{path}` at compile-time");
391                 }
392             }
393             _ => Ok(ecx.tcx.instance_mir(instance)),
394         }
395     }
396
397     fn find_mir_or_eval_fn(
398         ecx: &mut InterpCx<'mir, 'tcx, Self>,
399         instance: ty::Instance<'tcx>,
400         _abi: CallAbi,
401         args: &[OpTy<'tcx>],
402         dest: &PlaceTy<'tcx>,
403         ret: Option<mir::BasicBlock>,
404         _unwind: StackPopUnwind, // unwinding is not supported in consts
405     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
406         debug!("find_mir_or_eval_fn: {:?}", instance);
407
408         // Only check non-glue functions
409         if let ty::InstanceDef::Item(def) = instance.def {
410             // Execution might have wandered off into other crates, so we cannot do a stability-
411             // sensitive check here. But we can at least rule out functions that are not const
412             // at all.
413             if !ecx.tcx.is_const_fn_raw(def.did) {
414                 // allow calling functions inside a trait marked with #[const_trait].
415                 if !ecx.tcx.is_const_default_method(def.did) {
416                     // We certainly do *not* want to actually call the fn
417                     // though, so be sure we return here.
418                     throw_unsup_format!("calling non-const function `{}`", instance)
419                 }
420             }
421
422             let Some(new_instance) = ecx.hook_special_const_fn(instance, args, dest, ret)? else {
423                 return Ok(None);
424             };
425
426             if new_instance != instance {
427                 // We call another const fn instead.
428                 // However, we return the *original* instance to make backtraces work out
429                 // (and we hope this does not confuse the FnAbi checks too much).
430                 return Ok(Self::find_mir_or_eval_fn(
431                     ecx,
432                     new_instance,
433                     _abi,
434                     args,
435                     dest,
436                     ret,
437                     _unwind,
438                 )?
439                 .map(|(body, _instance)| (body, instance)));
440             }
441         }
442
443         // This is a const fn. Call it.
444         Ok(Some((ecx.load_mir(instance.def, None)?, instance)))
445     }
446
447     fn call_intrinsic(
448         ecx: &mut InterpCx<'mir, 'tcx, Self>,
449         instance: ty::Instance<'tcx>,
450         args: &[OpTy<'tcx>],
451         dest: &PlaceTy<'tcx, Self::Provenance>,
452         target: Option<mir::BasicBlock>,
453         _unwind: StackPopUnwind,
454     ) -> InterpResult<'tcx> {
455         // Shared intrinsics.
456         if ecx.emulate_intrinsic(instance, args, dest, target)? {
457             return Ok(());
458         }
459         let intrinsic_name = ecx.tcx.item_name(instance.def_id());
460
461         // CTFE-specific intrinsics.
462         let Some(ret) = target else {
463             throw_unsup_format!("intrinsic `{intrinsic_name}` is not supported at compile-time");
464         };
465         match intrinsic_name {
466             sym::ptr_guaranteed_cmp => {
467                 let a = ecx.read_scalar(&args[0])?;
468                 let b = ecx.read_scalar(&args[1])?;
469                 let cmp = ecx.guaranteed_cmp(a, b)?;
470                 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
471             }
472             sym::const_allocate => {
473                 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
474                 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
475
476                 let align = match Align::from_bytes(align) {
477                     Ok(a) => a,
478                     Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
479                 };
480
481                 let ptr = ecx.allocate_ptr(
482                     Size::from_bytes(size as u64),
483                     align,
484                     interpret::MemoryKind::Machine(MemoryKind::Heap),
485                 )?;
486                 ecx.write_pointer(ptr, dest)?;
487             }
488             sym::const_deallocate => {
489                 let ptr = ecx.read_pointer(&args[0])?;
490                 let size = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
491                 let align = ecx.read_scalar(&args[2])?.to_machine_usize(ecx)?;
492
493                 let size = Size::from_bytes(size);
494                 let align = match Align::from_bytes(align) {
495                     Ok(a) => a,
496                     Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
497                 };
498
499                 // If an allocation is created in an another const,
500                 // we don't deallocate it.
501                 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?;
502                 let is_allocated_in_another_const = matches!(
503                     ecx.tcx.try_get_global_alloc(alloc_id),
504                     Some(interpret::GlobalAlloc::Memory(_))
505                 );
506
507                 if !is_allocated_in_another_const {
508                     ecx.deallocate_ptr(
509                         ptr,
510                         Some((size, align)),
511                         interpret::MemoryKind::Machine(MemoryKind::Heap),
512                     )?;
513                 }
514             }
515             _ => {
516                 throw_unsup_format!(
517                     "intrinsic `{intrinsic_name}` is not supported at compile-time"
518                 );
519             }
520         }
521
522         ecx.go_to_block(ret);
523         Ok(())
524     }
525
526     fn assert_panic(
527         ecx: &mut InterpCx<'mir, 'tcx, Self>,
528         msg: &AssertMessage<'tcx>,
529         _unwind: Option<mir::BasicBlock>,
530     ) -> InterpResult<'tcx> {
531         use rustc_middle::mir::AssertKind::*;
532         // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
533         let eval_to_int =
534             |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
535         let err = match msg {
536             BoundsCheck { len, index } => {
537                 let len = eval_to_int(len)?;
538                 let index = eval_to_int(index)?;
539                 BoundsCheck { len, index }
540             }
541             Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
542             OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
543             DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
544             RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
545             ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
546             ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
547         };
548         Err(ConstEvalErrKind::AssertFailure(err).into())
549     }
550
551     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
552         Err(ConstEvalErrKind::Abort(msg).into())
553     }
554
555     fn binary_ptr_op(
556         _ecx: &InterpCx<'mir, 'tcx, Self>,
557         _bin_op: mir::BinOp,
558         _left: &ImmTy<'tcx>,
559         _right: &ImmTy<'tcx>,
560     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
561         throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
562     }
563
564     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
565         // The step limit has already been hit in a previous call to `before_terminator`.
566         if ecx.machine.steps_remaining == 0 {
567             return Ok(());
568         }
569
570         ecx.machine.steps_remaining -= 1;
571         if ecx.machine.steps_remaining == 0 {
572             throw_exhaust!(StepLimitReached)
573         }
574
575         Ok(())
576     }
577
578     #[inline(always)]
579     fn expose_ptr(
580         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
581         _ptr: Pointer<AllocId>,
582     ) -> InterpResult<'tcx> {
583         // This is only reachable with -Zunleash-the-miri-inside-of-you.
584         throw_unsup_format!("exposing pointers is not possible at compile-time")
585     }
586
587     #[inline(always)]
588     fn init_frame_extra(
589         ecx: &mut InterpCx<'mir, 'tcx, Self>,
590         frame: Frame<'mir, 'tcx>,
591     ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
592         // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
593         if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
594             throw_exhaust!(StackFrameLimitReached)
595         } else {
596             Ok(frame)
597         }
598     }
599
600     #[inline(always)]
601     fn stack<'a>(
602         ecx: &'a InterpCx<'mir, 'tcx, Self>,
603     ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
604         &ecx.machine.stack
605     }
606
607     #[inline(always)]
608     fn stack_mut<'a>(
609         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
610     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
611         &mut ecx.machine.stack
612     }
613
614     fn before_access_global(
615         _tcx: TyCtxt<'tcx>,
616         machine: &Self,
617         alloc_id: AllocId,
618         alloc: ConstAllocation<'tcx>,
619         static_def_id: Option<DefId>,
620         is_write: bool,
621     ) -> InterpResult<'tcx> {
622         let alloc = alloc.inner();
623         if is_write {
624             // Write access. These are never allowed, but we give a targeted error message.
625             if alloc.mutability == Mutability::Not {
626                 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
627             } else {
628                 Err(ConstEvalErrKind::ModifiedGlobal.into())
629             }
630         } else {
631             // Read access. These are usually allowed, with some exceptions.
632             if machine.can_access_statics {
633                 // Machine configuration allows us read from anything (e.g., `static` initializer).
634                 Ok(())
635             } else if static_def_id.is_some() {
636                 // Machine configuration does not allow us to read statics
637                 // (e.g., `const` initializer).
638                 // See const_eval::machine::MemoryExtra::can_access_statics for why
639                 // this check is so important: if we could read statics, we could read pointers
640                 // to mutable allocations *inside* statics. These allocations are not themselves
641                 // statics, so pointers to them can get around the check in `validity.rs`.
642                 Err(ConstEvalErrKind::ConstAccessesStatic.into())
643             } else {
644                 // Immutable global, this read is fine.
645                 // But make sure we never accept a read from something mutable, that would be
646                 // unsound. The reason is that as the content of this allocation may be different
647                 // now and at run-time, so if we permit reading now we might return the wrong value.
648                 assert_eq!(alloc.mutability, Mutability::Not);
649                 Ok(())
650             }
651         }
652     }
653 }
654
655 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
656 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
657 // at the bottom of this file.