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_panic {
43 $crate::mir::interpret::InterpError::Panic(
44 $crate::mir::interpret::PanicInfo::$($tt)*
50 macro_rules! err_exhaust {
52 $crate::mir::interpret::InterpError::ResourceExhaustion(
53 $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
59 macro_rules! throw_unsup {
60 ($($tt:tt)*) => { return Err(err_unsup!($($tt)*).into()) };
64 macro_rules! throw_unsup_format {
65 ($($tt:tt)*) => { throw_unsup!(Unsupported(format!($($tt)*))) };
69 macro_rules! throw_inval {
70 ($($tt:tt)*) => { return Err(err_inval!($($tt)*).into()) };
74 macro_rules! throw_ub {
75 ($($tt:tt)*) => { return Err(err_ub!($($tt)*).into()) };
79 macro_rules! throw_ub_format {
80 ($($tt:tt)*) => { throw_ub!(Ub(format!($($tt)*))) };
84 macro_rules! throw_panic {
85 ($($tt:tt)*) => { return Err(err_panic!($($tt)*).into()) };
89 macro_rules! throw_exhaust {
90 ($($tt:tt)*) => { return Err(err_exhaust!($($tt)*).into()) };
94 macro_rules! throw_machine_stop {
96 return Err($crate::mir::interpret::InterpError::MachineStop(Box::new($($tt)*)).into())
105 pub use self::error::{
106 InterpErrorInfo, InterpResult, InterpError, AssertMessage, ConstEvalErr, struct_error,
107 FrameInfo, ConstEvalRawResult, ConstEvalResult, ErrorHandled, PanicInfo, UnsupportedOpInfo,
108 InvalidProgramInfo, ResourceExhaustionInfo, UndefinedBehaviorInfo,
111 pub use self::value::{Scalar, ScalarMaybeUndef, RawConst, ConstValue, get_slice_bytes};
113 pub use self::allocation::{Allocation, AllocationExtra, Relocations, UndefMask};
115 pub use self::pointer::{Pointer, PointerArithmetic, CheckInAllocMsg};
118 use crate::hir::def_id::DefId;
119 use crate::ty::{self, TyCtxt, Instance, subst::GenericArgKind};
120 use crate::ty::codec::TyDecoder;
121 use crate::ty::layout::{self, Size};
124 use std::num::NonZeroU32;
125 use std::sync::atomic::{AtomicU32, Ordering};
126 use rustc_serialize::{Encoder, Decodable, Encodable};
127 use rustc_data_structures::fx::FxHashMap;
128 use rustc_data_structures::sync::{Lock, HashMapExt};
129 use rustc_data_structures::tiny_list::TinyList;
130 use rustc_macros::HashStable;
131 use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian};
133 /// Uniquely identifies one of the following:
136 /// - A const fn where all arguments (if any) are zero-sized types
137 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable)]
138 #[derive(HashStable, Lift)]
139 pub struct GlobalId<'tcx> {
140 /// For a constant or static, the `Instance` of the item itself.
141 /// For a promoted global, the `Instance` of the function they belong to.
142 pub instance: ty::Instance<'tcx>,
144 /// The index for promoted globals within their function's `mir::Body`.
145 pub promoted: Option<mir::Promoted>,
148 #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
149 pub struct AllocId(pub u64);
151 impl rustc_serialize::UseSpecializedEncodable for AllocId {}
152 impl rustc_serialize::UseSpecializedDecodable for AllocId {}
154 #[derive(RustcDecodable, RustcEncodable)]
155 enum AllocDiscriminant {
161 pub fn specialized_encode_alloc_id<'tcx, E: Encoder>(
165 ) -> Result<(), E::Error> {
166 let alloc: GlobalAlloc<'tcx> = tcx.alloc_map.lock().get(alloc_id)
167 .expect("no value for given alloc ID");
169 GlobalAlloc::Memory(alloc) => {
170 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
171 AllocDiscriminant::Alloc.encode(encoder)?;
172 alloc.encode(encoder)?;
174 GlobalAlloc::Function(fn_instance) => {
175 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
176 AllocDiscriminant::Fn.encode(encoder)?;
177 fn_instance.encode(encoder)?;
179 GlobalAlloc::Static(did) => {
180 // References to statics doesn't need to know about their allocations,
181 // just about its `DefId`.
182 AllocDiscriminant::Static.encode(encoder)?;
183 did.encode(encoder)?;
189 // Used to avoid infinite recursion when decoding cyclic allocations.
190 type DecodingSessionId = NonZeroU32;
195 InProgressNonAlloc(TinyList<DecodingSessionId>),
196 InProgress(TinyList<DecodingSessionId>, AllocId),
200 pub struct AllocDecodingState {
201 // For each `AllocId`, we keep track of which decoding state it's currently in.
202 decoding_state: Vec<Lock<State>>,
203 // The offsets of each allocation in the data stream.
204 data_offsets: Vec<u32>,
207 impl AllocDecodingState {
208 pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
209 static DECODER_SESSION_ID: AtomicU32 = AtomicU32::new(0);
210 let counter = DECODER_SESSION_ID.fetch_add(1, Ordering::SeqCst);
212 // Make sure this is never zero.
213 let session_id = DecodingSessionId::new((counter & 0x7FFFFFFF) + 1).unwrap();
215 AllocDecodingSession {
221 pub fn new(data_offsets: Vec<u32>) -> Self {
222 let decoding_state = vec![Lock::new(State::Empty); data_offsets.len()];
231 #[derive(Copy, Clone)]
232 pub struct AllocDecodingSession<'s> {
233 state: &'s AllocDecodingState,
234 session_id: DecodingSessionId,
237 impl<'s> AllocDecodingSession<'s> {
238 /// Decodes an `AllocId` in a thread-safe way.
239 pub fn decode_alloc_id<D>(&self, decoder: &mut D) -> Result<AllocId, D::Error>
243 // Read the index of the allocation.
244 let idx = decoder.read_u32()? as usize;
245 let pos = self.state.data_offsets[idx] as usize;
247 // Decode the `AllocDiscriminant` now so that we know if we have to reserve an
249 let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
250 let alloc_kind = AllocDiscriminant::decode(decoder)?;
251 Ok((alloc_kind, decoder.position()))
254 // Check the decoding state to see if it's already decoded or if we should
257 let mut entry = self.state.decoding_state[idx].lock();
260 State::Done(alloc_id) => {
263 ref mut entry @ State::Empty => {
264 // We are allowed to decode.
266 AllocDiscriminant::Alloc => {
267 // If this is an allocation, we need to reserve an
268 // `AllocId` so we can decode cyclic graphs.
269 let alloc_id = decoder.tcx().alloc_map.lock().reserve();
270 *entry = State::InProgress(
271 TinyList::new_single(self.session_id),
275 AllocDiscriminant::Fn | AllocDiscriminant::Static => {
276 // Fns and statics cannot be cyclic, and their `AllocId`
277 // is determined later by interning.
278 *entry = State::InProgressNonAlloc(
279 TinyList::new_single(self.session_id));
284 State::InProgressNonAlloc(ref mut sessions) => {
285 if sessions.contains(&self.session_id) {
286 bug!("this should be unreachable");
288 // Start decoding concurrently.
289 sessions.insert(self.session_id);
293 State::InProgress(ref mut sessions, alloc_id) => {
294 if sessions.contains(&self.session_id) {
298 // Start decoding concurrently.
299 sessions.insert(self.session_id);
306 // Now decode the actual data.
307 let alloc_id = decoder.with_position(pos, |decoder| {
309 AllocDiscriminant::Alloc => {
310 let alloc = <&'tcx Allocation as Decodable>::decode(decoder)?;
311 // We already have a reserved `AllocId`.
312 let alloc_id = alloc_id.unwrap();
313 trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc);
314 decoder.tcx().alloc_map.lock().set_alloc_id_same_memory(alloc_id, alloc);
317 AllocDiscriminant::Fn => {
318 assert!(alloc_id.is_none());
319 trace!("creating fn alloc ID");
320 let instance = ty::Instance::decode(decoder)?;
321 trace!("decoded fn alloc instance: {:?}", instance);
322 let alloc_id = decoder.tcx().alloc_map.lock().create_fn_alloc(instance);
325 AllocDiscriminant::Static => {
326 assert!(alloc_id.is_none());
327 trace!("creating extern static alloc ID");
328 let did = DefId::decode(decoder)?;
329 trace!("decoded static def-ID: {:?}", did);
330 let alloc_id = decoder.tcx().alloc_map.lock().create_static_alloc(did);
336 self.state.decoding_state[idx].with_lock(|entry| {
337 *entry = State::Done(alloc_id);
344 impl fmt::Display for AllocId {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 write!(f, "{}", self.0)
350 /// An allocation in the global (tcx-managed) memory can be either a function pointer,
351 /// a static, or a "real" allocation with some data in it.
352 #[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]
353 pub enum GlobalAlloc<'tcx> {
354 /// The alloc ID is used as a function pointer.
355 Function(Instance<'tcx>),
356 /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
357 /// This is also used to break the cycle in recursive statics.
359 /// The alloc ID points to memory.
360 Memory(&'tcx Allocation),
363 pub struct AllocMap<'tcx> {
364 /// Maps `AllocId`s to their corresponding allocations.
365 alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
367 /// Used to ensure that statics and functions only get one associated `AllocId`.
368 /// Should never contain a `GlobalAlloc::Memory`!
370 // FIXME: Should we just have two separate dedup maps for statics and functions each?
371 dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
373 /// The `AllocId` to assign to the next requested ID.
374 /// Always incremented; never gets smaller.
378 impl<'tcx> AllocMap<'tcx> {
379 pub fn new() -> Self {
381 alloc_map: Default::default(),
382 dedup: Default::default(),
387 /// Obtains a new allocation ID that can be referenced but does not
388 /// yet have an allocation backing it.
390 /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
391 /// an `AllocId` from a query.
395 let next = self.next_id;
396 self.next_id.0 = self.next_id.0
398 .expect("You overflowed a u64 by incrementing by 1... \
399 You've just earned yourself a free drink if we ever meet. \
400 Seriously, how did you do that?!");
404 /// Reserves a new ID *if* this allocation has not been dedup-reserved before.
405 /// Should only be used for function pointers and statics, we don't want
406 /// to dedup IDs for "real" memory!
407 fn reserve_and_set_dedup(&mut self, alloc: GlobalAlloc<'tcx>) -> AllocId {
409 GlobalAlloc::Function(..) | GlobalAlloc::Static(..) => {},
410 GlobalAlloc::Memory(..) => bug!("Trying to dedup-reserve memory with real data!"),
412 if let Some(&alloc_id) = self.dedup.get(&alloc) {
415 let id = self.reserve();
416 debug!("creating alloc {:?} with id {}", alloc, id);
417 self.alloc_map.insert(id, alloc.clone());
418 self.dedup.insert(alloc, id);
422 /// Generates an `AllocId` for a static or return a cached one in case this function has been
423 /// called on the same static before.
424 pub fn create_static_alloc(&mut self, static_id: DefId) -> AllocId {
425 self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
428 /// Generates an `AllocId` for a function. Depending on the function type,
429 /// this might get deduplicated or assigned a new ID each time.
430 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> AllocId {
431 // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
432 // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
433 // duplicated across crates.
434 // We thus generate a new `AllocId` for every mention of a function. This means that
435 // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
436 // However, formatting code relies on function identity (see #58320), so we only do
437 // this for generic functions. Lifetime parameters are ignored.
438 let is_generic = instance.substs.into_iter().any(|kind| {
439 match kind.unpack() {
440 GenericArgKind::Lifetime(_) => false,
446 let id = self.reserve();
447 self.alloc_map.insert(id, GlobalAlloc::Function(instance));
451 self.reserve_and_set_dedup(GlobalAlloc::Function(instance))
455 /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical
456 /// `Allocation` with a different `AllocId`.
457 /// Statics with identical content will still point to the same `Allocation`, i.e.,
458 /// their data will be deduplicated through `Allocation` interning -- but they
459 /// are different places in memory and as such need different IDs.
460 pub fn create_memory_alloc(&mut self, mem: &'tcx Allocation) -> AllocId {
461 let id = self.reserve();
462 self.set_alloc_id_memory(id, mem);
466 /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
467 /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
468 /// illegal and will likely ICE.
469 /// This function exists to allow const eval to detect the difference between evaluation-
470 /// local dangling pointers and allocations in constants/statics.
472 pub fn get(&self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
473 self.alloc_map.get(&id).cloned()
476 /// Panics if the `AllocId` does not refer to an `Allocation`
477 pub fn unwrap_memory(&self, id: AllocId) -> &'tcx Allocation {
479 Some(GlobalAlloc::Memory(mem)) => mem,
480 _ => bug!("expected allocation ID {} to point to memory", id),
484 /// Panics if the `AllocId` does not refer to a function
485 pub fn unwrap_fn(&self, id: AllocId) -> Instance<'tcx> {
487 Some(GlobalAlloc::Function(instance)) => instance,
488 _ => bug!("expected allocation ID {} to point to a function", id),
492 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
493 /// call this function twice, even with the same `Allocation` will ICE the compiler.
494 pub fn set_alloc_id_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
495 if let Some(old) = self.alloc_map.insert(id, GlobalAlloc::Memory(mem)) {
496 bug!("tried to set allocation ID {}, but it was already existing as {:#?}", id, old);
500 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
501 /// twice for the same `(AllocId, Allocation)` pair.
502 fn set_alloc_id_same_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
503 self.alloc_map.insert_same(id, GlobalAlloc::Memory(mem));
507 ////////////////////////////////////////////////////////////////////////////////
508 // Methods to access integers in the target endianness
509 ////////////////////////////////////////////////////////////////////////////////
512 pub fn write_target_uint(
513 endianness: layout::Endian,
514 mut target: &mut [u8],
516 ) -> Result<(), io::Error> {
517 let len = target.len();
519 layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
520 layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
525 pub fn read_target_uint(endianness: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
527 layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
528 layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
532 ////////////////////////////////////////////////////////////////////////////////
533 // Methods to facilitate working with signed integers stored in a u128
534 ////////////////////////////////////////////////////////////////////////////////
536 /// Truncates `value` to `size` bits and then sign-extend it to 128 bits
537 /// (i.e., if it is negative, fill with 1's on the left).
539 pub fn sign_extend(value: u128, size: Size) -> u128 {
540 let size = size.bits();
542 // Truncated until nothing is left.
546 let shift = 128 - size;
547 // Shift the unsigned value to the left, then shift back to the right as signed
548 // (essentially fills with FF on the left).
549 (((value << shift) as i128) >> shift) as u128
552 /// Truncates `value` to `size` bits.
554 pub fn truncate(value: u128, size: Size) -> u128 {
555 let size = size.bits();
557 // Truncated until nothing is left.
560 let shift = 128 - size;
561 // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
562 (value << shift) >> shift