1 //! An interpreter for MIR used in CTFE and by miri
4 macro_rules! throw_unsup {
5 ($($tt:tt)*) => { return Err(err_unsup!($($tt)*).into()) };
9 macro_rules! throw_inval {
10 ($($tt:tt)*) => { return Err(err_inval!($($tt)*).into()) };
14 macro_rules! throw_ub {
16 return Err($crate::mir::interpret::InterpError::UndefinedBehaviour(
17 $crate::mir::interpret::UndefinedBehaviourInfo::$($tt)*
23 macro_rules! throw_panic {
25 return Err($crate::mir::interpret::InterpError::Panic(
26 $crate::mir::interpret::PanicInfo::$($tt)*
32 macro_rules! throw_exhaust {
34 return Err($crate::mir::interpret::InterpError::ResourceExhaustion(
35 $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
41 macro_rules! err_inval {
43 $crate::mir::interpret::InterpError::InvalidProgram(
44 $crate::mir::interpret::InvalidProgramInfo::$($tt)*
50 macro_rules! err_unsup {
52 $crate::mir::interpret::InterpError::Unsupported(
53 $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
63 pub use self::error::{
64 InterpErrorInfo, InterpResult, InterpError, AssertMessage, ConstEvalErr, struct_error,
65 FrameInfo, ConstEvalRawResult, ConstEvalResult, ErrorHandled, PanicInfo, UnsupportedOpInfo,
66 InvalidProgramInfo, ResourceExhaustionInfo, UndefinedBehaviourInfo,
69 pub use self::value::{Scalar, ScalarMaybeUndef, RawConst, ConstValue};
71 pub use self::allocation::{Allocation, AllocationExtra, Relocations, UndefMask};
73 pub use self::pointer::{Pointer, PointerArithmetic, CheckInAllocMsg};
77 use crate::hir::def_id::DefId;
78 use crate::ty::{self, TyCtxt, Instance, subst::UnpackedKind};
79 use crate::ty::layout::{self, Size};
81 use rustc_serialize::{Encoder, Decodable, Encodable};
82 use rustc_data_structures::fx::FxHashMap;
83 use rustc_data_structures::sync::{Lock as Mutex, HashMapExt};
84 use rustc_data_structures::tiny_list::TinyList;
85 use rustc_macros::HashStable;
86 use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian};
87 use crate::ty::codec::TyDecoder;
88 use std::sync::atomic::{AtomicU32, Ordering};
89 use std::num::NonZeroU32;
91 /// Uniquely identifies a specific constant or static.
92 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable, HashStable)]
93 pub struct GlobalId<'tcx> {
94 /// For a constant or static, the `Instance` of the item itself.
95 /// For a promoted global, the `Instance` of the function they belong to.
96 pub instance: ty::Instance<'tcx>,
98 /// The index for promoted globals within their function's `mir::Body`.
99 pub promoted: Option<mir::Promoted>,
102 #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
103 pub struct AllocId(pub u64);
105 impl rustc_serialize::UseSpecializedEncodable for AllocId {}
106 impl rustc_serialize::UseSpecializedDecodable for AllocId {}
108 #[derive(RustcDecodable, RustcEncodable)]
109 enum AllocDiscriminant {
115 pub fn specialized_encode_alloc_id<'tcx, E: Encoder>(
119 ) -> Result<(), E::Error> {
120 let alloc: GlobalAlloc<'tcx> =
121 tcx.alloc_map.lock().get(alloc_id).expect("no value for AllocId");
123 GlobalAlloc::Memory(alloc) => {
124 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
125 AllocDiscriminant::Alloc.encode(encoder)?;
126 alloc.encode(encoder)?;
128 GlobalAlloc::Function(fn_instance) => {
129 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
130 AllocDiscriminant::Fn.encode(encoder)?;
131 fn_instance.encode(encoder)?;
133 GlobalAlloc::Static(did) => {
134 // referring to statics doesn't need to know about their allocations,
135 // just about its DefId
136 AllocDiscriminant::Static.encode(encoder)?;
137 did.encode(encoder)?;
143 // Used to avoid infinite recursion when decoding cyclic allocations.
144 type DecodingSessionId = NonZeroU32;
149 InProgressNonAlloc(TinyList<DecodingSessionId>),
150 InProgress(TinyList<DecodingSessionId>, AllocId),
154 pub struct AllocDecodingState {
155 // For each AllocId we keep track of which decoding state it's currently in.
156 decoding_state: Vec<Mutex<State>>,
157 // The offsets of each allocation in the data stream.
158 data_offsets: Vec<u32>,
161 impl AllocDecodingState {
163 pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
164 static DECODER_SESSION_ID: AtomicU32 = AtomicU32::new(0);
165 let counter = DECODER_SESSION_ID.fetch_add(1, Ordering::SeqCst);
167 // Make sure this is never zero
168 let session_id = DecodingSessionId::new((counter & 0x7FFFFFFF) + 1).unwrap();
170 AllocDecodingSession {
176 pub fn new(data_offsets: Vec<u32>) -> AllocDecodingState {
177 let decoding_state = vec![Mutex::new(State::Empty); data_offsets.len()];
186 #[derive(Copy, Clone)]
187 pub struct AllocDecodingSession<'s> {
188 state: &'s AllocDecodingState,
189 session_id: DecodingSessionId,
192 impl<'s> AllocDecodingSession<'s> {
193 // Decodes an AllocId in a thread-safe way.
194 pub fn decode_alloc_id<D>(&self, decoder: &mut D) -> Result<AllocId, D::Error>
198 // Read the index of the allocation
199 let idx = decoder.read_u32()? as usize;
200 let pos = self.state.data_offsets[idx] as usize;
202 // Decode the AllocDiscriminant now so that we know if we have to reserve an
204 let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
205 let alloc_kind = AllocDiscriminant::decode(decoder)?;
206 Ok((alloc_kind, decoder.position()))
209 // Check the decoding state, see if it's already decoded or if we should
212 let mut entry = self.state.decoding_state[idx].lock();
215 State::Done(alloc_id) => {
218 ref mut entry @ State::Empty => {
219 // We are allowed to decode
221 AllocDiscriminant::Alloc => {
222 // If this is an allocation, we need to reserve an
223 // AllocId so we can decode cyclic graphs.
224 let alloc_id = decoder.tcx().alloc_map.lock().reserve();
225 *entry = State::InProgress(
226 TinyList::new_single(self.session_id),
230 AllocDiscriminant::Fn | AllocDiscriminant::Static => {
231 // Fns and statics cannot be cyclic and their AllocId
232 // is determined later by interning
233 *entry = State::InProgressNonAlloc(
234 TinyList::new_single(self.session_id));
239 State::InProgressNonAlloc(ref mut sessions) => {
240 if sessions.contains(&self.session_id) {
241 bug!("This should be unreachable")
243 // Start decoding concurrently
244 sessions.insert(self.session_id);
248 State::InProgress(ref mut sessions, alloc_id) => {
249 if sessions.contains(&self.session_id) {
253 // Start decoding concurrently
254 sessions.insert(self.session_id);
261 // Now decode the actual data
262 let alloc_id = decoder.with_position(pos, |decoder| {
264 AllocDiscriminant::Alloc => {
265 let allocation = <&'tcx Allocation as Decodable>::decode(decoder)?;
266 // We already have a reserved AllocId.
267 let alloc_id = alloc_id.unwrap();
268 trace!("decoded alloc {:?} {:#?}", alloc_id, allocation);
269 decoder.tcx().alloc_map.lock().set_alloc_id_same_memory(alloc_id, allocation);
272 AllocDiscriminant::Fn => {
273 assert!(alloc_id.is_none());
274 trace!("creating fn alloc id");
275 let instance = ty::Instance::decode(decoder)?;
276 trace!("decoded fn alloc instance: {:?}", instance);
277 let alloc_id = decoder.tcx().alloc_map.lock().create_fn_alloc(instance);
280 AllocDiscriminant::Static => {
281 assert!(alloc_id.is_none());
282 trace!("creating extern static alloc id at");
283 let did = DefId::decode(decoder)?;
284 let alloc_id = decoder.tcx().alloc_map.lock().create_static_alloc(did);
290 self.state.decoding_state[idx].with_lock(|entry| {
291 *entry = State::Done(alloc_id);
298 impl fmt::Display for AllocId {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 write!(f, "{}", self.0)
304 /// An allocation in the global (tcx-managed) memory can be either a function pointer,
305 /// a static, or a "real" allocation with some data in it.
306 #[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]
307 pub enum GlobalAlloc<'tcx> {
308 /// The alloc ID is used as a function pointer
309 Function(Instance<'tcx>),
310 /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
311 /// This is also used to break the cycle in recursive statics.
313 /// The alloc ID points to memory.
314 Memory(&'tcx Allocation),
317 pub struct AllocMap<'tcx> {
318 /// Lets you know what an `AllocId` refers to.
319 alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
321 /// Used to ensure that statics and functions only get one associated `AllocId`.
322 /// Should never contain a `GlobalAlloc::Memory`!
323 /// FIXME: Should we just have two separate dedup maps for statics and functions each?
324 dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
326 /// The `AllocId` to assign to the next requested ID.
327 /// Always incremented, never gets smaller.
331 impl<'tcx> AllocMap<'tcx> {
332 pub fn new() -> Self {
334 alloc_map: Default::default(),
335 dedup: Default::default(),
340 /// Obtains a new allocation ID that can be referenced but does not
341 /// yet have an allocation backing it.
343 /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
344 /// an `AllocId` from a query.
348 let next = self.next_id;
349 self.next_id.0 = self.next_id.0
351 .expect("You overflowed a u64 by incrementing by 1... \
352 You've just earned yourself a free drink if we ever meet. \
353 Seriously, how did you do that?!");
357 /// Reserve a new ID *if* this allocation has not been dedup-reserved before.
358 /// Should only be used for function pointers and statics, we don't want
359 /// to dedup IDs for "real" memory!
360 fn reserve_and_set_dedup(&mut self, alloc: GlobalAlloc<'tcx>) -> AllocId {
362 GlobalAlloc::Function(..) | GlobalAlloc::Static(..) => {},
363 GlobalAlloc::Memory(..) => bug!("Trying to dedup-reserve memory with real data!"),
365 if let Some(&alloc_id) = self.dedup.get(&alloc) {
368 let id = self.reserve();
369 debug!("creating alloc {:?} with id {}", alloc, id);
370 self.alloc_map.insert(id, alloc.clone());
371 self.dedup.insert(alloc, id);
375 /// Generates an `AllocId` for a static or return a cached one in case this function has been
376 /// called on the same static before.
377 pub fn create_static_alloc(&mut self, static_id: DefId) -> AllocId {
378 self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
381 /// Generates an `AllocId` for a function. Depending on the function type,
382 /// this might get deduplicated or assigned a new ID each time.
383 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> AllocId {
384 // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
385 // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
386 // duplicated across crates.
387 // We thus generate a new `AllocId` for every mention of a function. This means that
388 // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
389 // However, formatting code relies on function identity (see #58320), so we only do
390 // this for generic functions. Lifetime parameters are ignored.
391 let is_generic = instance.substs.into_iter().any(|kind| {
392 match kind.unpack() {
393 UnpackedKind::Lifetime(_) => false,
399 let id = self.reserve();
400 self.alloc_map.insert(id, GlobalAlloc::Function(instance));
404 self.reserve_and_set_dedup(GlobalAlloc::Function(instance))
408 /// Intern the `Allocation` and return a new `AllocId`, even if there's already an identical
409 /// `Allocation` with a different `AllocId`.
410 /// Statics with identical content will still point to the same `Allocation`, i.e.,
411 /// their data will be deduplicated through `Allocation` interning -- but they
412 /// are different places in memory and as such need different IDs.
413 pub fn create_memory_alloc(&mut self, mem: &'tcx Allocation) -> AllocId {
414 let id = self.reserve();
415 self.set_alloc_id_memory(id, mem);
419 /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
420 /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
421 /// illegal and will likely ICE.
422 /// This function exists to allow const eval to detect the difference between evaluation-
423 /// local dangling pointers and allocations in constants/statics.
425 pub fn get(&self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
426 self.alloc_map.get(&id).cloned()
429 /// Panics if the `AllocId` does not refer to an `Allocation`
430 pub fn unwrap_memory(&self, id: AllocId) -> &'tcx Allocation {
432 Some(GlobalAlloc::Memory(mem)) => mem,
433 _ => bug!("expected allocation id {} to point to memory", id),
437 /// Freeze an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
438 /// call this function twice, even with the same `Allocation` will ICE the compiler.
439 pub fn set_alloc_id_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
440 if let Some(old) = self.alloc_map.insert(id, GlobalAlloc::Memory(mem)) {
441 bug!("tried to set allocation id {}, but it was already existing as {:#?}", id, old);
445 /// Freeze an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
446 /// twice for the same `(AllocId, Allocation)` pair.
447 fn set_alloc_id_same_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
448 self.alloc_map.insert_same(id, GlobalAlloc::Memory(mem));
452 ////////////////////////////////////////////////////////////////////////////////
453 // Methods to access integers in the target endianness
454 ////////////////////////////////////////////////////////////////////////////////
457 pub fn write_target_uint(
458 endianness: layout::Endian,
459 mut target: &mut [u8],
461 ) -> Result<(), io::Error> {
462 let len = target.len();
464 layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
465 layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
470 pub fn read_target_uint(endianness: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
472 layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
473 layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
477 ////////////////////////////////////////////////////////////////////////////////
478 // Methods to facilitate working with signed integers stored in a u128
479 ////////////////////////////////////////////////////////////////////////////////
481 /// Truncate `value` to `size` bits and then sign-extend it to 128 bits
482 /// (i.e., if it is negative, fill with 1's on the left).
484 pub fn sign_extend(value: u128, size: Size) -> u128 {
485 let size = size.bits();
487 // Truncated until nothing is left.
491 let shift = 128 - size;
492 // shift the unsigned value to the left
493 // and back to the right as signed (essentially fills with FF on the left)
494 (((value << shift) as i128) >> shift) as u128
497 /// Truncate `value` to `size` bits.
499 pub fn truncate(value: u128, size: Size) -> u128 {
500 let size = size.bits();
502 // Truncated until nothing is left.
505 let shift = 128 - size;
506 // truncate (shift left to drop out leftover values, shift right to fill with zeroes)
507 (value << shift) >> shift