]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
Rewrite `get_size_and_align` so it doesn't duplicate work
[rust.git] / src / librustc_mir / interpret / memory.rs
1 //! The memory subsystem.
2 //!
3 //! Generally, we use `Pointer` to denote memory addresses. However, some operations
4 //! have a "size"-like parameter, and they take `Scalar` for the address because
5 //! if the size is 0, then the pointer can also be a (properly aligned, non-NULL)
6 //! integer. It is crucial that these operations call `check_align` *before*
7 //! short-circuiting the empty case!
8
9 use std::collections::VecDeque;
10 use std::ptr;
11 use std::borrow::Cow;
12
13 use rustc::ty::{self, Instance, ParamEnv, query::TyCtxtAt};
14 use rustc::ty::layout::{Align, TargetDataLayout, Size, HasDataLayout};
15 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
16
17 use syntax::ast::Mutability;
18
19 use super::{
20     Pointer, AllocId, Allocation, GlobalId, AllocationExtra,
21     InterpResult, Scalar, InterpError, GlobalAlloc, PointerArithmetic,
22     Machine, AllocMap, MayLeak, ErrorHandled, CheckInAllocMsg,
23 };
24
25 #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
26 pub enum MemoryKind<T> {
27     /// Error if deallocated except during a stack pop
28     Stack,
29     /// Error if ever deallocated
30     Vtable,
31     /// Additional memory kinds a machine wishes to distinguish from the builtin ones
32     Machine(T),
33 }
34
35 impl<T: MayLeak> MayLeak for MemoryKind<T> {
36     #[inline]
37     fn may_leak(self) -> bool {
38         match self {
39             MemoryKind::Stack => false,
40             MemoryKind::Vtable => true,
41             MemoryKind::Machine(k) => k.may_leak()
42         }
43     }
44 }
45
46 /// Used by `get_size_and_align` to indicate whether the allocation needs to be live.
47 #[derive(Debug, Copy, Clone)]
48 pub enum AllocCheck {
49     /// Allocation must be live and not a function pointer.
50     Dereferencable,
51     /// Allocations needs to be live, but may be a function pointer.
52     Live,
53     /// Allocation may be dead.
54     MaybeDead,
55 }
56
57 /// The value of a function pointer.
58 #[derive(Debug, Copy, Clone)]
59 pub enum FnVal<'tcx, Other> {
60     Instance(Instance<'tcx>),
61     Other(Other),
62 }
63
64 impl<'tcx, Other> FnVal<'tcx, Other> {
65     pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
66         match self {
67             FnVal::Instance(instance) =>
68                 Ok(instance),
69             FnVal::Other(_) =>
70                 err!(MachineError(
71                     format!("Expected instance function pointer, got 'other' pointer")
72                 )),
73         }
74     }
75 }
76
77 // `Memory` has to depend on the `Machine` because some of its operations
78 // (e.g., `get`) call a `Machine` hook.
79 pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
80     /// Allocations local to this instance of the miri engine. The kind
81     /// helps ensure that the same mechanism is used for allocation and
82     /// deallocation. When an allocation is not found here, it is a
83     /// static and looked up in the `tcx` for read access. Some machines may
84     /// have to mutate this map even on a read-only access to a static (because
85     /// they do pointer provenance tracking and the allocations in `tcx` have
86     /// the wrong type), so we let the machine override this type.
87     /// Either way, if the machine allows writing to a static, doing so will
88     /// create a copy of the static allocation here.
89     // FIXME: this should not be public, but interning currently needs access to it
90     pub(super) alloc_map: M::MemoryMap,
91
92     /// Map for "extra" function pointers.
93     extra_fn_ptr_map: FxHashMap<AllocId, M::ExtraFnVal>,
94
95     /// To be able to compare pointers with NULL, and to check alignment for accesses
96     /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
97     /// that do not exist any more.
98     // FIXME: this should not be public, but interning currently needs access to it
99     pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
100
101     /// Extra data added by the machine.
102     pub extra: M::MemoryExtra,
103
104     /// Lets us implement `HasDataLayout`, which is awfully convenient.
105     pub tcx: TyCtxtAt<'tcx>,
106 }
107
108 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> {
109     #[inline]
110     fn data_layout(&self) -> &TargetDataLayout {
111         &self.tcx.data_layout
112     }
113 }
114
115 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
116 // carefully copy only the reachable parts.
117 impl<'mir, 'tcx, M> Clone for Memory<'mir, 'tcx, M>
118 where
119     M: Machine<'mir, 'tcx, PointerTag = (), AllocExtra = (), MemoryExtra = ()>,
120     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
121 {
122     fn clone(&self) -> Self {
123         Memory {
124             alloc_map: self.alloc_map.clone(),
125             extra_fn_ptr_map: self.extra_fn_ptr_map.clone(),
126             dead_alloc_map: self.dead_alloc_map.clone(),
127             extra: (),
128             tcx: self.tcx,
129         }
130     }
131 }
132
133 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
134     pub fn new(tcx: TyCtxtAt<'tcx>, extra: M::MemoryExtra) -> Self {
135         Memory {
136             alloc_map: M::MemoryMap::default(),
137             extra_fn_ptr_map: FxHashMap::default(),
138             dead_alloc_map: FxHashMap::default(),
139             extra,
140             tcx,
141         }
142     }
143
144     #[inline]
145     pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
146         ptr.with_tag(M::tag_static_base_pointer(&self.extra, ptr.alloc_id))
147     }
148
149     pub fn create_fn_alloc(
150         &mut self,
151         fn_val: FnVal<'tcx, M::ExtraFnVal>,
152     ) -> Pointer<M::PointerTag>
153     {
154         let id = match fn_val {
155             FnVal::Instance(instance) => self.tcx.alloc_map.lock().create_fn_alloc(instance),
156             FnVal::Other(extra) => {
157                 // FIXME(RalfJung): Should we have a cache here?
158                 let id = self.tcx.alloc_map.lock().reserve();
159                 let old = self.extra_fn_ptr_map.insert(id, extra);
160                 assert!(old.is_none());
161                 id
162             }
163         };
164         self.tag_static_base_pointer(Pointer::from(id))
165     }
166
167     pub fn allocate(
168         &mut self,
169         size: Size,
170         align: Align,
171         kind: MemoryKind<M::MemoryKinds>,
172     ) -> Pointer<M::PointerTag> {
173         let alloc = Allocation::undef(size, align);
174         self.allocate_with(alloc, kind)
175     }
176
177     pub fn allocate_static_bytes(
178         &mut self,
179         bytes: &[u8],
180         kind: MemoryKind<M::MemoryKinds>,
181     ) -> Pointer<M::PointerTag> {
182         let alloc = Allocation::from_byte_aligned_bytes(bytes);
183         self.allocate_with(alloc, kind)
184     }
185
186     pub fn allocate_with(
187         &mut self,
188         alloc: Allocation,
189         kind: MemoryKind<M::MemoryKinds>,
190     ) -> Pointer<M::PointerTag> {
191         let id = self.tcx.alloc_map.lock().reserve();
192         let (alloc, tag) = M::tag_allocation(&self.extra, id, Cow::Owned(alloc), Some(kind));
193         self.alloc_map.insert(id, (kind, alloc.into_owned()));
194         Pointer::from(id).with_tag(tag)
195     }
196
197     pub fn reallocate(
198         &mut self,
199         ptr: Pointer<M::PointerTag>,
200         old_size_and_align: Option<(Size, Align)>,
201         new_size: Size,
202         new_align: Align,
203         kind: MemoryKind<M::MemoryKinds>,
204     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
205         if ptr.offset.bytes() != 0 {
206             return err!(ReallocateNonBasePtr);
207         }
208
209         // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
210         // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
211         let new_ptr = self.allocate(new_size, new_align, kind);
212         let old_size = match old_size_and_align {
213             Some((size, _align)) => size,
214             None => Size::from_bytes(self.get(ptr.alloc_id)?.bytes.len() as u64),
215         };
216         self.copy(
217             ptr,
218             new_ptr,
219             old_size.min(new_size),
220             /*nonoverlapping*/ true,
221         )?;
222         self.deallocate(ptr, old_size_and_align, kind)?;
223
224         Ok(new_ptr)
225     }
226
227     /// Deallocate a local, or do nothing if that local has been made into a static
228     pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx> {
229         // The allocation might be already removed by static interning.
230         // This can only really happen in the CTFE instance, not in miri.
231         if self.alloc_map.contains_key(&ptr.alloc_id) {
232             self.deallocate(ptr, None, MemoryKind::Stack)
233         } else {
234             Ok(())
235         }
236     }
237
238     pub fn deallocate(
239         &mut self,
240         ptr: Pointer<M::PointerTag>,
241         old_size_and_align: Option<(Size, Align)>,
242         kind: MemoryKind<M::MemoryKinds>,
243     ) -> InterpResult<'tcx> {
244         trace!("deallocating: {}", ptr.alloc_id);
245
246         if ptr.offset.bytes() != 0 {
247             return err!(DeallocateNonBasePtr);
248         }
249
250         let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
251             Some(alloc) => alloc,
252             None => {
253                 // Deallocating static memory -- always an error
254                 return match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
255                     Some(GlobalAlloc::Function(..)) => err!(DeallocatedWrongMemoryKind(
256                         "function".to_string(),
257                         format!("{:?}", kind),
258                     )),
259                     Some(GlobalAlloc::Static(..)) |
260                     Some(GlobalAlloc::Memory(..)) => err!(DeallocatedWrongMemoryKind(
261                         "static".to_string(),
262                         format!("{:?}", kind),
263                     )),
264                     None => err!(DoubleFree)
265                 }
266             }
267         };
268
269         if alloc_kind != kind {
270             return err!(DeallocatedWrongMemoryKind(
271                 format!("{:?}", alloc_kind),
272                 format!("{:?}", kind),
273             ));
274         }
275         if let Some((size, align)) = old_size_and_align {
276             if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align {
277                 let bytes = Size::from_bytes(alloc.bytes.len() as u64);
278                 return err!(IncorrectAllocationInformation(size,
279                                                            bytes,
280                                                            align,
281                                                            alloc.align));
282             }
283         }
284
285         // Let the machine take some extra action
286         let size = Size::from_bytes(alloc.bytes.len() as u64);
287         AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?;
288
289         // Don't forget to remember size and align of this now-dead allocation
290         let old = self.dead_alloc_map.insert(
291             ptr.alloc_id,
292             (Size::from_bytes(alloc.bytes.len() as u64), alloc.align)
293         );
294         if old.is_some() {
295             bug!("Nothing can be deallocated twice");
296         }
297
298         Ok(())
299     }
300
301     /// Check if the given scalar is allowed to do a memory access of given `size`
302     /// and `align`. On success, returns `None` for zero-sized accesses (where
303     /// nothing else is left to do) and a `Pointer` to use for the actual access otherwise.
304     /// Crucially, if the input is a `Pointer`, we will test it for liveness
305     /// *even of* the size is 0.
306     ///
307     /// Everyone accessing memory based on a `Scalar` should use this method to get the
308     /// `Pointer` they need. And even if you already have a `Pointer`, call this method
309     /// to make sure it is sufficiently aligned and not dangling.  Not doing that may
310     /// cause ICEs.
311     ///
312     /// Most of the time you should use `check_mplace_access`, but when you just have a pointer,
313     /// this method is still appropriate.
314     pub fn check_ptr_access(
315         &self,
316         sptr: Scalar<M::PointerTag>,
317         size: Size,
318         align: Align,
319     ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
320         fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> {
321             if offset % align.bytes() == 0 {
322                 Ok(())
323             } else {
324                 // The biggest power of two through which `offset` is divisible.
325                 let offset_pow2 = 1 << offset.trailing_zeros();
326                 err!(AlignmentCheckFailed {
327                     has: Align::from_bytes(offset_pow2).unwrap(),
328                     required: align,
329                 })
330             }
331         }
332
333         // Normalize to a `Pointer` if we definitely need one.
334         let normalized = if size.bytes() == 0 {
335             // Can be an integer, just take what we got.  We do NOT `force_bits` here;
336             // if this is already a `Pointer` we want to do the bounds checks!
337             sptr
338         } else {
339             // A "real" access, we must get a pointer.
340             Scalar::Ptr(self.force_ptr(sptr)?)
341         };
342         Ok(match normalized.to_bits_or_ptr(self.pointer_size(), self) {
343             Ok(bits) => {
344                 let bits = bits as u64; // it's ptr-sized
345                 assert!(size.bytes() == 0);
346                 // Must be non-NULL and aligned.
347                 if bits == 0 {
348                     return err!(InvalidNullPointerUsage);
349                 }
350                 check_offset_align(bits, align)?;
351                 None
352             }
353             Err(ptr) => {
354                 let (allocation_size, alloc_align) =
355                     self.get_size_and_align(ptr.alloc_id, AllocCheck::Dereferencable)?;
356                 // Test bounds. This also ensures non-NULL.
357                 // It is sufficient to check this for the end pointer. The addition
358                 // checks for overflow.
359                 let end_ptr = ptr.offset(size, self)?;
360                 end_ptr.check_in_alloc(allocation_size, CheckInAllocMsg::MemoryAccessTest)?;
361                 // Test align. Check this last; if both bounds and alignment are violated
362                 // we want the error to be about the bounds.
363                 if alloc_align.bytes() < align.bytes() {
364                     // The allocation itself is not aligned enough.
365                     // FIXME: Alignment check is too strict, depending on the base address that
366                     // got picked we might be aligned even if this check fails.
367                     // We instead have to fall back to converting to an integer and checking
368                     // the "real" alignment.
369                     return err!(AlignmentCheckFailed {
370                         has: alloc_align,
371                         required: align,
372                     });
373                 }
374                 check_offset_align(ptr.offset.bytes(), align)?;
375
376                 // We can still be zero-sized in this branch, in which case we have to
377                 // return `None`.
378                 if size.bytes() == 0 { None } else { Some(ptr) }
379             }
380         })
381     }
382
383     /// Test if the pointer might be NULL.
384     pub fn ptr_may_be_null(
385         &self,
386         ptr: Pointer<M::PointerTag>,
387     ) -> bool {
388         let (size, _align) = self.get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead)
389             .expect("alloc info with MaybeDead cannot fail");
390         ptr.check_in_alloc(size, CheckInAllocMsg::NullPointerTest).is_err()
391     }
392 }
393
394 /// Allocation accessors
395 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
396     /// Helper function to obtain the global (tcx) allocation for a static.
397     /// This attempts to return a reference to an existing allocation if
398     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
399     /// this machine use the same pointer tag, so it is indirected through
400     /// `M::tag_allocation`.
401     ///
402     /// Notice that every static has two `AllocId` that will resolve to the same
403     /// thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
404     /// and the other one is maps to `GlobalAlloc::Memory`, this is returned by
405     /// `const_eval_raw` and it is the "resolved" ID.
406     /// The resolved ID is never used by the interpreted progrma, it is hidden.
407     /// The `GlobalAlloc::Memory` branch here is still reachable though; when a static
408     /// contains a reference to memory that was created during its evaluation (i.e., not to
409     /// another static), those inner references only exist in "resolved" form.
410     fn get_static_alloc(
411         memory_extra: &M::MemoryExtra,
412         tcx: TyCtxtAt<'tcx>,
413         id: AllocId,
414     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
415         let alloc = tcx.alloc_map.lock().get(id);
416         let alloc = match alloc {
417             Some(GlobalAlloc::Memory(mem)) =>
418                 Cow::Borrowed(mem),
419             Some(GlobalAlloc::Function(..)) =>
420                 return err!(DerefFunctionPointer),
421             None =>
422                 return err!(DanglingPointerDeref),
423             Some(GlobalAlloc::Static(def_id)) => {
424                 // We got a "lazy" static that has not been computed yet.
425                 if tcx.is_foreign_item(def_id) {
426                     trace!("static_alloc: foreign item {:?}", def_id);
427                     M::find_foreign_static(tcx.tcx, def_id)?
428                 } else {
429                     trace!("static_alloc: Need to compute {:?}", def_id);
430                     let instance = Instance::mono(tcx.tcx, def_id);
431                     let gid = GlobalId {
432                         instance,
433                         promoted: None,
434                     };
435                     // use the raw query here to break validation cycles. Later uses of the static
436                     // will call the full query anyway
437                     let raw_const = tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid))
438                         .map_err(|err| {
439                             // no need to report anything, the const_eval call takes care of that
440                             // for statics
441                             assert!(tcx.is_static(def_id));
442                             match err {
443                                 ErrorHandled::Reported => InterpError::ReferencedConstant,
444                                 ErrorHandled::TooGeneric => InterpError::TooGeneric,
445                             }
446                         })?;
447                     // Make sure we use the ID of the resolved memory, not the lazy one!
448                     let id = raw_const.alloc_id;
449                     let allocation = tcx.alloc_map.lock().unwrap_memory(id);
450                     Cow::Borrowed(allocation)
451                 }
452             }
453         };
454         // We got tcx memory. Let the machine figure out whether and how to
455         // turn that into memory with the right pointer tag.
456         Ok(M::tag_allocation(
457             memory_extra,
458             id, // always use the ID we got as input, not the "hidden" one.
459             alloc,
460             M::STATIC_KIND.map(MemoryKind::Machine),
461         ).0)
462     }
463
464     pub fn get(
465         &self,
466         id: AllocId,
467     ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
468         // The error type of the inner closure here is somewhat funny.  We have two
469         // ways of "erroring": An actual error, or because we got a reference from
470         // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
471         // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`.
472         let a = self.alloc_map.get_or(id, || {
473             let alloc = Self::get_static_alloc(&self.extra, self.tcx, id).map_err(Err)?;
474             match alloc {
475                 Cow::Borrowed(alloc) => {
476                     // We got a ref, cheaply return that as an "error" so that the
477                     // map does not get mutated.
478                     Err(Ok(alloc))
479                 }
480                 Cow::Owned(alloc) => {
481                     // Need to put it into the map and return a ref to that
482                     let kind = M::STATIC_KIND.expect(
483                         "I got an owned allocation that I have to copy but the machine does \
484                             not expect that to happen"
485                     );
486                     Ok((MemoryKind::Machine(kind), alloc))
487                 }
488             }
489         });
490         // Now unpack that funny error type
491         match a {
492             Ok(a) => Ok(&a.1),
493             Err(a) => a
494         }
495     }
496
497     pub fn get_mut(
498         &mut self,
499         id: AllocId,
500     ) -> InterpResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
501         let tcx = self.tcx;
502         let memory_extra = &self.extra;
503         let a = self.alloc_map.get_mut_or(id, || {
504             // Need to make a copy, even if `get_static_alloc` is able
505             // to give us a cheap reference.
506             let alloc = Self::get_static_alloc(memory_extra, tcx, id)?;
507             if alloc.mutability == Mutability::Immutable {
508                 return err!(ModifiedConstantMemory);
509             }
510             match M::STATIC_KIND {
511                 Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())),
512                 None => err!(ModifiedStatic),
513             }
514         });
515         // Unpack the error type manually because type inference doesn't
516         // work otherwise (and we cannot help it because `impl Trait`)
517         match a {
518             Err(e) => Err(e),
519             Ok(a) => {
520                 let a = &mut a.1;
521                 if a.mutability == Mutability::Immutable {
522                     return err!(ModifiedConstantMemory);
523                 }
524                 Ok(a)
525             }
526         }
527     }
528
529     /// Obtain the size and alignment of an allocation, even if that allocation has
530     /// been deallocated.
531     ///
532     /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`.
533     pub fn get_size_and_align(
534         &self,
535         id: AllocId,
536         liveness: AllocCheck,
537     ) -> InterpResult<'static, (Size, Align)> {
538         let alloc_or_size_align = self.alloc_map.get_or(id, || -> Result<_, InterpResult<'static, (Size, Align)>> {
539             // Can't do this in the match argument, we may get cycle errors since the lock would
540             // be held throughout the match.
541             let alloc = self.tcx.alloc_map.lock().get(id);
542             Err(match alloc {
543                 Some(GlobalAlloc::Static(did)) => {
544                     // Use size and align of the type
545                     let ty = self.tcx.type_of(did);
546                     let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
547                     Ok((layout.size, layout.align.abi))
548                 },
549                 Some(GlobalAlloc::Memory(alloc)) =>
550                     // this duplicates the logic on the `match alloc_or_size_align`, but due to the
551                     // API of `get_or` there's no way around that.
552                     Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)),
553                 Some(GlobalAlloc::Function(_)) => if let AllocCheck::Dereferencable = liveness {
554                     // The caller requested no function pointers.
555                     err!(DerefFunctionPointer)
556                 } else {
557                     Ok((Size::ZERO, Align::from_bytes(1).unwrap()))
558                 },
559                 // The rest must be dead.
560                 None => if let AllocCheck::MaybeDead = liveness {
561                     // Deallocated pointers are allowed, we should be able to find
562                     // them in the map.
563                     Ok(*self.dead_alloc_map.get(&id)
564                         .expect("deallocated pointers should all be recorded in `dead_alloc_map`"))
565                 } else {
566                     err!(DanglingPointerDeref)
567                 },
568             })
569         });
570         match alloc_or_size_align {
571             Ok((_, alloc)) => Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)),
572             Err(done) => done,
573         }
574     }
575
576     fn get_fn_alloc(&self, id: AllocId) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
577         trace!("reading fn ptr: {}", id);
578         if let Some(extra) = self.extra_fn_ptr_map.get(&id) {
579             Ok(FnVal::Other(*extra))
580         } else {
581             match self.tcx.alloc_map.lock().get(id) {
582                 Some(GlobalAlloc::Function(instance)) => Ok(FnVal::Instance(instance)),
583                 _ => Err(InterpError::ExecuteMemory.into()),
584             }
585         }
586     }
587
588     pub fn get_fn(
589         &self,
590         ptr: Scalar<M::PointerTag>,
591     ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
592         let ptr = self.force_ptr(ptr)?; // We definitely need a pointer value.
593         if ptr.offset.bytes() != 0 {
594             return err!(InvalidFunctionPointer);
595         }
596         self.get_fn_alloc(ptr.alloc_id)
597     }
598
599     pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
600         self.get_mut(id)?.mutability = Mutability::Immutable;
601         Ok(())
602     }
603
604     /// For debugging, print an allocation and all allocations it points to, recursively.
605     pub fn dump_alloc(&self, id: AllocId) {
606         self.dump_allocs(vec![id]);
607     }
608
609     fn dump_alloc_helper<Tag, Extra>(
610         &self,
611         allocs_seen: &mut FxHashSet<AllocId>,
612         allocs_to_print: &mut VecDeque<AllocId>,
613         mut msg: String,
614         alloc: &Allocation<Tag, Extra>,
615         extra: String,
616     ) {
617         use std::fmt::Write;
618
619         let prefix_len = msg.len();
620         let mut relocations = vec![];
621
622         for i in 0..(alloc.bytes.len() as u64) {
623             let i = Size::from_bytes(i);
624             if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
625                 if allocs_seen.insert(target_id) {
626                     allocs_to_print.push_back(target_id);
627                 }
628                 relocations.push((i, target_id));
629             }
630             if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
631                 // this `as usize` is fine, since `i` came from a `usize`
632                 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
633             } else {
634                 msg.push_str("__ ");
635             }
636         }
637
638         trace!(
639             "{}({} bytes, alignment {}){}",
640             msg,
641             alloc.bytes.len(),
642             alloc.align.bytes(),
643             extra
644         );
645
646         if !relocations.is_empty() {
647             msg.clear();
648             write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
649             let mut pos = Size::ZERO;
650             let relocation_width = (self.pointer_size().bytes() - 1) * 3;
651             for (i, target_id) in relocations {
652                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
653                 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
654                 let target = format!("({})", target_id);
655                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
656                 write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
657                 pos = i + self.pointer_size();
658             }
659             trace!("{}", msg);
660         }
661     }
662
663     /// For debugging, print a list of allocations and all allocations they point to, recursively.
664     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
665         if !log_enabled!(::log::Level::Trace) {
666             return;
667         }
668         allocs.sort();
669         allocs.dedup();
670         let mut allocs_to_print = VecDeque::from(allocs);
671         let mut allocs_seen = FxHashSet::default();
672
673         while let Some(id) = allocs_to_print.pop_front() {
674             let msg = format!("Alloc {:<5} ", format!("{}:", id));
675
676             // normal alloc?
677             match self.alloc_map.get_or(id, || Err(())) {
678                 Ok((kind, alloc)) => {
679                     let extra = match kind {
680                         MemoryKind::Stack => " (stack)".to_owned(),
681                         MemoryKind::Vtable => " (vtable)".to_owned(),
682                         MemoryKind::Machine(m) => format!(" ({:?})", m),
683                     };
684                     self.dump_alloc_helper(
685                         &mut allocs_seen, &mut allocs_to_print,
686                         msg, alloc, extra
687                     );
688                 },
689                 Err(()) => {
690                     // static alloc?
691                     match self.tcx.alloc_map.lock().get(id) {
692                         Some(GlobalAlloc::Memory(alloc)) => {
693                             self.dump_alloc_helper(
694                                 &mut allocs_seen, &mut allocs_to_print,
695                                 msg, alloc, " (immutable)".to_owned()
696                             );
697                         }
698                         Some(GlobalAlloc::Function(func)) => {
699                             trace!("{} {}", msg, func);
700                         }
701                         Some(GlobalAlloc::Static(did)) => {
702                             trace!("{} {:?}", msg, did);
703                         }
704                         None => {
705                             trace!("{} (deallocated)", msg);
706                         }
707                     }
708                 },
709             };
710
711         }
712     }
713
714     pub fn leak_report(&self) -> usize {
715         trace!("### LEAK REPORT ###");
716         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
717             if kind.may_leak() { None } else { Some(id) }
718         });
719         let n = leaks.len();
720         self.dump_allocs(leaks);
721         n
722     }
723
724     /// This is used by [priroda](https://github.com/oli-obk/priroda)
725     pub fn alloc_map(&self) -> &M::MemoryMap {
726         &self.alloc_map
727     }
728 }
729
730 /// Reading and writing.
731 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
732     /// Reads the given number of bytes from memory. Returns them as a slice.
733     ///
734     /// Performs appropriate bounds checks.
735     pub fn read_bytes(
736         &self,
737         ptr: Scalar<M::PointerTag>,
738         size: Size,
739     ) -> InterpResult<'tcx, &[u8]> {
740         let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? {
741             Some(ptr) => ptr,
742             None => return Ok(&[]), // zero-sized access
743         };
744         self.get(ptr.alloc_id)?.get_bytes(self, ptr, size)
745     }
746
747     /// Reads a 0-terminated sequence of bytes from memory. Returns them as a slice.
748     ///
749     /// Performs appropriate bounds checks.
750     pub fn read_c_str(&self, ptr: Scalar<M::PointerTag>) -> InterpResult<'tcx, &[u8]> {
751         let ptr = self.force_ptr(ptr)?; // We need to read at least 1 byte, so we *need* a ptr.
752         self.get(ptr.alloc_id)?.read_c_str(self, ptr)
753     }
754
755     /// Expects the caller to have checked bounds and alignment.
756     pub fn copy(
757         &mut self,
758         src: Pointer<M::PointerTag>,
759         dest: Pointer<M::PointerTag>,
760         size: Size,
761         nonoverlapping: bool,
762     ) -> InterpResult<'tcx> {
763         self.copy_repeatedly(src, dest, size, 1, nonoverlapping)
764     }
765
766     /// Expects the caller to have checked bounds and alignment.
767     pub fn copy_repeatedly(
768         &mut self,
769         src: Pointer<M::PointerTag>,
770         dest: Pointer<M::PointerTag>,
771         size: Size,
772         length: u64,
773         nonoverlapping: bool,
774     ) -> InterpResult<'tcx> {
775         // first copy the relocations to a temporary buffer, because
776         // `get_bytes_mut` will clear the relocations, which is correct,
777         // since we don't want to keep any relocations at the target.
778         // (`get_bytes_with_undef_and_ptr` below checks that there are no
779         // relocations overlapping the edges; those would not be handled correctly).
780         let relocations = {
781             let relocations = self.get(src.alloc_id)?.relocations(self, src, size);
782             if relocations.is_empty() {
783                 // nothing to copy, ignore even the `length` loop
784                 Vec::new()
785             } else {
786                 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
787                 for i in 0..length {
788                     new_relocations.extend(
789                         relocations
790                         .iter()
791                         .map(|&(offset, reloc)| {
792                             // compute offset for current repetition
793                             let dest_offset = dest.offset + (i * size);
794                             (
795                                 // shift offsets from source allocation to destination allocation
796                                 offset + dest_offset - src.offset,
797                                 reloc,
798                             )
799                         })
800                     );
801                 }
802
803                 new_relocations
804             }
805         };
806
807         let tcx = self.tcx.tcx;
808
809         // This checks relocation edges on the src.
810         let src_bytes = self.get(src.alloc_id)?
811             .get_bytes_with_undef_and_ptr(&tcx, src, size)?
812             .as_ptr();
813         let dest_bytes = self.get_mut(dest.alloc_id)?
814             .get_bytes_mut(&tcx, dest, size * length)?
815             .as_mut_ptr();
816
817         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
818         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
819         // `dest` could possibly overlap.
820         // The pointers above remain valid even if the `HashMap` table is moved around because they
821         // point into the `Vec` storing the bytes.
822         unsafe {
823             assert_eq!(size.bytes() as usize as u64, size.bytes());
824             if src.alloc_id == dest.alloc_id {
825                 if nonoverlapping {
826                     if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
827                         (dest.offset <= src.offset && dest.offset + size > src.offset)
828                     {
829                         return err!(Intrinsic(
830                             "copy_nonoverlapping called on overlapping ranges".to_string(),
831                         ));
832                     }
833                 }
834
835                 for i in 0..length {
836                     ptr::copy(src_bytes,
837                               dest_bytes.offset((size.bytes() * i) as isize),
838                               size.bytes() as usize);
839                 }
840             } else {
841                 for i in 0..length {
842                     ptr::copy_nonoverlapping(src_bytes,
843                                              dest_bytes.offset((size.bytes() * i) as isize),
844                                              size.bytes() as usize);
845                 }
846             }
847         }
848
849         // copy definedness to the destination
850         self.copy_undef_mask(src, dest, size, length)?;
851         // copy the relocations to the destination
852         self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
853
854         Ok(())
855     }
856 }
857
858 /// Undefined bytes
859 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
860     // FIXME: Add a fast version for the common, nonoverlapping case
861     fn copy_undef_mask(
862         &mut self,
863         src: Pointer<M::PointerTag>,
864         dest: Pointer<M::PointerTag>,
865         size: Size,
866         repeat: u64,
867     ) -> InterpResult<'tcx> {
868         // The bits have to be saved locally before writing to dest in case src and dest overlap.
869         assert_eq!(size.bytes() as usize as u64, size.bytes());
870
871         let undef_mask = &self.get(src.alloc_id)?.undef_mask;
872
873         // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
874         // a naive undef mask copying algorithm would repeatedly have to read the undef mask from
875         // the source and write it to the destination. Even if we optimized the memory accesses,
876         // we'd be doing all of this `repeat` times.
877         // Therefor we precompute a compressed version of the undef mask of the source value and
878         // then write it back `repeat` times without computing any more information from the source.
879
880         // a precomputed cache for ranges of defined/undefined bits
881         // 0000010010001110 will become
882         // [5, 1, 2, 1, 3, 3, 1]
883         // where each element toggles the state
884         let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
885         let first = undef_mask.get(src.offset);
886         let mut cur_len = 1;
887         let mut cur = first;
888         for i in 1..size.bytes() {
889             // FIXME: optimize to bitshift the current undef block's bits and read the top bit
890             if undef_mask.get(src.offset + Size::from_bytes(i)) == cur {
891                 cur_len += 1;
892             } else {
893                 ranges.push(cur_len);
894                 cur_len = 1;
895                 cur = !cur;
896             }
897         }
898
899         // now fill in all the data
900         let dest_allocation = self.get_mut(dest.alloc_id)?;
901         // an optimization where we can just overwrite an entire range of definedness bits if
902         // they are going to be uniformly `1` or `0`.
903         if ranges.is_empty() {
904             dest_allocation.undef_mask.set_range_inbounds(
905                 dest.offset,
906                 dest.offset + size * repeat,
907                 first,
908             );
909             return Ok(())
910         }
911
912         // remember to fill in the trailing bits
913         ranges.push(cur_len);
914
915         for mut j in 0..repeat {
916             j *= size.bytes();
917             j += dest.offset.bytes();
918             let mut cur = first;
919             for range in &ranges {
920                 let old_j = j;
921                 j += range;
922                 dest_allocation.undef_mask.set_range_inbounds(
923                     Size::from_bytes(old_j),
924                     Size::from_bytes(j),
925                     cur,
926                 );
927                 cur = !cur;
928             }
929         }
930         Ok(())
931     }
932
933     pub fn force_ptr(
934         &self,
935         scalar: Scalar<M::PointerTag>,
936     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
937         match scalar {
938             Scalar::Ptr(ptr) => Ok(ptr),
939             _ => M::int_to_ptr(&self, scalar.to_usize(self)?)
940         }
941     }
942
943     pub fn force_bits(
944         &self,
945         scalar: Scalar<M::PointerTag>,
946         size: Size
947     ) -> InterpResult<'tcx, u128> {
948         match scalar.to_bits_or_ptr(size, self) {
949             Ok(bits) => Ok(bits),
950             Err(ptr) => Ok(M::ptr_to_int(&self, ptr)? as u128)
951         }
952     }
953 }