]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/const_eval/machine.rs
Auto merge of #86335 - CDirkx:ipv4-in-ipv6, r=dtolnay
[rust.git] / compiler / rustc_mir / src / const_eval / machine.rs
1 use rustc_middle::mir;
2 use rustc_middle::ty::{self, Ty};
3 use std::borrow::Borrow;
4 use std::collections::hash_map::Entry;
5 use std::hash::Hash;
6
7 use rustc_data_structures::fx::FxHashMap;
8 use std::fmt;
9
10 use rustc_ast::Mutability;
11 use rustc_hir::def_id::DefId;
12 use rustc_middle::mir::AssertMessage;
13 use rustc_session::Limit;
14 use rustc_span::symbol::{sym, Symbol};
15 use rustc_target::abi::{Align, Size};
16 use rustc_target::spec::abi::Abi;
17
18 use crate::interpret::{
19     self, compile_time_machine, AllocId, Allocation, Frame, ImmTy, InterpCx, InterpResult, OpTy,
20     PlaceTy, Scalar, StackPopUnwind,
21 };
22
23 use super::error::*;
24
25 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
26     /// "Intercept" a function call to a panic-related function
27     /// because we have something special to do for it.
28     /// If this returns successfully (`Ok`), the function should just be evaluated normally.
29     fn hook_panic_fn(
30         &mut self,
31         instance: ty::Instance<'tcx>,
32         args: &[OpTy<'tcx>],
33     ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
34         // The list of functions we handle here must be in sync with
35         // `is_lang_panic_fn` in `transform/check_consts/mod.rs`.
36         let def_id = instance.def_id();
37         if Some(def_id) == self.tcx.lang_items().panic_fn()
38             || Some(def_id) == self.tcx.lang_items().panic_str()
39             || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
40         {
41             // &str
42             assert!(args.len() == 1);
43
44             let msg_place = self.deref_operand(&args[0])?;
45             let msg = Symbol::intern(self.read_str(&msg_place)?);
46             let span = self.find_closest_untracked_caller_location();
47             let (file, line, col) = self.location_triple_for_span(span);
48             return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
49         } else if Some(def_id) == self.tcx.lang_items().panic_fmt()
50             || Some(def_id) == self.tcx.lang_items().begin_panic_fmt()
51         {
52             // For panic_fmt, call const_panic_fmt instead.
53             if let Some(const_panic_fmt) = self.tcx.lang_items().const_panic_fmt() {
54                 return Ok(Some(
55                     ty::Instance::resolve(
56                         *self.tcx,
57                         ty::ParamEnv::reveal_all(),
58                         const_panic_fmt,
59                         self.tcx.intern_substs(&[]),
60                     )
61                     .unwrap()
62                     .unwrap(),
63                 ));
64             }
65         }
66         Ok(None)
67     }
68 }
69
70 /// Extra machine state for CTFE, and the Machine instance
71 pub struct CompileTimeInterpreter<'mir, 'tcx> {
72     /// For now, the number of terminators that can be evaluated before we throw a resource
73     /// exhaustion error.
74     ///
75     /// Setting this to `0` disables the limit and allows the interpreter to run forever.
76     pub steps_remaining: usize,
77
78     /// The virtual call stack.
79     pub(crate) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
80 }
81
82 #[derive(Copy, Clone, Debug)]
83 pub struct MemoryExtra {
84     /// We need to make sure consts never point to anything mutable, even recursively. That is
85     /// relied on for pattern matching on consts with references.
86     /// To achieve this, two pieces have to work together:
87     /// * Interning makes everything outside of statics immutable.
88     /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
89     /// This boolean here controls the second part.
90     pub(super) can_access_statics: bool,
91 }
92
93 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
94     pub(super) fn new(const_eval_limit: Limit) -> Self {
95         CompileTimeInterpreter { steps_remaining: const_eval_limit.0, stack: Vec::new() }
96     }
97 }
98
99 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
100     #[inline(always)]
101     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
102     where
103         K: Borrow<Q>,
104     {
105         FxHashMap::contains_key(self, k)
106     }
107
108     #[inline(always)]
109     fn insert(&mut self, k: K, v: V) -> Option<V> {
110         FxHashMap::insert(self, k, v)
111     }
112
113     #[inline(always)]
114     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
115     where
116         K: Borrow<Q>,
117     {
118         FxHashMap::remove(self, k)
119     }
120
121     #[inline(always)]
122     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
123         self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
124     }
125
126     #[inline(always)]
127     fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
128         match self.get(&k) {
129             Some(v) => Ok(v),
130             None => {
131                 vacant()?;
132                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
133             }
134         }
135     }
136
137     #[inline(always)]
138     fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
139         match self.entry(k) {
140             Entry::Occupied(e) => Ok(e.into_mut()),
141             Entry::Vacant(e) => {
142                 let v = vacant()?;
143                 Ok(e.insert(v))
144             }
145         }
146     }
147 }
148
149 crate type CompileTimeEvalContext<'mir, 'tcx> =
150     InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
151
152 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
153 pub enum MemoryKind {
154     Heap,
155 }
156
157 impl fmt::Display for MemoryKind {
158     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159         match self {
160             MemoryKind::Heap => write!(f, "heap allocation"),
161         }
162     }
163 }
164
165 impl interpret::MayLeak for MemoryKind {
166     #[inline(always)]
167     fn may_leak(self) -> bool {
168         match self {
169             MemoryKind::Heap => false,
170         }
171     }
172 }
173
174 impl interpret::MayLeak for ! {
175     #[inline(always)]
176     fn may_leak(self) -> bool {
177         // `self` is uninhabited
178         self
179     }
180 }
181
182 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
183     fn guaranteed_eq(&mut self, a: Scalar, b: Scalar) -> bool {
184         match (a, b) {
185             // Comparisons between integers are always known.
186             (Scalar::Int { .. }, Scalar::Int { .. }) => a == b,
187             // Equality with integers can never be known for sure.
188             (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => false,
189             // FIXME: return `true` for when both sides are the same pointer, *except* that
190             // some things (like functions and vtables) do not have stable addresses
191             // so we need to be careful around them (see e.g. #73722).
192             (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
193         }
194     }
195
196     fn guaranteed_ne(&mut self, a: Scalar, b: Scalar) -> bool {
197         match (a, b) {
198             // Comparisons between integers are always known.
199             (Scalar::Int(_), Scalar::Int(_)) => a != b,
200             // Comparisons of abstract pointers with null pointers are known if the pointer
201             // is in bounds, because if they are in bounds, the pointer can't be null.
202             // Inequality with integers other than null can never be known for sure.
203             (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
204                 int.is_null() && !self.memory.ptr_may_be_null(ptr.into())
205             }
206             // FIXME: return `true` for at least some comparisons where we can reliably
207             // determine the result of runtime inequality tests at compile-time.
208             // Examples include comparison of addresses in different static items.
209             (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
210         }
211     }
212 }
213
214 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
215     compile_time_machine!(<'mir, 'tcx>);
216
217     type MemoryKind = MemoryKind;
218
219     type MemoryExtra = MemoryExtra;
220
221     const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
222
223     fn load_mir(
224         ecx: &InterpCx<'mir, 'tcx, Self>,
225         instance: ty::InstanceDef<'tcx>,
226     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
227         match instance {
228             ty::InstanceDef::Item(def) => {
229                 if ecx.tcx.is_ctfe_mir_available(def.did) {
230                     Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
231                 } else {
232                     let path = ecx.tcx.def_path_str(def.did);
233                     Err(ConstEvalErrKind::NeedsRfc(format!("calling extern function `{}`", path))
234                         .into())
235                 }
236             }
237             _ => Ok(ecx.tcx.instance_mir(instance)),
238         }
239     }
240
241     fn find_mir_or_eval_fn(
242         ecx: &mut InterpCx<'mir, 'tcx, Self>,
243         instance: ty::Instance<'tcx>,
244         _abi: Abi,
245         args: &[OpTy<'tcx>],
246         _ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
247         _unwind: StackPopUnwind, // unwinding is not supported in consts
248     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
249         debug!("find_mir_or_eval_fn: {:?}", instance);
250
251         // Only check non-glue functions
252         if let ty::InstanceDef::Item(def) = instance.def {
253             // Execution might have wandered off into other crates, so we cannot do a stability-
254             // sensitive check here.  But we can at least rule out functions that are not const
255             // at all.
256             if !ecx.tcx.is_const_fn_raw(def.did) {
257                 // allow calling functions marked with #[default_method_body_is_const].
258                 if !ecx.tcx.has_attr(def.did, sym::default_method_body_is_const) {
259                     // Some functions we support even if they are non-const -- but avoid testing
260                     // that for const fn!
261                     if let Some(new_instance) = ecx.hook_panic_fn(instance, args)? {
262                         // We call another const fn instead.
263                         return Self::find_mir_or_eval_fn(
264                             ecx,
265                             new_instance,
266                             _abi,
267                             args,
268                             _ret,
269                             _unwind,
270                         );
271                     } else {
272                         // We certainly do *not* want to actually call the fn
273                         // though, so be sure we return here.
274                         throw_unsup_format!("calling non-const function `{}`", instance)
275                     }
276                 }
277             }
278         }
279         // This is a const fn. Call it.
280         Ok(Some(ecx.load_mir(instance.def, None)?))
281     }
282
283     fn call_intrinsic(
284         ecx: &mut InterpCx<'mir, 'tcx, Self>,
285         instance: ty::Instance<'tcx>,
286         args: &[OpTy<'tcx>],
287         ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
288         _unwind: StackPopUnwind,
289     ) -> InterpResult<'tcx> {
290         // Shared intrinsics.
291         if ecx.emulate_intrinsic(instance, args, ret)? {
292             return Ok(());
293         }
294         let intrinsic_name = ecx.tcx.item_name(instance.def_id());
295
296         // CTFE-specific intrinsics.
297         let (dest, ret) = match ret {
298             None => {
299                 return Err(ConstEvalErrKind::NeedsRfc(format!(
300                     "calling intrinsic `{}`",
301                     intrinsic_name
302                 ))
303                 .into());
304             }
305             Some(p) => p,
306         };
307         match intrinsic_name {
308             sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
309                 let a = ecx.read_immediate(&args[0])?.to_scalar()?;
310                 let b = ecx.read_immediate(&args[1])?.to_scalar()?;
311                 let cmp = if intrinsic_name == sym::ptr_guaranteed_eq {
312                     ecx.guaranteed_eq(a, b)
313                 } else {
314                     ecx.guaranteed_ne(a, b)
315                 };
316                 ecx.write_scalar(Scalar::from_bool(cmp), dest)?;
317             }
318             sym::const_allocate => {
319                 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
320                 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
321
322                 let align = match Align::from_bytes(align) {
323                     Ok(a) => a,
324                     Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
325                 };
326
327                 let ptr = ecx.memory.allocate(
328                     Size::from_bytes(size as u64),
329                     align,
330                     interpret::MemoryKind::Machine(MemoryKind::Heap),
331                 )?;
332                 ecx.write_pointer(ptr, dest)?;
333             }
334             _ => {
335                 return Err(ConstEvalErrKind::NeedsRfc(format!(
336                     "calling intrinsic `{}`",
337                     intrinsic_name
338                 ))
339                 .into());
340             }
341         }
342
343         ecx.go_to_block(ret);
344         Ok(())
345     }
346
347     fn assert_panic(
348         ecx: &mut InterpCx<'mir, 'tcx, Self>,
349         msg: &AssertMessage<'tcx>,
350         _unwind: Option<mir::BasicBlock>,
351     ) -> InterpResult<'tcx> {
352         use rustc_middle::mir::AssertKind::*;
353         // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
354         let eval_to_int =
355             |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
356         let err = match msg {
357             BoundsCheck { ref len, ref index } => {
358                 let len = eval_to_int(len)?;
359                 let index = eval_to_int(index)?;
360                 BoundsCheck { len, index }
361             }
362             Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
363             OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
364             DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
365             RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
366             ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
367             ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
368         };
369         Err(ConstEvalErrKind::AssertFailure(err).into())
370     }
371
372     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
373         Err(ConstEvalErrKind::Abort(msg).into())
374     }
375
376     fn binary_ptr_op(
377         _ecx: &InterpCx<'mir, 'tcx, Self>,
378         _bin_op: mir::BinOp,
379         _left: &ImmTy<'tcx>,
380         _right: &ImmTy<'tcx>,
381     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
382         Err(ConstEvalErrKind::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
383     }
384
385     fn box_alloc(
386         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
387         _dest: &PlaceTy<'tcx>,
388     ) -> InterpResult<'tcx> {
389         Err(ConstEvalErrKind::NeedsRfc("heap allocations via `box` keyword".to_string()).into())
390     }
391
392     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
393         // The step limit has already been hit in a previous call to `before_terminator`.
394         if ecx.machine.steps_remaining == 0 {
395             return Ok(());
396         }
397
398         ecx.machine.steps_remaining -= 1;
399         if ecx.machine.steps_remaining == 0 {
400             throw_exhaust!(StepLimitReached)
401         }
402
403         Ok(())
404     }
405
406     #[inline(always)]
407     fn init_frame_extra(
408         ecx: &mut InterpCx<'mir, 'tcx, Self>,
409         frame: Frame<'mir, 'tcx>,
410     ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
411         // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
412         if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
413             throw_exhaust!(StackFrameLimitReached)
414         } else {
415             Ok(frame)
416         }
417     }
418
419     #[inline(always)]
420     fn stack(
421         ecx: &'a InterpCx<'mir, 'tcx, Self>,
422     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
423         &ecx.machine.stack
424     }
425
426     #[inline(always)]
427     fn stack_mut(
428         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
429     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
430         &mut ecx.machine.stack
431     }
432
433     fn before_access_global(
434         memory_extra: &MemoryExtra,
435         alloc_id: AllocId,
436         allocation: &Allocation,
437         static_def_id: Option<DefId>,
438         is_write: bool,
439     ) -> InterpResult<'tcx> {
440         if is_write {
441             // Write access. These are never allowed, but we give a targeted error message.
442             if allocation.mutability == Mutability::Not {
443                 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
444             } else {
445                 Err(ConstEvalErrKind::ModifiedGlobal.into())
446             }
447         } else {
448             // Read access. These are usually allowed, with some exceptions.
449             if memory_extra.can_access_statics {
450                 // Machine configuration allows us read from anything (e.g., `static` initializer).
451                 Ok(())
452             } else if static_def_id.is_some() {
453                 // Machine configuration does not allow us to read statics
454                 // (e.g., `const` initializer).
455                 // See const_eval::machine::MemoryExtra::can_access_statics for why
456                 // this check is so important: if we could read statics, we could read pointers
457                 // to mutable allocations *inside* statics. These allocations are not themselves
458                 // statics, so pointers to them can get around the check in `validity.rs`.
459                 Err(ConstEvalErrKind::ConstAccessesStatic.into())
460             } else {
461                 // Immutable global, this read is fine.
462                 // But make sure we never accept a read from something mutable, that would be
463                 // unsound. The reason is that as the content of this allocation may be different
464                 // now and at run-time, so if we permit reading now we might return the wrong value.
465                 assert_eq!(allocation.mutability, Mutability::Not);
466                 Ok(())
467             }
468         }
469     }
470 }
471
472 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
473 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
474 // at the bottom of this file.