]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
Auto merge of #55705 - ethanboxx:master, r=SimonSapin
[rust.git] / src / librustc_mir / interpret / memory.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The memory subsystem.
12 //!
13 //! Generally, we use `Pointer` to denote memory addresses. However, some operations
14 //! have a "size"-like parameter, and they take `Scalar` for the address because
15 //! if the size is 0, then the pointer can also be a (properly aligned, non-NULL)
16 //! integer.  It is crucial that these operations call `check_align` *before*
17 //! short-circuiting the empty case!
18
19 use std::collections::VecDeque;
20 use std::ptr;
21 use std::borrow::Cow;
22
23 use rustc::ty::{self, Instance, ParamEnv, query::TyCtxtAt};
24 use rustc::ty::layout::{Align, TargetDataLayout, Size, HasDataLayout};
25 pub use rustc::mir::interpret::{truncate, write_target_uint, read_target_uint};
26 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
27
28 use syntax::ast::Mutability;
29
30 use super::{
31     Pointer, AllocId, Allocation, GlobalId, AllocationExtra,
32     EvalResult, Scalar, EvalErrorKind, AllocType, PointerArithmetic,
33     Machine, AllocMap, MayLeak, ErrorHandled, InboundsCheck,
34 };
35
36 #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
37 pub enum MemoryKind<T> {
38     /// Error if deallocated except during a stack pop
39     Stack,
40     /// Error if ever deallocated
41     Vtable,
42     /// Additional memory kinds a machine wishes to distinguish from the builtin ones
43     Machine(T),
44 }
45
46 impl<T: MayLeak> MayLeak for MemoryKind<T> {
47     #[inline]
48     fn may_leak(self) -> bool {
49         match self {
50             MemoryKind::Stack => false,
51             MemoryKind::Vtable => true,
52             MemoryKind::Machine(k) => k.may_leak()
53         }
54     }
55 }
56
57 // `Memory` has to depend on the `Machine` because some of its operations
58 // (e.g. `get`) call a `Machine` hook.
59 pub struct Memory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
60     /// Allocations local to this instance of the miri engine.  The kind
61     /// helps ensure that the same mechanism is used for allocation and
62     /// deallocation.  When an allocation is not found here, it is a
63     /// static and looked up in the `tcx` for read access.  Some machines may
64     /// have to mutate this map even on a read-only access to a static (because
65     /// they do pointer provenance tracking and the allocations in `tcx` have
66     /// the wrong type), so we let the machine override this type.
67     /// Either way, if the machine allows writing to a static, doing so will
68     /// create a copy of the static allocation here.
69     alloc_map: M::MemoryMap,
70
71     /// To be able to compare pointers with NULL, and to check alignment for accesses
72     /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
73     /// that do not exist any more.
74     dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
75
76     /// Lets us implement `HasDataLayout`, which is awfully convenient.
77     pub(super) tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
78 }
79
80 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
81     for Memory<'a, 'mir, 'tcx, M>
82 {
83     #[inline]
84     fn data_layout(&self) -> &TargetDataLayout {
85         &self.tcx.data_layout
86     }
87 }
88
89 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
90 // carefully copy only the reachable parts.
91 impl<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>>
92     Clone for Memory<'a, 'mir, 'tcx, M>
93 {
94     fn clone(&self) -> Self {
95         Memory {
96             alloc_map: self.alloc_map.clone(),
97             dead_alloc_map: self.dead_alloc_map.clone(),
98             tcx: self.tcx,
99         }
100     }
101 }
102
103 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
104     pub fn new(tcx: TyCtxtAt<'a, 'tcx, 'tcx>) -> Self {
105         Memory {
106             alloc_map: Default::default(),
107             dead_alloc_map: FxHashMap::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     ) -> EvalResult<'tcx, AllocId> {
125         let id = self.tcx.alloc_map.lock().reserve();
126         self.alloc_map.insert(id, (kind, alloc));
127         Ok(id)
128     }
129
130     pub fn allocate(
131         &mut self,
132         size: Size,
133         align: Align,
134         kind: MemoryKind<M::MemoryKinds>,
135     ) -> EvalResult<'tcx, Pointer> {
136         Ok(Pointer::from(self.allocate_with(Allocation::undef(size, align), kind)?))
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> {
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.with_default_tag().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(AllocType::Function(..)) => err!(DeallocatedWrongMemoryKind(
197                         "function".to_string(),
198                         format!("{:?}", kind),
199                     )),
200                     Some(AllocType::Static(..)) |
201                     Some(AllocType::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     /// Check 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 {
251             Scalar::Ptr(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_maybe_dead(ptr)?;
255                 (ptr.offset.bytes(), align)
256             }
257             Scalar::Bits { bits, size } => {
258                 assert_eq!(size as u64, self.pointer_size().bytes());
259                 assert!(bits < (1u128 << self.pointer_size().bits()));
260                 // check this is not NULL
261                 if bits == 0 {
262                     return err!(InvalidNullPointerUsage);
263                 }
264                 // the "base address" is 0 and hence always aligned
265                 (bits as u64, required_align)
266             }
267         };
268         // Check alignment
269         if alloc_align.bytes() < required_align.bytes() {
270             return err!(AlignmentCheckFailed {
271                 has: alloc_align,
272                 required: required_align,
273             });
274         }
275         if offset % required_align.bytes() == 0 {
276             Ok(())
277         } else {
278             let has = offset % required_align.bytes();
279             err!(AlignmentCheckFailed {
280                 has: Align::from_bytes(has).unwrap(),
281                 required: required_align,
282             })
283         }
284     }
285
286     /// Check if the pointer is "in-bounds". Notice that a pointer pointing at the end
287     /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
288     /// in-bounds!  This follows C's/LLVM's rules.
289     /// This function also works for deallocated allocations.
290     /// Use `.get(ptr.alloc_id)?.check_bounds_ptr(ptr)` if you want to force the allocation
291     /// to still be live.
292     /// If you want to check bounds before doing a memory access, better first obtain
293     /// an `Allocation` and call `check_bounds`.
294     pub fn check_bounds_ptr_maybe_dead(
295         &self,
296         ptr: Pointer<M::PointerTag>,
297     ) -> EvalResult<'tcx, Align> {
298         let (allocation_size, align) = self.get_size_and_align(ptr.alloc_id);
299         ptr.check_in_alloc(allocation_size, InboundsCheck::MaybeDead)?;
300         Ok(align)
301     }
302 }
303
304 /// Allocation accessors
305 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
306     /// Helper function to obtain the global (tcx) allocation for a static.
307     /// This attempts to return a reference to an existing allocation if
308     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
309     /// this machine use the same pointer tag, so it is indirected through
310     /// `M::static_with_default_tag`.
311     fn get_static_alloc(
312         tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
313         id: AllocId,
314     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
315         let alloc = tcx.alloc_map.lock().get(id);
316         let def_id = match alloc {
317             Some(AllocType::Memory(mem)) => {
318                 // We got tcx memory. Let the machine figure out whether and how to
319                 // turn that into memory with the right pointer tag.
320                 return Ok(M::adjust_static_allocation(mem))
321             }
322             Some(AllocType::Function(..)) => {
323                 return err!(DerefFunctionPointer)
324             }
325             Some(AllocType::Static(did)) => {
326                 did
327             }
328             None =>
329                 return err!(DanglingPointerDeref),
330         };
331         // We got a "lazy" static that has not been computed yet, do some work
332         trace!("static_alloc: Need to compute {:?}", def_id);
333         if tcx.is_foreign_item(def_id) {
334             return M::find_foreign_static(tcx, def_id);
335         }
336         let instance = Instance::mono(tcx.tcx, def_id);
337         let gid = GlobalId {
338             instance,
339             promoted: None,
340         };
341         // use the raw query here to break validation cycles. Later uses of the static will call the
342         // full query anyway
343         tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
344             // no need to report anything, the const_eval call takes care of that for statics
345             assert!(tcx.is_static(def_id).is_some());
346             match err {
347                 ErrorHandled::Reported => EvalErrorKind::ReferencedConstant.into(),
348                 ErrorHandled::TooGeneric => EvalErrorKind::TooGeneric.into(),
349             }
350         }).map(|raw_const| {
351             let allocation = tcx.alloc_map.lock().unwrap_memory(raw_const.alloc_id);
352             // We got tcx memory. Let the machine figure out whether and how to
353             // turn that into memory with the right pointer tag.
354             M::adjust_static_allocation(allocation)
355         })
356     }
357
358     pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
359         // The error type of the inner closure here is somewhat funny.  We have two
360         // ways of "erroring": An actual error, or because we got a reference from
361         // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
362         // So the error type is `EvalResult<'tcx, &Allocation<M::PointerTag>>`.
363         let a = self.alloc_map.get_or(id, || {
364             let alloc = Self::get_static_alloc(self.tcx, id).map_err(Err)?;
365             match alloc {
366                 Cow::Borrowed(alloc) => {
367                     // We got a ref, cheaply return that as an "error" so that the
368                     // map does not get mutated.
369                     Err(Ok(alloc))
370                 }
371                 Cow::Owned(alloc) => {
372                     // Need to put it into the map and return a ref to that
373                     let kind = M::STATIC_KIND.expect(
374                         "I got an owned allocation that I have to copy but the machine does \
375                             not expect that to happen"
376                     );
377                     Ok((MemoryKind::Machine(kind), alloc))
378                 }
379             }
380         });
381         // Now unpack that funny error type
382         match a {
383             Ok(a) => Ok(&a.1),
384             Err(a) => a
385         }
386     }
387
388     pub fn get_mut(
389         &mut self,
390         id: AllocId,
391     ) -> EvalResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
392         let tcx = self.tcx;
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(tcx, id)?;
397             if alloc.mutability == Mutability::Immutable {
398                 return err!(ModifiedConstantMemory);
399             }
400             let kind = M::STATIC_KIND.expect(
401                 "An allocation is being mutated but the machine does not expect that to happen"
402             );
403             Ok((MemoryKind::Machine(kind), alloc.into_owned()))
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     pub fn get_size_and_align(&self, id: AllocId) -> (Size, Align) {
420         if let Ok(alloc) = self.get(id) {
421             return (Size::from_bytes(alloc.bytes.len() as u64), alloc.align);
422         }
423         // Could also be a fn ptr or extern static
424         match self.tcx.alloc_map.lock().get(id) {
425             Some(AllocType::Function(..)) => (Size::ZERO, Align::from_bytes(1).unwrap()),
426             Some(AllocType::Static(did)) => {
427                 // The only way `get` couldn't have worked here is if this is an extern static
428                 assert!(self.tcx.is_foreign_item(did));
429                 // Use size and align of the type
430                 let ty = self.tcx.type_of(did);
431                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
432                 (layout.size, layout.align.abi)
433             }
434             _ => {
435                 // Must be a deallocated pointer
436                 *self.dead_alloc_map.get(&id).expect(
437                     "allocation missing in dead_alloc_map"
438                 )
439             }
440         }
441     }
442
443     pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
444         if ptr.offset.bytes() != 0 {
445             return err!(InvalidFunctionPointer);
446         }
447         trace!("reading fn ptr: {}", ptr.alloc_id);
448         match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
449             Some(AllocType::Function(instance)) => Ok(instance),
450             _ => Err(EvalErrorKind::ExecuteMemory.into()),
451         }
452     }
453
454     pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
455         self.get_mut(id)?.mutability = Mutability::Immutable;
456         Ok(())
457     }
458
459     /// For debugging, print an allocation and all allocations it points to, recursively.
460     pub fn dump_alloc(&self, id: AllocId) {
461         self.dump_allocs(vec![id]);
462     }
463
464     fn dump_alloc_helper<Tag, Extra>(
465         &self,
466         allocs_seen: &mut FxHashSet<AllocId>,
467         allocs_to_print: &mut VecDeque<AllocId>,
468         mut msg: String,
469         alloc: &Allocation<Tag, Extra>,
470         extra: String,
471     ) {
472         use std::fmt::Write;
473
474         let prefix_len = msg.len();
475         let mut relocations = vec![];
476
477         for i in 0..(alloc.bytes.len() as u64) {
478             let i = Size::from_bytes(i);
479             if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
480                 if allocs_seen.insert(target_id) {
481                     allocs_to_print.push_back(target_id);
482                 }
483                 relocations.push((i, target_id));
484             }
485             if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
486                 // this `as usize` is fine, since `i` came from a `usize`
487                 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
488             } else {
489                 msg.push_str("__ ");
490             }
491         }
492
493         trace!(
494             "{}({} bytes, alignment {}){}",
495             msg,
496             alloc.bytes.len(),
497             alloc.align.bytes(),
498             extra
499         );
500
501         if !relocations.is_empty() {
502             msg.clear();
503             write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
504             let mut pos = Size::ZERO;
505             let relocation_width = (self.pointer_size().bytes() - 1) * 3;
506             for (i, target_id) in relocations {
507                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
508                 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
509                 let target = format!("({})", target_id);
510                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
511                 write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
512                 pos = i + self.pointer_size();
513             }
514             trace!("{}", msg);
515         }
516     }
517
518     /// For debugging, print a list of allocations and all allocations they point to, recursively.
519     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
520         if !log_enabled!(::log::Level::Trace) {
521             return;
522         }
523         allocs.sort();
524         allocs.dedup();
525         let mut allocs_to_print = VecDeque::from(allocs);
526         let mut allocs_seen = FxHashSet::default();
527
528         while let Some(id) = allocs_to_print.pop_front() {
529             let msg = format!("Alloc {:<5} ", format!("{}:", id));
530
531             // normal alloc?
532             match self.alloc_map.get_or(id, || Err(())) {
533                 Ok((kind, alloc)) => {
534                     let extra = match kind {
535                         MemoryKind::Stack => " (stack)".to_owned(),
536                         MemoryKind::Vtable => " (vtable)".to_owned(),
537                         MemoryKind::Machine(m) => format!(" ({:?})", m),
538                     };
539                     self.dump_alloc_helper(
540                         &mut allocs_seen, &mut allocs_to_print,
541                         msg, alloc, extra
542                     );
543                 },
544                 Err(()) => {
545                     // static alloc?
546                     match self.tcx.alloc_map.lock().get(id) {
547                         Some(AllocType::Memory(alloc)) => {
548                             self.dump_alloc_helper(
549                                 &mut allocs_seen, &mut allocs_to_print,
550                                 msg, alloc, " (immutable)".to_owned()
551                             );
552                         }
553                         Some(AllocType::Function(func)) => {
554                             trace!("{} {}", msg, func);
555                         }
556                         Some(AllocType::Static(did)) => {
557                             trace!("{} {:?}", msg, did);
558                         }
559                         None => {
560                             trace!("{} (deallocated)", msg);
561                         }
562                     }
563                 },
564             };
565
566         }
567     }
568
569     pub fn leak_report(&self) -> usize {
570         trace!("### LEAK REPORT ###");
571         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
572             if kind.may_leak() { None } else { Some(id) }
573         });
574         let n = leaks.len();
575         self.dump_allocs(leaks);
576         n
577     }
578
579     /// This is used by [priroda](https://github.com/oli-obk/priroda)
580     pub fn alloc_map(&self) -> &M::MemoryMap {
581         &self.alloc_map
582     }
583 }
584
585 /// Byte Accessors
586 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
587     pub fn read_bytes(
588         &self,
589         ptr: Scalar<M::PointerTag>,
590         size: Size,
591     ) -> EvalResult<'tcx, &[u8]> {
592         if size.bytes() == 0 {
593             Ok(&[])
594         } else {
595             let ptr = ptr.to_ptr()?;
596             self.get(ptr.alloc_id)?.get_bytes(self, ptr, size)
597         }
598     }
599 }
600
601 /// Interning (for CTFE)
602 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
603 where
604     M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=()>,
605     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
606 {
607     /// mark an allocation as static and initialized, either mutable or not
608     pub fn intern_static(
609         &mut self,
610         alloc_id: AllocId,
611         mutability: Mutability,
612     ) -> EvalResult<'tcx> {
613         trace!(
614             "mark_static_initialized {:?}, mutability: {:?}",
615             alloc_id,
616             mutability
617         );
618         // remove allocation
619         let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
620         match kind {
621             MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
622             MemoryKind::Stack | MemoryKind::Vtable => {},
623         }
624         // ensure llvm knows not to put this into immutable memory
625         alloc.mutability = mutability;
626         let alloc = self.tcx.intern_const_alloc(alloc);
627         self.tcx.alloc_map.lock().set_id_memory(alloc_id, alloc);
628         // recurse into inner allocations
629         for &(_, alloc) in alloc.relocations.values() {
630             // FIXME: Reusing the mutability here is likely incorrect.  It is originally
631             // determined via `is_freeze`, and data is considered frozen if there is no
632             // `UnsafeCell` *immediately* in that data -- however, this search stops
633             // at references.  So whenever we follow a reference, we should likely
634             // assume immutability -- and we should make sure that the compiler
635             // does not permit code that would break this!
636             if self.alloc_map.contains_key(&alloc) {
637                 // Not yet interned, so proceed recursively
638                 self.intern_static(alloc, mutability)?;
639             } else if self.dead_alloc_map.contains_key(&alloc) {
640                 // dangling pointer
641                 return err!(ValidationFailure(
642                     "encountered dangling pointer in final constant".into(),
643                 ))
644             }
645         }
646         Ok(())
647     }
648 }
649
650 /// Reading and writing
651 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
652     pub fn copy(
653         &mut self,
654         src: Scalar<M::PointerTag>,
655         src_align: Align,
656         dest: Scalar<M::PointerTag>,
657         dest_align: Align,
658         size: Size,
659         nonoverlapping: bool,
660     ) -> EvalResult<'tcx> {
661         self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
662     }
663
664     pub fn copy_repeatedly(
665         &mut self,
666         src: Scalar<M::PointerTag>,
667         src_align: Align,
668         dest: Scalar<M::PointerTag>,
669         dest_align: Align,
670         size: Size,
671         length: u64,
672         nonoverlapping: bool,
673     ) -> EvalResult<'tcx> {
674         self.check_align(src, src_align)?;
675         self.check_align(dest, dest_align)?;
676         if size.bytes() == 0 {
677             // Nothing to do for ZST, other than checking alignment and
678             // non-NULLness which already happened.
679             return Ok(());
680         }
681         let src = src.to_ptr()?;
682         let dest = dest.to_ptr()?;
683
684         // first copy the relocations to a temporary buffer, because
685         // `get_bytes_mut` will clear the relocations, which is correct,
686         // since we don't want to keep any relocations at the target.
687         // (`get_bytes_with_undef_and_ptr` below checks that there are no
688         // relocations overlapping the edges; those would not be handled correctly).
689         let relocations = {
690             let relocations = self.get(src.alloc_id)?.relocations(self, src, size);
691             let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
692             for i in 0..length {
693                 new_relocations.extend(
694                     relocations
695                     .iter()
696                     .map(|&(offset, reloc)| {
697                     (offset + dest.offset - src.offset + (i * size * relocations.len() as u64),
698                      reloc)
699                     })
700                 );
701             }
702
703             new_relocations
704         };
705
706         let tcx = self.tcx.tcx;
707
708         // This checks relocation edges on the src.
709         let src_bytes = self.get(src.alloc_id)?
710             .get_bytes_with_undef_and_ptr(&tcx, src, size)?
711             .as_ptr();
712         let dest_bytes = self.get_mut(dest.alloc_id)?
713             .get_bytes_mut(&tcx, dest, size * length)?
714             .as_mut_ptr();
715
716         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
717         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
718         // `dest` could possibly overlap.
719         // The pointers above remain valid even if the `HashMap` table is moved around because they
720         // point into the `Vec` storing the bytes.
721         unsafe {
722             assert_eq!(size.bytes() as usize as u64, size.bytes());
723             if src.alloc_id == dest.alloc_id {
724                 if nonoverlapping {
725                     if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
726                         (dest.offset <= src.offset && dest.offset + size > src.offset)
727                     {
728                         return err!(Intrinsic(
729                             "copy_nonoverlapping called on overlapping ranges".to_string(),
730                         ));
731                     }
732                 }
733
734                 for i in 0..length {
735                     ptr::copy(src_bytes,
736                               dest_bytes.offset((size.bytes() * i) as isize),
737                               size.bytes() as usize);
738                 }
739             } else {
740                 for i in 0..length {
741                     ptr::copy_nonoverlapping(src_bytes,
742                                              dest_bytes.offset((size.bytes() * i) as isize),
743                                              size.bytes() as usize);
744                 }
745             }
746         }
747
748         // copy definedness to the destination
749         self.copy_undef_mask(src, dest, size, length)?;
750         // copy the relocations to the destination
751         self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
752
753         Ok(())
754     }
755 }
756
757 /// Undefined bytes
758 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
759     // FIXME: Add a fast version for the common, nonoverlapping case
760     fn copy_undef_mask(
761         &mut self,
762         src: Pointer<M::PointerTag>,
763         dest: Pointer<M::PointerTag>,
764         size: Size,
765         repeat: u64,
766     ) -> EvalResult<'tcx> {
767         // The bits have to be saved locally before writing to dest in case src and dest overlap.
768         assert_eq!(size.bytes() as usize as u64, size.bytes());
769
770         let undef_mask = self.get(src.alloc_id)?.undef_mask.clone();
771         let dest_allocation = self.get_mut(dest.alloc_id)?;
772
773         for i in 0..size.bytes() {
774             let defined = undef_mask.get(src.offset + Size::from_bytes(i));
775
776             for j in 0..repeat {
777                 dest_allocation.undef_mask.set(
778                     dest.offset + Size::from_bytes(i + (size.bytes() * j)),
779                     defined
780                 );
781             }
782         }
783
784         Ok(())
785     }
786 }