]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
6cbb611c1a3ec461c97b63d7add8775a12bce811
[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, EvalErrorKind, AllocKind, PointerArithmetic,
23     Machine, AllocMap, MayLeak, ErrorHandled, 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 {
136         let extra = AllocationExtra::memory_allocated(size, &self.extra);
137         Pointer::from(self.allocate_with(Allocation::undef(size, align, extra), kind))
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> {
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.with_default_tag().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                 (ptr.offset.bytes(), align)
257             }
258             Scalar::Bits { bits, size } => {
259                 assert_eq!(size as u64, self.pointer_size().bytes());
260                 assert!(bits < (1u128 << self.pointer_size().bits()));
261                 // check this is not NULL
262                 if bits == 0 {
263                     return err!(InvalidNullPointerUsage);
264                 }
265                 // the "base address" is 0 and hence always aligned
266                 (bits as u64, required_align)
267             }
268         };
269         // Check alignment
270         if alloc_align.bytes() < required_align.bytes() {
271             return err!(AlignmentCheckFailed {
272                 has: alloc_align,
273                 required: required_align,
274             });
275         }
276         if offset % required_align.bytes() == 0 {
277             Ok(())
278         } else {
279             let has = offset % required_align.bytes();
280             err!(AlignmentCheckFailed {
281                 has: Align::from_bytes(has).unwrap(),
282                 required: required_align,
283             })
284         }
285     }
286
287     /// Checks if the pointer is "in-bounds". Notice that a pointer pointing at the end
288     /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
289     /// in-bounds!  This follows C's/LLVM's rules.
290     /// If you want to check bounds before doing a memory access, better first obtain
291     /// an `Allocation` and call `check_bounds`.
292     pub fn check_bounds_ptr(
293         &self,
294         ptr: Pointer<M::PointerTag>,
295         liveness: InboundsCheck,
296     ) -> EvalResult<'tcx, Align> {
297         let (allocation_size, align) = self.get_size_and_align(ptr.alloc_id, liveness)?;
298         ptr.check_in_alloc(allocation_size, liveness)?;
299         Ok(align)
300     }
301 }
302
303 /// Allocation accessors
304 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
305     /// Helper function to obtain the global (tcx) allocation for a static.
306     /// This attempts to return a reference to an existing allocation if
307     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
308     /// this machine use the same pointer tag, so it is indirected through
309     /// `M::static_with_default_tag`.
310     fn get_static_alloc(
311         id: AllocId,
312         tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
313         memory_extra: &M::MemoryExtra,
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(AllocKind::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, memory_extra))
321             }
322             Some(AllocKind::Function(..)) => {
323                 return err!(DerefFunctionPointer)
324             }
325             Some(AllocKind::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(def_id, tcx, memory_extra);
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, memory_extra)
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(id, self.tcx, &self.extra).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 memory_extra = &self.extra;
394         let a = self.alloc_map.get_mut_or(id, || {
395             // Need to make a copy, even if `get_static_alloc` is able
396             // to give us a cheap reference.
397             let alloc = Self::get_static_alloc(id, tcx, memory_extra)?;
398             if alloc.mutability == Mutability::Immutable {
399                 return err!(ModifiedConstantMemory);
400             }
401             match M::STATIC_KIND {
402                 Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())),
403                 None => err!(ModifiedStatic),
404             }
405         });
406         // Unpack the error type manually because type inference doesn't
407         // work otherwise (and we cannot help it because `impl Trait`)
408         match a {
409             Err(e) => Err(e),
410             Ok(a) => {
411                 let a = &mut a.1;
412                 if a.mutability == Mutability::Immutable {
413                     return err!(ModifiedConstantMemory);
414                 }
415                 Ok(a)
416             }
417         }
418     }
419
420     /// Obtain the size and alignment of an allocation, even if that allocation has been deallocated
421     ///
422     /// If `liveness` is `InboundsCheck::Dead`, this function always returns `Ok`
423     pub fn get_size_and_align(
424         &self,
425         id: AllocId,
426         liveness: InboundsCheck,
427     ) -> EvalResult<'static, (Size, Align)> {
428         if let Ok(alloc) = self.get(id) {
429             return Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align));
430         }
431         // Could also be a fn ptr or extern static
432         match self.tcx.alloc_map.lock().get(id) {
433             Some(AllocKind::Function(..)) => Ok((Size::ZERO, Align::from_bytes(1).unwrap())),
434             Some(AllocKind::Static(did)) => {
435                 // The only way `get` couldn't have worked here is if this is an extern static
436                 assert!(self.tcx.is_foreign_item(did));
437                 // Use size and align of the type
438                 let ty = self.tcx.type_of(did);
439                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
440                 Ok((layout.size, layout.align.abi))
441             }
442             _ => match liveness {
443                 InboundsCheck::MaybeDead => {
444                     // Must be a deallocated pointer
445                     Ok(*self.dead_alloc_map.get(&id).expect(
446                         "allocation missing in dead_alloc_map"
447                     ))
448                 },
449                 InboundsCheck::Live => err!(DanglingPointerDeref),
450             },
451         }
452     }
453
454     pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
455         if ptr.offset.bytes() != 0 {
456             return err!(InvalidFunctionPointer);
457         }
458         trace!("reading fn ptr: {}", ptr.alloc_id);
459         match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
460             Some(AllocKind::Function(instance)) => Ok(instance),
461             _ => Err(EvalErrorKind::ExecuteMemory.into()),
462         }
463     }
464
465     pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
466         self.get_mut(id)?.mutability = Mutability::Immutable;
467         Ok(())
468     }
469
470     /// For debugging, print an allocation and all allocations it points to, recursively.
471     pub fn dump_alloc(&self, id: AllocId) {
472         self.dump_allocs(vec![id]);
473     }
474
475     fn dump_alloc_helper<Tag, Extra>(
476         &self,
477         allocs_seen: &mut FxHashSet<AllocId>,
478         allocs_to_print: &mut VecDeque<AllocId>,
479         mut msg: String,
480         alloc: &Allocation<Tag, Extra>,
481         extra: String,
482     ) {
483         use std::fmt::Write;
484
485         let prefix_len = msg.len();
486         let mut relocations = vec![];
487
488         for i in 0..(alloc.bytes.len() as u64) {
489             let i = Size::from_bytes(i);
490             if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
491                 if allocs_seen.insert(target_id) {
492                     allocs_to_print.push_back(target_id);
493                 }
494                 relocations.push((i, target_id));
495             }
496             if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
497                 // this `as usize` is fine, since `i` came from a `usize`
498                 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
499             } else {
500                 msg.push_str("__ ");
501             }
502         }
503
504         trace!(
505             "{}({} bytes, alignment {}){}",
506             msg,
507             alloc.bytes.len(),
508             alloc.align.bytes(),
509             extra
510         );
511
512         if !relocations.is_empty() {
513             msg.clear();
514             write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
515             let mut pos = Size::ZERO;
516             let relocation_width = (self.pointer_size().bytes() - 1) * 3;
517             for (i, target_id) in relocations {
518                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
519                 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
520                 let target = format!("({})", target_id);
521                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
522                 write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
523                 pos = i + self.pointer_size();
524             }
525             trace!("{}", msg);
526         }
527     }
528
529     /// For debugging, print a list of allocations and all allocations they point to, recursively.
530     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
531         if !log_enabled!(::log::Level::Trace) {
532             return;
533         }
534         allocs.sort();
535         allocs.dedup();
536         let mut allocs_to_print = VecDeque::from(allocs);
537         let mut allocs_seen = FxHashSet::default();
538
539         while let Some(id) = allocs_to_print.pop_front() {
540             let msg = format!("Alloc {:<5} ", format!("{}:", id));
541
542             // normal alloc?
543             match self.alloc_map.get_or(id, || Err(())) {
544                 Ok((kind, alloc)) => {
545                     let extra = match kind {
546                         MemoryKind::Stack => " (stack)".to_owned(),
547                         MemoryKind::Vtable => " (vtable)".to_owned(),
548                         MemoryKind::Machine(m) => format!(" ({:?})", m),
549                     };
550                     self.dump_alloc_helper(
551                         &mut allocs_seen, &mut allocs_to_print,
552                         msg, alloc, extra
553                     );
554                 },
555                 Err(()) => {
556                     // static alloc?
557                     match self.tcx.alloc_map.lock().get(id) {
558                         Some(AllocKind::Memory(alloc)) => {
559                             self.dump_alloc_helper(
560                                 &mut allocs_seen, &mut allocs_to_print,
561                                 msg, alloc, " (immutable)".to_owned()
562                             );
563                         }
564                         Some(AllocKind::Function(func)) => {
565                             trace!("{} {}", msg, func);
566                         }
567                         Some(AllocKind::Static(did)) => {
568                             trace!("{} {:?}", msg, did);
569                         }
570                         None => {
571                             trace!("{} (deallocated)", msg);
572                         }
573                     }
574                 },
575             };
576
577         }
578     }
579
580     pub fn leak_report(&self) -> usize {
581         trace!("### LEAK REPORT ###");
582         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
583             if kind.may_leak() { None } else { Some(id) }
584         });
585         let n = leaks.len();
586         self.dump_allocs(leaks);
587         n
588     }
589
590     /// This is used by [priroda](https://github.com/oli-obk/priroda)
591     pub fn alloc_map(&self) -> &M::MemoryMap {
592         &self.alloc_map
593     }
594 }
595
596 /// Byte Accessors
597 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
598     pub fn read_bytes(
599         &self,
600         ptr: Scalar<M::PointerTag>,
601         size: Size,
602     ) -> EvalResult<'tcx, &[u8]> {
603         if size.bytes() == 0 {
604             Ok(&[])
605         } else {
606             let ptr = ptr.to_ptr()?;
607             self.get(ptr.alloc_id)?.get_bytes(self, ptr, size)
608         }
609     }
610 }
611
612 /// Interning (for CTFE)
613 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
614 where
615     M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=(), MemoryExtra=()>,
616     // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
617     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
618 {
619     /// mark an allocation as static and initialized, either mutable or not
620     pub fn intern_static(
621         &mut self,
622         alloc_id: AllocId,
623         mutability: Mutability,
624     ) -> EvalResult<'tcx> {
625         trace!(
626             "mark_static_initialized {:?}, mutability: {:?}",
627             alloc_id,
628             mutability
629         );
630         // remove allocation
631         let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
632         match kind {
633             MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
634             MemoryKind::Stack | MemoryKind::Vtable => {},
635         }
636         // ensure llvm knows not to put this into immutable memory
637         alloc.mutability = mutability;
638         let alloc = self.tcx.intern_const_alloc(alloc);
639         self.tcx.alloc_map.lock().set_alloc_id_memory(alloc_id, alloc);
640         // recurse into inner allocations
641         for &(_, alloc) in alloc.relocations.values() {
642             // FIXME: Reusing the mutability here is likely incorrect.  It is originally
643             // determined via `is_freeze`, and data is considered frozen if there is no
644             // `UnsafeCell` *immediately* in that data -- however, this search stops
645             // at references.  So whenever we follow a reference, we should likely
646             // assume immutability -- and we should make sure that the compiler
647             // does not permit code that would break this!
648             if self.alloc_map.contains_key(&alloc) {
649                 // Not yet interned, so proceed recursively
650                 self.intern_static(alloc, mutability)?;
651             } else if self.dead_alloc_map.contains_key(&alloc) {
652                 // dangling pointer
653                 return err!(ValidationFailure(
654                     "encountered dangling pointer in final constant".into(),
655                 ))
656             }
657         }
658         Ok(())
659     }
660 }
661
662 /// Reading and writing.
663 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
664     pub fn copy(
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         nonoverlapping: bool,
672     ) -> EvalResult<'tcx> {
673         self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
674     }
675
676     pub fn copy_repeatedly(
677         &mut self,
678         src: Scalar<M::PointerTag>,
679         src_align: Align,
680         dest: Scalar<M::PointerTag>,
681         dest_align: Align,
682         size: Size,
683         length: u64,
684         nonoverlapping: bool,
685     ) -> EvalResult<'tcx> {
686         self.check_align(src, src_align)?;
687         self.check_align(dest, dest_align)?;
688         if size.bytes() == 0 {
689             // Nothing to do for ZST, other than checking alignment and
690             // non-NULLness which already happened.
691             return Ok(());
692         }
693         let src = src.to_ptr()?;
694         let dest = dest.to_ptr()?;
695
696         // first copy the relocations to a temporary buffer, because
697         // `get_bytes_mut` will clear the relocations, which is correct,
698         // since we don't want to keep any relocations at the target.
699         // (`get_bytes_with_undef_and_ptr` below checks that there are no
700         // relocations overlapping the edges; those would not be handled correctly).
701         let relocations = {
702             let relocations = self.get(src.alloc_id)?.relocations(self, src, size);
703             if relocations.is_empty() {
704                 // nothing to copy, ignore even the `length` loop
705                 Vec::new()
706             } else {
707                 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
708                 for i in 0..length {
709                     new_relocations.extend(
710                         relocations
711                         .iter()
712                         .map(|&(offset, reloc)| {
713                             // compute offset for current repetition
714                             let dest_offset = dest.offset + (i * size);
715                             (
716                                 // shift offsets from source allocation to destination allocation
717                                 offset + dest_offset - src.offset,
718                                 reloc,
719                             )
720                         })
721                     );
722                 }
723
724                 new_relocations
725             }
726         };
727
728         let tcx = self.tcx.tcx;
729
730         // This checks relocation edges on the src.
731         let src_bytes = self.get(src.alloc_id)?
732             .get_bytes_with_undef_and_ptr(&tcx, src, size)?
733             .as_ptr();
734         let dest_bytes = self.get_mut(dest.alloc_id)?
735             .get_bytes_mut(&tcx, dest, size * length)?
736             .as_mut_ptr();
737
738         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
739         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
740         // `dest` could possibly overlap.
741         // The pointers above remain valid even if the `HashMap` table is moved around because they
742         // point into the `Vec` storing the bytes.
743         unsafe {
744             assert_eq!(size.bytes() as usize as u64, size.bytes());
745             if src.alloc_id == dest.alloc_id {
746                 if nonoverlapping {
747                     if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
748                         (dest.offset <= src.offset && dest.offset + size > src.offset)
749                     {
750                         return err!(Intrinsic(
751                             "copy_nonoverlapping called on overlapping ranges".to_string(),
752                         ));
753                     }
754                 }
755
756                 for i in 0..length {
757                     ptr::copy(src_bytes,
758                               dest_bytes.offset((size.bytes() * i) as isize),
759                               size.bytes() as usize);
760                 }
761             } else {
762                 for i in 0..length {
763                     ptr::copy_nonoverlapping(src_bytes,
764                                              dest_bytes.offset((size.bytes() * i) as isize),
765                                              size.bytes() as usize);
766                 }
767             }
768         }
769
770         // copy definedness to the destination
771         self.copy_undef_mask(src, dest, size, length)?;
772         // copy the relocations to the destination
773         self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
774
775         Ok(())
776     }
777 }
778
779 /// Undefined bytes
780 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
781     // FIXME: Add a fast version for the common, nonoverlapping case
782     fn copy_undef_mask(
783         &mut self,
784         src: Pointer<M::PointerTag>,
785         dest: Pointer<M::PointerTag>,
786         size: Size,
787         repeat: u64,
788     ) -> EvalResult<'tcx> {
789         // The bits have to be saved locally before writing to dest in case src and dest overlap.
790         assert_eq!(size.bytes() as usize as u64, size.bytes());
791
792         let undef_mask = &self.get(src.alloc_id)?.undef_mask;
793
794         // a precomputed cache for ranges of defined/undefined bits
795         // 0000010010001110 will become
796         // [5, 1, 2, 1, 3, 3, 1]
797         // where each element toggles the state
798         let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
799         let first = undef_mask.get(src.offset);
800         let mut cur_len = 1;
801         let mut cur = first;
802         for i in 1..size.bytes() {
803             // FIXME: optimize to bitshift the current undef block's bits and read the top bit
804             if undef_mask.get(src.offset + Size::from_bytes(i)) == cur {
805                 cur_len += 1;
806             } else {
807                 ranges.push(cur_len);
808                 cur_len = 1;
809                 cur = !cur;
810             }
811         }
812
813         // now fill in all the data
814         let dest_allocation = self.get_mut(dest.alloc_id)?;
815         // an optimization where we can just overwrite an entire range of definedness bits if
816         // they are going to be uniformly `1` or `0`.
817         if ranges.is_empty() {
818             dest_allocation.undef_mask.set_range(
819                 dest.offset,
820                 dest.offset + size * repeat,
821                 first,
822             );
823             return Ok(())
824         }
825
826         // remember to fill in the trailing bits
827         ranges.push(cur_len);
828
829         for mut j in 0..repeat {
830             j *= size.bytes();
831             j += dest.offset.bytes();
832             let mut cur = first;
833             for range in &ranges {
834                 let old_j = j;
835                 j += range;
836                 dest_allocation.undef_mask.set_range_inbounds(
837                     Size::from_bytes(old_j),
838                     Size::from_bytes(j),
839                     cur,
840                 );
841                 cur = !cur;
842             }
843         }
844         Ok(())
845     }
846 }