]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/mod.rs
Auto merge of #67532 - Centril:rollup-3duj42d, r=Centril
[rust.git] / src / librustc / mir / interpret / mod.rs
1 //! An interpreter for MIR used in CTFE and by miri.
2
3 #[macro_export]
4 macro_rules! err_unsup {
5     ($($tt:tt)*) => {
6         $crate::mir::interpret::InterpError::Unsupported(
7             $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
8         )
9     };
10 }
11
12 #[macro_export]
13 macro_rules! err_unsup_format {
14     ($($tt:tt)*) => { err_unsup!(Unsupported(format!($($tt)*))) };
15 }
16
17 #[macro_export]
18 macro_rules! err_inval {
19     ($($tt:tt)*) => {
20         $crate::mir::interpret::InterpError::InvalidProgram(
21             $crate::mir::interpret::InvalidProgramInfo::$($tt)*
22         )
23     };
24 }
25
26 #[macro_export]
27 macro_rules! err_ub {
28     ($($tt:tt)*) => {
29         $crate::mir::interpret::InterpError::UndefinedBehavior(
30             $crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
31         )
32     };
33 }
34
35 #[macro_export]
36 macro_rules! err_ub_format {
37     ($($tt:tt)*) => { err_ub!(Ub(format!($($tt)*))) };
38 }
39
40 #[macro_export]
41 macro_rules! err_panic {
42     ($($tt:tt)*) => {
43         $crate::mir::interpret::InterpError::Panic(
44             $crate::mir::interpret::PanicInfo::$($tt)*
45         )
46     };
47 }
48
49 #[macro_export]
50 macro_rules! err_exhaust {
51     ($($tt:tt)*) => {
52         $crate::mir::interpret::InterpError::ResourceExhaustion(
53             $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
54         )
55     };
56 }
57
58 #[macro_export]
59 macro_rules! throw_unsup {
60     ($($tt:tt)*) => { return Err(err_unsup!($($tt)*).into()) };
61 }
62
63 #[macro_export]
64 macro_rules! throw_unsup_format {
65     ($($tt:tt)*) => { throw_unsup!(Unsupported(format!($($tt)*))) };
66 }
67
68 #[macro_export]
69 macro_rules! throw_inval {
70     ($($tt:tt)*) => { return Err(err_inval!($($tt)*).into()) };
71 }
72
73 #[macro_export]
74 macro_rules! throw_ub {
75     ($($tt:tt)*) => { return Err(err_ub!($($tt)*).into()) };
76 }
77
78 #[macro_export]
79 macro_rules! throw_ub_format {
80     ($($tt:tt)*) => { throw_ub!(Ub(format!($($tt)*))) };
81 }
82
83 #[macro_export]
84 macro_rules! throw_panic {
85     ($($tt:tt)*) => { return Err(err_panic!($($tt)*).into()) };
86 }
87
88 #[macro_export]
89 macro_rules! throw_exhaust {
90     ($($tt:tt)*) => { return Err(err_exhaust!($($tt)*).into()) };
91 }
92
93 #[macro_export]
94 macro_rules! throw_machine_stop {
95     ($($tt:tt)*) => {
96         return Err($crate::mir::interpret::InterpError::MachineStop(Box::new($($tt)*)).into())
97     };
98 }
99
100 mod error;
101 mod value;
102 mod allocation;
103 mod pointer;
104 mod queries;
105
106 pub use self::error::{
107     InterpErrorInfo, InterpResult, InterpError, AssertMessage, ConstEvalErr, struct_error,
108     FrameInfo, ConstEvalRawResult, ConstEvalResult, ErrorHandled, PanicInfo, UnsupportedOpInfo,
109     InvalidProgramInfo, ResourceExhaustionInfo, UndefinedBehaviorInfo,
110 };
111
112 pub use self::value::{Scalar, ScalarMaybeUndef, RawConst, ConstValue, get_slice_bytes};
113
114 pub use self::allocation::{Allocation, AllocationExtra, Relocations, UndefMask};
115
116 pub use self::pointer::{Pointer, PointerArithmetic, CheckInAllocMsg};
117
118 use crate::mir;
119 use crate::hir::def_id::DefId;
120 use crate::ty::{self, TyCtxt, Instance};
121 use crate::ty::codec::TyDecoder;
122 use crate::ty::layout::{self, Size};
123 use crate::ty::subst::GenericArgKind;
124 use std::io;
125 use std::fmt;
126 use std::num::NonZeroU32;
127 use std::sync::atomic::{AtomicU32, Ordering};
128 use rustc_serialize::{Encoder, Decodable, Encodable};
129 use rustc_data_structures::fx::FxHashMap;
130 use rustc_data_structures::sync::{Lock, HashMapExt};
131 use rustc_data_structures::tiny_list::TinyList;
132 use rustc_macros::HashStable;
133 use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian};
134
135 /// Uniquely identifies one of the following:
136 /// - A constant
137 /// - A static
138 /// - A const fn where all arguments (if any) are zero-sized types
139 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable)]
140 #[derive(HashStable, Lift)]
141 pub struct GlobalId<'tcx> {
142     /// For a constant or static, the `Instance` of the item itself.
143     /// For a promoted global, the `Instance` of the function they belong to.
144     pub instance: ty::Instance<'tcx>,
145
146     /// The index for promoted globals within their function's `mir::Body`.
147     pub promoted: Option<mir::Promoted>,
148 }
149
150 #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
151 pub struct AllocId(pub u64);
152
153 impl rustc_serialize::UseSpecializedEncodable for AllocId {}
154 impl rustc_serialize::UseSpecializedDecodable for AllocId {}
155
156 #[derive(RustcDecodable, RustcEncodable)]
157 enum AllocDiscriminant {
158     Alloc,
159     Fn,
160     Static,
161 }
162
163 pub fn specialized_encode_alloc_id<'tcx, E: Encoder>(
164     encoder: &mut E,
165     tcx: TyCtxt<'tcx>,
166     alloc_id: AllocId,
167 ) -> Result<(), E::Error> {
168     let alloc: GlobalAlloc<'tcx> = tcx.alloc_map.lock().get(alloc_id)
169         .expect("no value for given alloc ID");
170     match alloc {
171         GlobalAlloc::Memory(alloc) => {
172             trace!("encoding {:?} with {:#?}", alloc_id, alloc);
173             AllocDiscriminant::Alloc.encode(encoder)?;
174             alloc.encode(encoder)?;
175         }
176         GlobalAlloc::Function(fn_instance) => {
177             trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
178             AllocDiscriminant::Fn.encode(encoder)?;
179             fn_instance.encode(encoder)?;
180         }
181         GlobalAlloc::Static(did) => {
182             // References to statics doesn't need to know about their allocations,
183             // just about its `DefId`.
184             AllocDiscriminant::Static.encode(encoder)?;
185             did.encode(encoder)?;
186         }
187     }
188     Ok(())
189 }
190
191 // Used to avoid infinite recursion when decoding cyclic allocations.
192 type DecodingSessionId = NonZeroU32;
193
194 #[derive(Clone)]
195 enum State {
196     Empty,
197     InProgressNonAlloc(TinyList<DecodingSessionId>),
198     InProgress(TinyList<DecodingSessionId>, AllocId),
199     Done(AllocId),
200 }
201
202 pub struct AllocDecodingState {
203     // For each `AllocId`, we keep track of which decoding state it's currently in.
204     decoding_state: Vec<Lock<State>>,
205     // The offsets of each allocation in the data stream.
206     data_offsets: Vec<u32>,
207 }
208
209 impl AllocDecodingState {
210     pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
211         static DECODER_SESSION_ID: AtomicU32 = AtomicU32::new(0);
212         let counter = DECODER_SESSION_ID.fetch_add(1, Ordering::SeqCst);
213
214         // Make sure this is never zero.
215         let session_id = DecodingSessionId::new((counter & 0x7FFFFFFF) + 1).unwrap();
216
217         AllocDecodingSession {
218             state: self,
219             session_id,
220         }
221     }
222
223     pub fn new(data_offsets: Vec<u32>) -> Self {
224         let decoding_state = vec![Lock::new(State::Empty); data_offsets.len()];
225
226         Self {
227             decoding_state,
228             data_offsets,
229         }
230     }
231 }
232
233 #[derive(Copy, Clone)]
234 pub struct AllocDecodingSession<'s> {
235     state: &'s AllocDecodingState,
236     session_id: DecodingSessionId,
237 }
238
239 impl<'s> AllocDecodingSession<'s> {
240     /// Decodes an `AllocId` in a thread-safe way.
241     pub fn decode_alloc_id<D>(&self, decoder: &mut D) -> Result<AllocId, D::Error>
242     where
243         D: TyDecoder<'tcx>,
244     {
245         // Read the index of the allocation.
246         let idx = decoder.read_u32()? as usize;
247         let pos = self.state.data_offsets[idx] as usize;
248
249         // Decode the `AllocDiscriminant` now so that we know if we have to reserve an
250         // `AllocId`.
251         let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
252             let alloc_kind = AllocDiscriminant::decode(decoder)?;
253             Ok((alloc_kind, decoder.position()))
254         })?;
255
256         // Check the decoding state to see if it's already decoded or if we should
257         // decode it here.
258         let alloc_id = {
259             let mut entry = self.state.decoding_state[idx].lock();
260
261             match *entry {
262                 State::Done(alloc_id) => {
263                     return Ok(alloc_id);
264                 }
265                 ref mut entry @ State::Empty => {
266                     // We are allowed to decode.
267                     match alloc_kind {
268                         AllocDiscriminant::Alloc => {
269                             // If this is an allocation, we need to reserve an
270                             // `AllocId` so we can decode cyclic graphs.
271                             let alloc_id = decoder.tcx().alloc_map.lock().reserve();
272                             *entry = State::InProgress(
273                                 TinyList::new_single(self.session_id),
274                                 alloc_id);
275                             Some(alloc_id)
276                         },
277                         AllocDiscriminant::Fn | AllocDiscriminant::Static => {
278                             // Fns and statics cannot be cyclic, and their `AllocId`
279                             // is determined later by interning.
280                             *entry = State::InProgressNonAlloc(
281                                 TinyList::new_single(self.session_id));
282                             None
283                         }
284                     }
285                 }
286                 State::InProgressNonAlloc(ref mut sessions) => {
287                     if sessions.contains(&self.session_id) {
288                         bug!("this should be unreachable");
289                     } else {
290                         // Start decoding concurrently.
291                         sessions.insert(self.session_id);
292                         None
293                     }
294                 }
295                 State::InProgress(ref mut sessions, alloc_id) => {
296                     if sessions.contains(&self.session_id) {
297                         // Don't recurse.
298                         return Ok(alloc_id)
299                     } else {
300                         // Start decoding concurrently.
301                         sessions.insert(self.session_id);
302                         Some(alloc_id)
303                     }
304                 }
305             }
306         };
307
308         // Now decode the actual data.
309         let alloc_id = decoder.with_position(pos, |decoder| {
310             match alloc_kind {
311                 AllocDiscriminant::Alloc => {
312                     let alloc = <&'tcx Allocation as Decodable>::decode(decoder)?;
313                     // We already have a reserved `AllocId`.
314                     let alloc_id = alloc_id.unwrap();
315                     trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc);
316                     decoder.tcx().alloc_map.lock().set_alloc_id_same_memory(alloc_id, alloc);
317                     Ok(alloc_id)
318                 },
319                 AllocDiscriminant::Fn => {
320                     assert!(alloc_id.is_none());
321                     trace!("creating fn alloc ID");
322                     let instance = ty::Instance::decode(decoder)?;
323                     trace!("decoded fn alloc instance: {:?}", instance);
324                     let alloc_id = decoder.tcx().alloc_map.lock().create_fn_alloc(instance);
325                     Ok(alloc_id)
326                 },
327                 AllocDiscriminant::Static => {
328                     assert!(alloc_id.is_none());
329                     trace!("creating extern static alloc ID");
330                     let did = DefId::decode(decoder)?;
331                     trace!("decoded static def-ID: {:?}", did);
332                     let alloc_id = decoder.tcx().alloc_map.lock().create_static_alloc(did);
333                     Ok(alloc_id)
334                 }
335             }
336         })?;
337
338         self.state.decoding_state[idx].with_lock(|entry| {
339             *entry = State::Done(alloc_id);
340         });
341
342         Ok(alloc_id)
343     }
344 }
345
346 impl fmt::Display for AllocId {
347     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348         write!(f, "{}", self.0)
349     }
350 }
351
352 /// An allocation in the global (tcx-managed) memory can be either a function pointer,
353 /// a static, or a "real" allocation with some data in it.
354 #[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]
355 pub enum GlobalAlloc<'tcx> {
356     /// The alloc ID is used as a function pointer.
357     Function(Instance<'tcx>),
358     /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
359     /// This is also used to break the cycle in recursive statics.
360     Static(DefId),
361     /// The alloc ID points to memory.
362     Memory(&'tcx Allocation),
363 }
364
365 pub struct AllocMap<'tcx> {
366     /// Maps `AllocId`s to their corresponding allocations.
367     alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
368
369     /// Used to ensure that statics and functions only get one associated `AllocId`.
370     /// Should never contain a `GlobalAlloc::Memory`!
371     //
372     // FIXME: Should we just have two separate dedup maps for statics and functions each?
373     dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
374
375     /// The `AllocId` to assign to the next requested ID.
376     /// Always incremented; never gets smaller.
377     next_id: AllocId,
378 }
379
380 impl<'tcx> AllocMap<'tcx> {
381     pub fn new() -> Self {
382         AllocMap {
383             alloc_map: Default::default(),
384             dedup: Default::default(),
385             next_id: AllocId(0),
386         }
387     }
388
389     /// Obtains a new allocation ID that can be referenced but does not
390     /// yet have an allocation backing it.
391     ///
392     /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
393     /// an `AllocId` from a query.
394     pub fn reserve(
395         &mut self,
396     ) -> AllocId {
397         let next = self.next_id;
398         self.next_id.0 = self.next_id.0
399             .checked_add(1)
400             .expect("You overflowed a u64 by incrementing by 1... \
401                      You've just earned yourself a free drink if we ever meet. \
402                      Seriously, how did you do that?!");
403         next
404     }
405
406     /// Reserves a new ID *if* this allocation has not been dedup-reserved before.
407     /// Should only be used for function pointers and statics, we don't want
408     /// to dedup IDs for "real" memory!
409     fn reserve_and_set_dedup(&mut self, alloc: GlobalAlloc<'tcx>) -> AllocId {
410         match alloc {
411             GlobalAlloc::Function(..) | GlobalAlloc::Static(..) => {},
412             GlobalAlloc::Memory(..) => bug!("Trying to dedup-reserve memory with real data!"),
413         }
414         if let Some(&alloc_id) = self.dedup.get(&alloc) {
415             return alloc_id;
416         }
417         let id = self.reserve();
418         debug!("creating alloc {:?} with id {}", alloc, id);
419         self.alloc_map.insert(id, alloc.clone());
420         self.dedup.insert(alloc, id);
421         id
422     }
423
424     /// Generates an `AllocId` for a static or return a cached one in case this function has been
425     /// called on the same static before.
426     pub fn create_static_alloc(&mut self, static_id: DefId) -> AllocId {
427         self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
428     }
429
430     /// Generates an `AllocId` for a function.  Depending on the function type,
431     /// this might get deduplicated or assigned a new ID each time.
432     pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> AllocId {
433         // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
434         // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
435         // duplicated across crates.
436         // We thus generate a new `AllocId` for every mention of a function. This means that
437         // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
438         // However, formatting code relies on function identity (see #58320), so we only do
439         // this for generic functions.  Lifetime parameters are ignored.
440         let is_generic = instance.substs.into_iter().any(|kind| {
441             match kind.unpack() {
442                 GenericArgKind::Lifetime(_) => false,
443                 _ => true,
444             }
445         });
446         if is_generic {
447             // Get a fresh ID.
448             let id = self.reserve();
449             self.alloc_map.insert(id, GlobalAlloc::Function(instance));
450             id
451         } else {
452             // Deduplicate.
453             self.reserve_and_set_dedup(GlobalAlloc::Function(instance))
454         }
455     }
456
457     /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical
458     /// `Allocation` with a different `AllocId`.
459     /// Statics with identical content will still point to the same `Allocation`, i.e.,
460     /// their data will be deduplicated through `Allocation` interning -- but they
461     /// are different places in memory and as such need different IDs.
462     pub fn create_memory_alloc(&mut self, mem: &'tcx Allocation) -> AllocId {
463         let id = self.reserve();
464         self.set_alloc_id_memory(id, mem);
465         id
466     }
467
468     /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
469     /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
470     /// illegal and will likely ICE.
471     /// This function exists to allow const eval to detect the difference between evaluation-
472     /// local dangling pointers and allocations in constants/statics.
473     #[inline]
474     pub fn get(&self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
475         self.alloc_map.get(&id).cloned()
476     }
477
478     /// Panics if the `AllocId` does not refer to an `Allocation`
479     pub fn unwrap_memory(&self, id: AllocId) -> &'tcx Allocation {
480         match self.get(id) {
481             Some(GlobalAlloc::Memory(mem)) => mem,
482             _ => bug!("expected allocation ID {} to point to memory", id),
483         }
484     }
485
486     /// Panics if the `AllocId` does not refer to a function
487     pub fn unwrap_fn(&self, id: AllocId) -> Instance<'tcx> {
488         match self.get(id) {
489             Some(GlobalAlloc::Function(instance)) => instance,
490             _ => bug!("expected allocation ID {} to point to a function", id),
491         }
492     }
493
494     /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
495     /// call this function twice, even with the same `Allocation` will ICE the compiler.
496     pub fn set_alloc_id_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
497         if let Some(old) = self.alloc_map.insert(id, GlobalAlloc::Memory(mem)) {
498             bug!("tried to set allocation ID {}, but it was already existing as {:#?}", id, old);
499         }
500     }
501
502     /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
503     /// twice for the same `(AllocId, Allocation)` pair.
504     fn set_alloc_id_same_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
505         self.alloc_map.insert_same(id, GlobalAlloc::Memory(mem));
506     }
507 }
508
509 ////////////////////////////////////////////////////////////////////////////////
510 // Methods to access integers in the target endianness
511 ////////////////////////////////////////////////////////////////////////////////
512
513 #[inline]
514 pub fn write_target_uint(
515     endianness: layout::Endian,
516     mut target: &mut [u8],
517     data: u128,
518 ) -> Result<(), io::Error> {
519     let len = target.len();
520     match endianness {
521         layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
522         layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
523     }
524 }
525
526 #[inline]
527 pub fn read_target_uint(endianness: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
528     match endianness {
529         layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
530         layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
531     }
532 }
533
534 ////////////////////////////////////////////////////////////////////////////////
535 // Methods to facilitate working with signed integers stored in a u128
536 ////////////////////////////////////////////////////////////////////////////////
537
538 /// Truncates `value` to `size` bits and then sign-extend it to 128 bits
539 /// (i.e., if it is negative, fill with 1's on the left).
540 #[inline]
541 pub fn sign_extend(value: u128, size: Size) -> u128 {
542     let size = size.bits();
543     if size == 0 {
544         // Truncated until nothing is left.
545         return 0;
546     }
547     // Sign-extend it.
548     let shift = 128 - size;
549     // Shift the unsigned value to the left, then shift back to the right as signed
550     // (essentially fills with FF on the left).
551     (((value << shift) as i128) >> shift) as u128
552 }
553
554 /// Truncates `value` to `size` bits.
555 #[inline]
556 pub fn truncate(value: u128, size: Size) -> u128 {
557     let size = size.bits();
558     if size == 0 {
559         // Truncated until nothing is left.
560         return 0;
561     }
562     let shift = 128 - size;
563     // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
564     (value << shift) >> shift
565 }