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