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