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()) };
98 pub use self::error::{
99 InterpErrorInfo, InterpResult, InterpError, AssertMessage, ConstEvalErr, struct_error,
100 FrameInfo, ConstEvalRawResult, ConstEvalResult, ErrorHandled, PanicInfo, UnsupportedOpInfo,
101 InvalidProgramInfo, ResourceExhaustionInfo, UndefinedBehaviorInfo,
104 pub use self::value::{Scalar, ScalarMaybeUndef, RawConst, ConstValue, get_slice_bytes};
106 pub use self::allocation::{Allocation, AllocationExtra, Relocations, UndefMask};
108 pub use self::pointer::{Pointer, PointerArithmetic, CheckInAllocMsg};
111 use crate::hir::def_id::DefId;
112 use crate::ty::{self, TyCtxt, Instance, subst::GenericArgKind};
113 use crate::ty::codec::TyDecoder;
114 use crate::ty::layout::{self, Size};
117 use std::num::NonZeroU32;
118 use std::sync::atomic::{AtomicU32, Ordering};
119 use rustc_serialize::{Encoder, Decodable, Encodable};
120 use rustc_data_structures::fx::FxHashMap;
121 use rustc_data_structures::sync::{Lock, HashMapExt};
122 use rustc_data_structures::tiny_list::TinyList;
123 use rustc_macros::HashStable;
124 use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian};
126 /// Uniquely identifies one of the following:
129 /// - A const fn where all arguments (if any) are zero-sized types
130 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable)]
131 #[derive(HashStable, Lift)]
132 pub struct GlobalId<'tcx> {
133 /// For a constant or static, the `Instance` of the item itself.
134 /// For a promoted global, the `Instance` of the function they belong to.
135 pub instance: ty::Instance<'tcx>,
137 /// The index for promoted globals within their function's `mir::Body`.
138 pub promoted: Option<mir::Promoted>,
141 #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
142 pub struct AllocId(pub u64);
144 impl rustc_serialize::UseSpecializedEncodable for AllocId {}
145 impl rustc_serialize::UseSpecializedDecodable for AllocId {}
147 #[derive(RustcDecodable, RustcEncodable)]
148 enum AllocDiscriminant {
154 pub fn specialized_encode_alloc_id<'tcx, E: Encoder>(
158 ) -> Result<(), E::Error> {
159 let alloc: GlobalAlloc<'tcx> = tcx.alloc_map.lock().get(alloc_id)
160 .expect("no value for given alloc ID");
162 GlobalAlloc::Memory(alloc) => {
163 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
164 AllocDiscriminant::Alloc.encode(encoder)?;
165 alloc.encode(encoder)?;
167 GlobalAlloc::Function(fn_instance) => {
168 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
169 AllocDiscriminant::Fn.encode(encoder)?;
170 fn_instance.encode(encoder)?;
172 GlobalAlloc::Static(did) => {
173 // References to statics doesn't need to know about their allocations,
174 // just about its `DefId`.
175 AllocDiscriminant::Static.encode(encoder)?;
176 did.encode(encoder)?;
182 // Used to avoid infinite recursion when decoding cyclic allocations.
183 type DecodingSessionId = NonZeroU32;
188 InProgressNonAlloc(TinyList<DecodingSessionId>),
189 InProgress(TinyList<DecodingSessionId>, AllocId),
193 pub struct AllocDecodingState {
194 // For each `AllocId`, we keep track of which decoding state it's currently in.
195 decoding_state: Vec<Lock<State>>,
196 // The offsets of each allocation in the data stream.
197 data_offsets: Vec<u32>,
200 impl AllocDecodingState {
201 pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
202 static DECODER_SESSION_ID: AtomicU32 = AtomicU32::new(0);
203 let counter = DECODER_SESSION_ID.fetch_add(1, Ordering::SeqCst);
205 // Make sure this is never zero.
206 let session_id = DecodingSessionId::new((counter & 0x7FFFFFFF) + 1).unwrap();
208 AllocDecodingSession {
214 pub fn new(data_offsets: Vec<u32>) -> Self {
215 let decoding_state = vec![Lock::new(State::Empty); data_offsets.len()];
224 #[derive(Copy, Clone)]
225 pub struct AllocDecodingSession<'s> {
226 state: &'s AllocDecodingState,
227 session_id: DecodingSessionId,
230 impl<'s> AllocDecodingSession<'s> {
231 /// Decodes an `AllocId` in a thread-safe way.
232 pub fn decode_alloc_id<D>(&self, decoder: &mut D) -> Result<AllocId, D::Error>
236 // Read the index of the allocation.
237 let idx = decoder.read_u32()? as usize;
238 let pos = self.state.data_offsets[idx] as usize;
240 // Decode the `AllocDiscriminant` now so that we know if we have to reserve an
242 let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
243 let alloc_kind = AllocDiscriminant::decode(decoder)?;
244 Ok((alloc_kind, decoder.position()))
247 // Check the decoding state to see if it's already decoded or if we should
250 let mut entry = self.state.decoding_state[idx].lock();
253 State::Done(alloc_id) => {
256 ref mut entry @ State::Empty => {
257 // We are allowed to decode.
259 AllocDiscriminant::Alloc => {
260 // If this is an allocation, we need to reserve an
261 // `AllocId` so we can decode cyclic graphs.
262 let alloc_id = decoder.tcx().alloc_map.lock().reserve();
263 *entry = State::InProgress(
264 TinyList::new_single(self.session_id),
268 AllocDiscriminant::Fn | AllocDiscriminant::Static => {
269 // Fns and statics cannot be cyclic, and their `AllocId`
270 // is determined later by interning.
271 *entry = State::InProgressNonAlloc(
272 TinyList::new_single(self.session_id));
277 State::InProgressNonAlloc(ref mut sessions) => {
278 if sessions.contains(&self.session_id) {
279 bug!("this should be unreachable");
281 // Start decoding concurrently.
282 sessions.insert(self.session_id);
286 State::InProgress(ref mut sessions, alloc_id) => {
287 if sessions.contains(&self.session_id) {
291 // Start decoding concurrently.
292 sessions.insert(self.session_id);
299 // Now decode the actual data.
300 let alloc_id = decoder.with_position(pos, |decoder| {
302 AllocDiscriminant::Alloc => {
303 let alloc = <&'tcx Allocation as Decodable>::decode(decoder)?;
304 // We already have a reserved `AllocId`.
305 let alloc_id = alloc_id.unwrap();
306 trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc);
307 decoder.tcx().alloc_map.lock().set_alloc_id_same_memory(alloc_id, alloc);
310 AllocDiscriminant::Fn => {
311 assert!(alloc_id.is_none());
312 trace!("creating fn alloc ID");
313 let instance = ty::Instance::decode(decoder)?;
314 trace!("decoded fn alloc instance: {:?}", instance);
315 let alloc_id = decoder.tcx().alloc_map.lock().create_fn_alloc(instance);
318 AllocDiscriminant::Static => {
319 assert!(alloc_id.is_none());
320 trace!("creating extern static alloc ID");
321 let did = DefId::decode(decoder)?;
322 trace!("decoded static def-ID: {:?}", did);
323 let alloc_id = decoder.tcx().alloc_map.lock().create_static_alloc(did);
329 self.state.decoding_state[idx].with_lock(|entry| {
330 *entry = State::Done(alloc_id);
337 impl fmt::Display for AllocId {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 write!(f, "{}", self.0)
343 /// An allocation in the global (tcx-managed) memory can be either a function pointer,
344 /// a static, or a "real" allocation with some data in it.
345 #[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]
346 pub enum GlobalAlloc<'tcx> {
347 /// The alloc ID is used as a function pointer.
348 Function(Instance<'tcx>),
349 /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
350 /// This is also used to break the cycle in recursive statics.
352 /// The alloc ID points to memory.
353 Memory(&'tcx Allocation),
356 pub struct AllocMap<'tcx> {
357 /// Maps `AllocId`s to their corresponding allocations.
358 alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
360 /// Used to ensure that statics and functions only get one associated `AllocId`.
361 /// Should never contain a `GlobalAlloc::Memory`!
363 // FIXME: Should we just have two separate dedup maps for statics and functions each?
364 dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
366 /// The `AllocId` to assign to the next requested ID.
367 /// Always incremented; never gets smaller.
371 impl<'tcx> AllocMap<'tcx> {
372 pub fn new() -> Self {
374 alloc_map: Default::default(),
375 dedup: Default::default(),
380 /// Obtains a new allocation ID that can be referenced but does not
381 /// yet have an allocation backing it.
383 /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
384 /// an `AllocId` from a query.
388 let next = self.next_id;
389 self.next_id.0 = self.next_id.0
391 .expect("You overflowed a u64 by incrementing by 1... \
392 You've just earned yourself a free drink if we ever meet. \
393 Seriously, how did you do that?!");
397 /// Reserves a new ID *if* this allocation has not been dedup-reserved before.
398 /// Should only be used for function pointers and statics, we don't want
399 /// to dedup IDs for "real" memory!
400 fn reserve_and_set_dedup(&mut self, alloc: GlobalAlloc<'tcx>) -> AllocId {
402 GlobalAlloc::Function(..) | GlobalAlloc::Static(..) => {},
403 GlobalAlloc::Memory(..) => bug!("Trying to dedup-reserve memory with real data!"),
405 if let Some(&alloc_id) = self.dedup.get(&alloc) {
408 let id = self.reserve();
409 debug!("creating alloc {:?} with id {}", alloc, id);
410 self.alloc_map.insert(id, alloc.clone());
411 self.dedup.insert(alloc, id);
415 /// Generates an `AllocId` for a static or return a cached one in case this function has been
416 /// called on the same static before.
417 pub fn create_static_alloc(&mut self, static_id: DefId) -> AllocId {
418 self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
421 /// Generates an `AllocId` for a function. Depending on the function type,
422 /// this might get deduplicated or assigned a new ID each time.
423 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> AllocId {
424 // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
425 // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
426 // duplicated across crates.
427 // We thus generate a new `AllocId` for every mention of a function. This means that
428 // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
429 // However, formatting code relies on function identity (see #58320), so we only do
430 // this for generic functions. Lifetime parameters are ignored.
431 let is_generic = instance.substs.into_iter().any(|kind| {
432 match kind.unpack() {
433 GenericArgKind::Lifetime(_) => false,
439 let id = self.reserve();
440 self.alloc_map.insert(id, GlobalAlloc::Function(instance));
444 self.reserve_and_set_dedup(GlobalAlloc::Function(instance))
448 /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical
449 /// `Allocation` with a different `AllocId`.
450 /// Statics with identical content will still point to the same `Allocation`, i.e.,
451 /// their data will be deduplicated through `Allocation` interning -- but they
452 /// are different places in memory and as such need different IDs.
453 pub fn create_memory_alloc(&mut self, mem: &'tcx Allocation) -> AllocId {
454 let id = self.reserve();
455 self.set_alloc_id_memory(id, mem);
459 /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
460 /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
461 /// illegal and will likely ICE.
462 /// This function exists to allow const eval to detect the difference between evaluation-
463 /// local dangling pointers and allocations in constants/statics.
465 pub fn get(&self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
466 self.alloc_map.get(&id).cloned()
469 /// Panics if the `AllocId` does not refer to an `Allocation`
470 pub fn unwrap_memory(&self, id: AllocId) -> &'tcx Allocation {
472 Some(GlobalAlloc::Memory(mem)) => mem,
473 _ => bug!("expected allocation ID {} to point to memory", id),
477 /// Panics if the `AllocId` does not refer to a function
478 pub fn unwrap_fn(&self, id: AllocId) -> Instance<'tcx> {
480 Some(GlobalAlloc::Function(instance)) => instance,
481 _ => bug!("expected allocation ID {} to point to a function", id),
485 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
486 /// call this function twice, even with the same `Allocation` will ICE the compiler.
487 pub fn set_alloc_id_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
488 if let Some(old) = self.alloc_map.insert(id, GlobalAlloc::Memory(mem)) {
489 bug!("tried to set allocation ID {}, but it was already existing as {:#?}", id, old);
493 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
494 /// twice for the same `(AllocId, Allocation)` pair.
495 fn set_alloc_id_same_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
496 self.alloc_map.insert_same(id, GlobalAlloc::Memory(mem));
500 ////////////////////////////////////////////////////////////////////////////////
501 // Methods to access integers in the target endianness
502 ////////////////////////////////////////////////////////////////////////////////
505 pub fn write_target_uint(
506 endianness: layout::Endian,
507 mut target: &mut [u8],
509 ) -> Result<(), io::Error> {
510 let len = target.len();
512 layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
513 layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
518 pub fn read_target_uint(endianness: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
520 layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
521 layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
525 ////////////////////////////////////////////////////////////////////////////////
526 // Methods to facilitate working with signed integers stored in a u128
527 ////////////////////////////////////////////////////////////////////////////////
529 /// Truncates `value` to `size` bits and then sign-extend it to 128 bits
530 /// (i.e., if it is negative, fill with 1's on the left).
532 pub fn sign_extend(value: u128, size: Size) -> u128 {
533 let size = size.bits();
535 // Truncated until nothing is left.
539 let shift = 128 - size;
540 // Shift the unsigned value to the left, then shift back to the right as signed
541 // (essentially fills with FF on the left).
542 (((value << shift) as i128) >> shift) as u128
545 /// Truncates `value` to `size` bits.
547 pub fn truncate(value: u128, size: Size) -> u128 {
548 let size = size.bits();
550 // Truncated until nothing is left.
553 let shift = 128 - size;
554 // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
555 (value << shift) >> shift