1 //! An interpreter for MIR used in CTFE and by miri.
4 macro_rules! err_unsup {
6 $crate::mir::interpret::InterpError::Unsupported(
7 $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
13 macro_rules! err_unsup_format {
14 ($($tt:tt)*) => { err_unsup!(Unsupported(format!($($tt)*))) };
18 macro_rules! err_inval {
20 $crate::mir::interpret::InterpError::InvalidProgram(
21 $crate::mir::interpret::InvalidProgramInfo::$($tt)*
29 $crate::mir::interpret::InterpError::UndefinedBehavior(
30 $crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
36 macro_rules! err_ub_format {
37 ($($tt:tt)*) => { err_ub!(Ub(format!($($tt)*))) };
41 macro_rules! err_exhaust {
43 $crate::mir::interpret::InterpError::ResourceExhaustion(
44 $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
50 macro_rules! err_machine_stop {
52 $crate::mir::interpret::InterpError::MachineStop(Box::new($($tt)*))
56 // In the `throw_*` macros, avoid `return` to make them work with `try {}`.
58 macro_rules! throw_unsup {
59 ($($tt:tt)*) => { Err::<!, _>(err_unsup!($($tt)*))? };
63 macro_rules! throw_unsup_format {
64 ($($tt:tt)*) => { throw_unsup!(Unsupported(format!($($tt)*))) };
68 macro_rules! throw_inval {
69 ($($tt:tt)*) => { Err::<!, _>(err_inval!($($tt)*))? };
73 macro_rules! throw_ub {
74 ($($tt:tt)*) => { Err::<!, _>(err_ub!($($tt)*))? };
78 macro_rules! throw_ub_format {
79 ($($tt:tt)*) => { throw_ub!(Ub(format!($($tt)*))) };
83 macro_rules! throw_exhaust {
84 ($($tt:tt)*) => { Err::<!, _>(err_exhaust!($($tt)*))? };
88 macro_rules! throw_machine_stop {
89 ($($tt:tt)*) => { Err::<!, _>(err_machine_stop!($($tt)*))? };
98 use std::convert::TryFrom;
101 use std::num::NonZeroU32;
102 use std::sync::atomic::{AtomicU32, Ordering};
104 use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt};
105 use rustc_ast::ast::LitKind;
106 use rustc_data_structures::fx::FxHashMap;
107 use rustc_data_structures::sync::{HashMapExt, Lock};
108 use rustc_data_structures::tiny_list::TinyList;
109 use rustc_hir::def_id::DefId;
110 use rustc_macros::HashStable;
111 use rustc_serialize::{Decodable, Encodable, Encoder};
112 use rustc_target::abi::{Endian, Size};
115 use crate::ty::codec::TyDecoder;
116 use crate::ty::subst::GenericArgKind;
117 use crate::ty::{self, Instance, Ty, TyCtxt};
119 pub use self::error::{
120 struct_error, CheckInAllocMsg, ConstEvalRawResult, ConstEvalResult, ErrorHandled, InterpError,
121 InterpErrorInfo, InterpResult, InvalidProgramInfo, MachineStopType, ResourceExhaustionInfo,
122 UndefinedBehaviorInfo, UninitBytesAccess, UnsupportedOpInfo,
125 pub use self::value::{get_slice_bytes, ConstValue, RawConst, Scalar, ScalarMaybeUninit};
127 pub use self::allocation::{Allocation, AllocationExtra, InitMask, Relocations};
129 pub use self::pointer::{Pointer, PointerArithmetic};
131 /// Uniquely identifies one of the following:
134 /// - A const fn where all arguments (if any) are zero-sized types
135 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable)]
136 #[derive(HashStable, Lift)]
137 pub struct GlobalId<'tcx> {
138 /// For a constant or static, the `Instance` of the item itself.
139 /// For a promoted global, the `Instance` of the function they belong to.
140 pub instance: ty::Instance<'tcx>,
142 /// The index for promoted globals within their function's `mir::Body`.
143 pub promoted: Option<mir::Promoted>,
146 /// Input argument for `tcx.lit_to_const`.
147 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable)]
148 pub struct LitToConstInput<'tcx> {
149 /// The absolute value of the resultant constant.
150 pub lit: &'tcx LitKind,
151 /// The type of the constant.
153 /// If the constant is negative.
157 /// Error type for `tcx.lit_to_const`.
158 #[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable)]
159 pub enum LitToConstError {
160 /// The literal's inferred type did not match the expected `ty` in the input.
161 /// This is used for graceful error handling (`delay_span_bug`) in
162 /// type checking (`Const::from_anon_const`).
168 #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
169 pub struct AllocId(pub u64);
171 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
172 // all the Miri types.
173 impl fmt::Debug for AllocId {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 if f.alternate() { write!(f, "a{}", self.0) } else { write!(f, "alloc{}", self.0) }
179 impl fmt::Display for AllocId {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 fmt::Debug::fmt(self, f)
185 impl rustc_serialize::UseSpecializedEncodable for AllocId {}
186 impl rustc_serialize::UseSpecializedDecodable for AllocId {}
188 #[derive(RustcDecodable, RustcEncodable)]
189 enum AllocDiscriminant {
195 pub fn specialized_encode_alloc_id<'tcx, E: Encoder>(
199 ) -> Result<(), E::Error> {
200 match tcx.global_alloc(alloc_id) {
201 GlobalAlloc::Memory(alloc) => {
202 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
203 AllocDiscriminant::Alloc.encode(encoder)?;
204 alloc.encode(encoder)?;
206 GlobalAlloc::Function(fn_instance) => {
207 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
208 AllocDiscriminant::Fn.encode(encoder)?;
209 fn_instance.encode(encoder)?;
211 GlobalAlloc::Static(did) => {
212 assert!(!tcx.is_thread_local_static(did));
213 // References to statics doesn't need to know about their allocations,
214 // just about its `DefId`.
215 AllocDiscriminant::Static.encode(encoder)?;
216 did.encode(encoder)?;
222 // Used to avoid infinite recursion when decoding cyclic allocations.
223 type DecodingSessionId = NonZeroU32;
228 InProgressNonAlloc(TinyList<DecodingSessionId>),
229 InProgress(TinyList<DecodingSessionId>, AllocId),
233 pub struct AllocDecodingState {
234 // For each `AllocId`, we keep track of which decoding state it's currently in.
235 decoding_state: Vec<Lock<State>>,
236 // The offsets of each allocation in the data stream.
237 data_offsets: Vec<u32>,
240 impl AllocDecodingState {
241 pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
242 static DECODER_SESSION_ID: AtomicU32 = AtomicU32::new(0);
243 let counter = DECODER_SESSION_ID.fetch_add(1, Ordering::SeqCst);
245 // Make sure this is never zero.
246 let session_id = DecodingSessionId::new((counter & 0x7FFFFFFF) + 1).unwrap();
248 AllocDecodingSession { state: self, session_id }
251 pub fn new(data_offsets: Vec<u32>) -> Self {
252 let decoding_state = vec![Lock::new(State::Empty); data_offsets.len()];
254 Self { decoding_state, data_offsets }
258 #[derive(Copy, Clone)]
259 pub struct AllocDecodingSession<'s> {
260 state: &'s AllocDecodingState,
261 session_id: DecodingSessionId,
264 impl<'s> AllocDecodingSession<'s> {
265 /// Decodes an `AllocId` in a thread-safe way.
266 pub fn decode_alloc_id<D>(&self, decoder: &mut D) -> Result<AllocId, D::Error>
270 // Read the index of the allocation.
271 let idx = usize::try_from(decoder.read_u32()?).unwrap();
272 let pos = usize::try_from(self.state.data_offsets[idx]).unwrap();
274 // Decode the `AllocDiscriminant` now so that we know if we have to reserve an
276 let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
277 let alloc_kind = AllocDiscriminant::decode(decoder)?;
278 Ok((alloc_kind, decoder.position()))
281 // Check the decoding state to see if it's already decoded or if we should
284 let mut entry = self.state.decoding_state[idx].lock();
287 State::Done(alloc_id) => {
290 ref mut entry @ State::Empty => {
291 // We are allowed to decode.
293 AllocDiscriminant::Alloc => {
294 // If this is an allocation, we need to reserve an
295 // `AllocId` so we can decode cyclic graphs.
296 let alloc_id = decoder.tcx().reserve_alloc_id();
298 State::InProgress(TinyList::new_single(self.session_id), alloc_id);
301 AllocDiscriminant::Fn | AllocDiscriminant::Static => {
302 // Fns and statics cannot be cyclic, and their `AllocId`
303 // is determined later by interning.
305 State::InProgressNonAlloc(TinyList::new_single(self.session_id));
310 State::InProgressNonAlloc(ref mut sessions) => {
311 if sessions.contains(&self.session_id) {
312 bug!("this should be unreachable");
314 // Start decoding concurrently.
315 sessions.insert(self.session_id);
319 State::InProgress(ref mut sessions, alloc_id) => {
320 if sessions.contains(&self.session_id) {
324 // Start decoding concurrently.
325 sessions.insert(self.session_id);
332 // Now decode the actual data.
333 let alloc_id = decoder.with_position(pos, |decoder| {
335 AllocDiscriminant::Alloc => {
336 let alloc = <&'tcx Allocation as Decodable>::decode(decoder)?;
337 // We already have a reserved `AllocId`.
338 let alloc_id = alloc_id.unwrap();
339 trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc);
340 decoder.tcx().set_alloc_id_same_memory(alloc_id, alloc);
343 AllocDiscriminant::Fn => {
344 assert!(alloc_id.is_none());
345 trace!("creating fn alloc ID");
346 let instance = ty::Instance::decode(decoder)?;
347 trace!("decoded fn alloc instance: {:?}", instance);
348 let alloc_id = decoder.tcx().create_fn_alloc(instance);
351 AllocDiscriminant::Static => {
352 assert!(alloc_id.is_none());
353 trace!("creating extern static alloc ID");
354 let did = DefId::decode(decoder)?;
355 trace!("decoded static def-ID: {:?}", did);
356 let alloc_id = decoder.tcx().create_static_alloc(did);
362 self.state.decoding_state[idx].with_lock(|entry| {
363 *entry = State::Done(alloc_id);
370 /// An allocation in the global (tcx-managed) memory can be either a function pointer,
371 /// a static, or a "real" allocation with some data in it.
372 #[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]
373 pub enum GlobalAlloc<'tcx> {
374 /// The alloc ID is used as a function pointer.
375 Function(Instance<'tcx>),
376 /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
377 /// This is also used to break the cycle in recursive statics.
379 /// The alloc ID points to memory.
380 Memory(&'tcx Allocation),
383 impl GlobalAlloc<'tcx> {
384 /// Panics if the `GlobalAlloc` does not refer to an `GlobalAlloc::Memory`
387 pub fn unwrap_memory(&self) -> &'tcx Allocation {
389 GlobalAlloc::Memory(mem) => mem,
390 _ => bug!("expected memory, got {:?}", self),
394 /// Panics if the `GlobalAlloc` is not `GlobalAlloc::Function`
397 pub fn unwrap_fn(&self) -> Instance<'tcx> {
399 GlobalAlloc::Function(instance) => instance,
400 _ => bug!("expected function, got {:?}", self),
405 crate struct AllocMap<'tcx> {
406 /// Maps `AllocId`s to their corresponding allocations.
407 alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
409 /// Used to ensure that statics and functions only get one associated `AllocId`.
410 /// Should never contain a `GlobalAlloc::Memory`!
412 // FIXME: Should we just have two separate dedup maps for statics and functions each?
413 dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
415 /// The `AllocId` to assign to the next requested ID.
416 /// Always incremented; never gets smaller.
420 impl<'tcx> AllocMap<'tcx> {
421 crate fn new() -> Self {
422 AllocMap { alloc_map: Default::default(), dedup: Default::default(), next_id: AllocId(0) }
424 fn reserve(&mut self) -> AllocId {
425 let next = self.next_id;
426 self.next_id.0 = self.next_id.0.checked_add(1).expect(
427 "You overflowed a u64 by incrementing by 1... \
428 You've just earned yourself a free drink if we ever meet. \
429 Seriously, how did you do that?!",
435 impl<'tcx> TyCtxt<'tcx> {
436 /// Obtains a new allocation ID that can be referenced but does not
437 /// yet have an allocation backing it.
439 /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
440 /// an `AllocId` from a query.
441 pub fn reserve_alloc_id(&self) -> AllocId {
442 self.alloc_map.lock().reserve()
445 /// Reserves a new ID *if* this allocation has not been dedup-reserved before.
446 /// Should only be used for function pointers and statics, we don't want
447 /// to dedup IDs for "real" memory!
448 fn reserve_and_set_dedup(&self, alloc: GlobalAlloc<'tcx>) -> AllocId {
449 let mut alloc_map = self.alloc_map.lock();
451 GlobalAlloc::Function(..) | GlobalAlloc::Static(..) => {}
452 GlobalAlloc::Memory(..) => bug!("Trying to dedup-reserve memory with real data!"),
454 if let Some(&alloc_id) = alloc_map.dedup.get(&alloc) {
457 let id = alloc_map.reserve();
458 debug!("creating alloc {:?} with id {}", alloc, id);
459 alloc_map.alloc_map.insert(id, alloc.clone());
460 alloc_map.dedup.insert(alloc, id);
464 /// Generates an `AllocId` for a static or return a cached one in case this function has been
465 /// called on the same static before.
466 pub fn create_static_alloc(&self, static_id: DefId) -> AllocId {
467 self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
470 /// Generates an `AllocId` for a function. Depending on the function type,
471 /// this might get deduplicated or assigned a new ID each time.
472 pub fn create_fn_alloc(&self, instance: Instance<'tcx>) -> AllocId {
473 // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
474 // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
475 // duplicated across crates.
476 // We thus generate a new `AllocId` for every mention of a function. This means that
477 // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
478 // However, formatting code relies on function identity (see #58320), so we only do
479 // this for generic functions. Lifetime parameters are ignored.
480 let is_generic = instance.substs.into_iter().any(|kind| match kind.unpack() {
481 GenericArgKind::Lifetime(_) => false,
486 let mut alloc_map = self.alloc_map.lock();
487 let id = alloc_map.reserve();
488 alloc_map.alloc_map.insert(id, GlobalAlloc::Function(instance));
492 self.reserve_and_set_dedup(GlobalAlloc::Function(instance))
496 /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical
497 /// `Allocation` with a different `AllocId`.
498 /// Statics with identical content will still point to the same `Allocation`, i.e.,
499 /// their data will be deduplicated through `Allocation` interning -- but they
500 /// are different places in memory and as such need different IDs.
501 pub fn create_memory_alloc(&self, mem: &'tcx Allocation) -> AllocId {
502 let id = self.reserve_alloc_id();
503 self.set_alloc_id_memory(id, mem);
507 /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
508 /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
509 /// illegal and will likely ICE.
510 /// This function exists to allow const eval to detect the difference between evaluation-
511 /// local dangling pointers and allocations in constants/statics.
513 pub fn get_global_alloc(&self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
514 self.alloc_map.lock().alloc_map.get(&id).cloned()
519 /// Panics in case the `AllocId` is dangling. Since that is impossible for `AllocId`s in
520 /// constants (as all constants must pass interning and validation that check for dangling
521 /// ids), this function is frequently used throughout rustc, but should not be used within
523 pub fn global_alloc(&self, id: AllocId) -> GlobalAlloc<'tcx> {
524 match self.get_global_alloc(id) {
525 Some(alloc) => alloc,
526 None => bug!("could not find allocation for {}", id),
530 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
531 /// call this function twice, even with the same `Allocation` will ICE the compiler.
532 pub fn set_alloc_id_memory(&self, id: AllocId, mem: &'tcx Allocation) {
533 if let Some(old) = self.alloc_map.lock().alloc_map.insert(id, GlobalAlloc::Memory(mem)) {
534 bug!("tried to set allocation ID {}, but it was already existing as {:#?}", id, old);
538 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
539 /// twice for the same `(AllocId, Allocation)` pair.
540 fn set_alloc_id_same_memory(&self, id: AllocId, mem: &'tcx Allocation) {
541 self.alloc_map.lock().alloc_map.insert_same(id, GlobalAlloc::Memory(mem));
545 ////////////////////////////////////////////////////////////////////////////////
546 // Methods to access integers in the target endianness
547 ////////////////////////////////////////////////////////////////////////////////
550 pub fn write_target_uint(
552 mut target: &mut [u8],
554 ) -> Result<(), io::Error> {
555 let len = target.len();
557 Endian::Little => target.write_uint128::<LittleEndian>(data, len),
558 Endian::Big => target.write_uint128::<BigEndian>(data, len),
563 pub fn read_target_uint(endianness: Endian, mut source: &[u8]) -> Result<u128, io::Error> {
565 Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
566 Endian::Big => source.read_uint128::<BigEndian>(source.len()),
570 ////////////////////////////////////////////////////////////////////////////////
571 // Methods to facilitate working with signed integers stored in a u128
572 ////////////////////////////////////////////////////////////////////////////////
574 /// Truncates `value` to `size` bits and then sign-extend it to 128 bits
575 /// (i.e., if it is negative, fill with 1's on the left).
577 pub fn sign_extend(value: u128, size: Size) -> u128 {
578 let size = size.bits();
580 // Truncated until nothing is left.
584 let shift = 128 - size;
585 // Shift the unsigned value to the left, then shift back to the right as signed
586 // (essentially fills with FF on the left).
587 (((value << shift) as i128) >> shift) as u128
590 /// Truncates `value` to `size` bits.
592 pub fn truncate(value: u128, size: Size) -> u128 {
593 let size = size.bits();
595 // Truncated until nothing is left.
598 let shift = 128 - size;
599 // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
600 (value << shift) >> shift
603 /// Computes the unsigned absolute value without wrapping or panicking.
605 pub fn uabs(value: i64) -> u64 {
606 // The only tricky part here is if value == i64::MIN. In that case,
607 // wrapping_abs() returns i64::MIN == -2^63. Casting this value to a u64
608 // gives 2^63, the correct value.
609 value.wrapping_abs() as u64