]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
Move alignment and bounds check from `Memory` to `Allocation`
[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::{self, 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, InboundsCheck,
32     EvalResult, Scalar, EvalErrorKind, AllocType, PointerArithmetic,
33     Machine, AllocMap, MayLeak, ScalarMaybeUndef, ErrorHandled,
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                 self.check_bounds_ptr(ptr, InboundsCheck::MaybeDead)?;
255                 // data required for alignment check
256                 let (_, align) = self.get_size_and_align(ptr.alloc_id);
257                 (ptr.offset.bytes(), align)
258             }
259             Scalar::Bits { bits, size } => {
260                 assert_eq!(size as u64, self.pointer_size().bytes());
261                 assert!(bits < (1u128 << self.pointer_size().bits()));
262                 // check this is not NULL
263                 if bits == 0 {
264                     return err!(InvalidNullPointerUsage);
265                 }
266                 // the "base address" is 0 and hence always aligned
267                 (bits as u64, required_align)
268             }
269         };
270         // Check alignment
271         if alloc_align.bytes() < required_align.bytes() {
272             return err!(AlignmentCheckFailed {
273                 has: alloc_align,
274                 required: required_align,
275             });
276         }
277         if offset % required_align.bytes() == 0 {
278             Ok(())
279         } else {
280             let has = offset % required_align.bytes();
281             err!(AlignmentCheckFailed {
282                 has: Align::from_bytes(has).unwrap(),
283                 required: required_align,
284             })
285         }
286     }
287 }
288
289 /// Allocation accessors
290 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
291     /// Helper function to obtain the global (tcx) allocation for a static.
292     /// This attempts to return a reference to an existing allocation if
293     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
294     /// this machine use the same pointer tag, so it is indirected through
295     /// `M::static_with_default_tag`.
296     fn get_static_alloc(
297         tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
298         id: AllocId,
299     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
300         let alloc = tcx.alloc_map.lock().get(id);
301         let def_id = match alloc {
302             Some(AllocType::Memory(mem)) => {
303                 // We got tcx memory. Let the machine figure out whether and how to
304                 // turn that into memory with the right pointer tag.
305                 return Ok(M::adjust_static_allocation(mem))
306             }
307             Some(AllocType::Function(..)) => {
308                 return err!(DerefFunctionPointer)
309             }
310             Some(AllocType::Static(did)) => {
311                 did
312             }
313             None =>
314                 return err!(DanglingPointerDeref),
315         };
316         // We got a "lazy" static that has not been computed yet, do some work
317         trace!("static_alloc: Need to compute {:?}", def_id);
318         if tcx.is_foreign_item(def_id) {
319             return M::find_foreign_static(tcx, def_id);
320         }
321         let instance = Instance::mono(tcx.tcx, def_id);
322         let gid = GlobalId {
323             instance,
324             promoted: None,
325         };
326         // use the raw query here to break validation cycles. Later uses of the static will call the
327         // full query anyway
328         tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
329             // no need to report anything, the const_eval call takes care of that for statics
330             assert!(tcx.is_static(def_id).is_some());
331             match err {
332                 ErrorHandled::Reported => EvalErrorKind::ReferencedConstant.into(),
333                 ErrorHandled::TooGeneric => EvalErrorKind::TooGeneric.into(),
334             }
335         }).map(|raw_const| {
336             let allocation = tcx.alloc_map.lock().unwrap_memory(raw_const.alloc_id);
337             // We got tcx memory. Let the machine figure out whether and how to
338             // turn that into memory with the right pointer tag.
339             M::adjust_static_allocation(allocation)
340         })
341     }
342
343     pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
344         // The error type of the inner closure here is somewhat funny.  We have two
345         // ways of "erroring": An actual error, or because we got a reference from
346         // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
347         // So the error type is `EvalResult<'tcx, &Allocation<M::PointerTag>>`.
348         let a = self.alloc_map.get_or(id, || {
349             let alloc = Self::get_static_alloc(self.tcx, id).map_err(Err)?;
350             match alloc {
351                 Cow::Borrowed(alloc) => {
352                     // We got a ref, cheaply return that as an "error" so that the
353                     // map does not get mutated.
354                     Err(Ok(alloc))
355                 }
356                 Cow::Owned(alloc) => {
357                     // Need to put it into the map and return a ref to that
358                     let kind = M::STATIC_KIND.expect(
359                         "I got an owned allocation that I have to copy but the machine does \
360                             not expect that to happen"
361                     );
362                     Ok((MemoryKind::Machine(kind), alloc))
363                 }
364             }
365         });
366         // Now unpack that funny error type
367         match a {
368             Ok(a) => Ok(&a.1),
369             Err(a) => a
370         }
371     }
372
373     pub fn get_mut(
374         &mut self,
375         id: AllocId,
376     ) -> EvalResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
377         let tcx = self.tcx;
378         let a = self.alloc_map.get_mut_or(id, || {
379             // Need to make a copy, even if `get_static_alloc` is able
380             // to give us a cheap reference.
381             let alloc = Self::get_static_alloc(tcx, id)?;
382             if alloc.mutability == Mutability::Immutable {
383                 return err!(ModifiedConstantMemory);
384             }
385             let kind = M::STATIC_KIND.expect(
386                 "An allocation is being mutated but the machine does not expect that to happen"
387             );
388             Ok((MemoryKind::Machine(kind), alloc.into_owned()))
389         });
390         // Unpack the error type manually because type inference doesn't
391         // work otherwise (and we cannot help it because `impl Trait`)
392         match a {
393             Err(e) => Err(e),
394             Ok(a) => {
395                 let a = &mut a.1;
396                 if a.mutability == Mutability::Immutable {
397                     return err!(ModifiedConstantMemory);
398                 }
399                 Ok(a)
400             }
401         }
402     }
403
404     pub fn get_size_and_align(&self, id: AllocId) -> (Size, Align) {
405         if let Ok(alloc) = self.get(id) {
406             return (Size::from_bytes(alloc.bytes.len() as u64), alloc.align);
407         }
408         // Could also be a fn ptr or extern static
409         match self.tcx.alloc_map.lock().get(id) {
410             Some(AllocType::Function(..)) => (Size::ZERO, Align::from_bytes(1).unwrap()),
411             Some(AllocType::Static(did)) => {
412                 // The only way `get` couldn't have worked here is if this is an extern static
413                 assert!(self.tcx.is_foreign_item(did));
414                 // Use size and align of the type
415                 let ty = self.tcx.type_of(did);
416                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
417                 (layout.size, layout.align.abi)
418             }
419             _ => {
420                 // Must be a deallocated pointer
421                 *self.dead_alloc_map.get(&id).expect(
422                     "allocation missing in dead_alloc_map"
423                 )
424             }
425         }
426     }
427
428     pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
429         if ptr.offset.bytes() != 0 {
430             return err!(InvalidFunctionPointer);
431         }
432         trace!("reading fn ptr: {}", ptr.alloc_id);
433         match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
434             Some(AllocType::Function(instance)) => Ok(instance),
435             _ => Err(EvalErrorKind::ExecuteMemory.into()),
436         }
437     }
438
439     pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
440         self.get_mut(id)?.mutability = Mutability::Immutable;
441         Ok(())
442     }
443
444     /// For debugging, print an allocation and all allocations it points to, recursively.
445     pub fn dump_alloc(&self, id: AllocId) {
446         self.dump_allocs(vec![id]);
447     }
448
449     fn dump_alloc_helper<Tag, Extra>(
450         &self,
451         allocs_seen: &mut FxHashSet<AllocId>,
452         allocs_to_print: &mut VecDeque<AllocId>,
453         mut msg: String,
454         alloc: &Allocation<Tag, Extra>,
455         extra: String,
456     ) {
457         use std::fmt::Write;
458
459         let prefix_len = msg.len();
460         let mut relocations = vec![];
461
462         for i in 0..(alloc.bytes.len() as u64) {
463             let i = Size::from_bytes(i);
464             if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
465                 if allocs_seen.insert(target_id) {
466                     allocs_to_print.push_back(target_id);
467                 }
468                 relocations.push((i, target_id));
469             }
470             if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
471                 // this `as usize` is fine, since `i` came from a `usize`
472                 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
473             } else {
474                 msg.push_str("__ ");
475             }
476         }
477
478         trace!(
479             "{}({} bytes, alignment {}){}",
480             msg,
481             alloc.bytes.len(),
482             alloc.align.bytes(),
483             extra
484         );
485
486         if !relocations.is_empty() {
487             msg.clear();
488             write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
489             let mut pos = Size::ZERO;
490             let relocation_width = (self.pointer_size().bytes() - 1) * 3;
491             for (i, target_id) in relocations {
492                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
493                 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
494                 let target = format!("({})", target_id);
495                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
496                 write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
497                 pos = i + self.pointer_size();
498             }
499             trace!("{}", msg);
500         }
501     }
502
503     /// For debugging, print a list of allocations and all allocations they point to, recursively.
504     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
505         if !log_enabled!(::log::Level::Trace) {
506             return;
507         }
508         allocs.sort();
509         allocs.dedup();
510         let mut allocs_to_print = VecDeque::from(allocs);
511         let mut allocs_seen = FxHashSet::default();
512
513         while let Some(id) = allocs_to_print.pop_front() {
514             let msg = format!("Alloc {:<5} ", format!("{}:", id));
515
516             // normal alloc?
517             match self.alloc_map.get_or(id, || Err(())) {
518                 Ok((kind, alloc)) => {
519                     let extra = match kind {
520                         MemoryKind::Stack => " (stack)".to_owned(),
521                         MemoryKind::Vtable => " (vtable)".to_owned(),
522                         MemoryKind::Machine(m) => format!(" ({:?})", m),
523                     };
524                     self.dump_alloc_helper(
525                         &mut allocs_seen, &mut allocs_to_print,
526                         msg, alloc, extra
527                     );
528                 },
529                 Err(()) => {
530                     // static alloc?
531                     match self.tcx.alloc_map.lock().get(id) {
532                         Some(AllocType::Memory(alloc)) => {
533                             self.dump_alloc_helper(
534                                 &mut allocs_seen, &mut allocs_to_print,
535                                 msg, alloc, " (immutable)".to_owned()
536                             );
537                         }
538                         Some(AllocType::Function(func)) => {
539                             trace!("{} {}", msg, func);
540                         }
541                         Some(AllocType::Static(did)) => {
542                             trace!("{} {:?}", msg, did);
543                         }
544                         None => {
545                             trace!("{} (deallocated)", msg);
546                         }
547                     }
548                 },
549             };
550
551         }
552     }
553
554     pub fn leak_report(&self) -> usize {
555         trace!("### LEAK REPORT ###");
556         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
557             if kind.may_leak() { None } else { Some(id) }
558         });
559         let n = leaks.len();
560         self.dump_allocs(leaks);
561         n
562     }
563
564     /// This is used by [priroda](https://github.com/oli-obk/priroda)
565     pub fn alloc_map(&self) -> &M::MemoryMap {
566         &self.alloc_map
567     }
568 }
569
570 /// Interning (for CTFE)
571 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
572 where
573     M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=()>,
574     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
575 {
576     /// mark an allocation as static and initialized, either mutable or not
577     pub fn intern_static(
578         &mut self,
579         alloc_id: AllocId,
580         mutability: Mutability,
581     ) -> EvalResult<'tcx> {
582         trace!(
583             "mark_static_initialized {:?}, mutability: {:?}",
584             alloc_id,
585             mutability
586         );
587         // remove allocation
588         let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
589         match kind {
590             MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
591             MemoryKind::Stack | MemoryKind::Vtable => {},
592         }
593         // ensure llvm knows not to put this into immutable memory
594         alloc.mutability = mutability;
595         let alloc = self.tcx.intern_const_alloc(alloc);
596         self.tcx.alloc_map.lock().set_id_memory(alloc_id, alloc);
597         // recurse into inner allocations
598         for &(_, alloc) in alloc.relocations.values() {
599             // FIXME: Reusing the mutability here is likely incorrect.  It is originally
600             // determined via `is_freeze`, and data is considered frozen if there is no
601             // `UnsafeCell` *immediately* in that data -- however, this search stops
602             // at references.  So whenever we follow a reference, we should likely
603             // assume immutability -- and we should make sure that the compiler
604             // does not permit code that would break this!
605             if self.alloc_map.contains_key(&alloc) {
606                 // Not yet interned, so proceed recursively
607                 self.intern_static(alloc, mutability)?;
608             } else if self.dead_alloc_map.contains_key(&alloc) {
609                 // dangling pointer
610                 return err!(ValidationFailure(
611                     "encountered dangling pointer in final constant".into(),
612                 ))
613             }
614         }
615         Ok(())
616     }
617 }
618
619 /// Reading and writing
620 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
621     pub fn copy(
622         &mut self,
623         src: Scalar<M::PointerTag>,
624         src_align: Align,
625         dest: Scalar<M::PointerTag>,
626         dest_align: Align,
627         size: Size,
628         nonoverlapping: bool,
629     ) -> EvalResult<'tcx> {
630         self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
631     }
632
633     pub fn copy_repeatedly(
634         &mut self,
635         src: Scalar<M::PointerTag>,
636         src_align: Align,
637         dest: Scalar<M::PointerTag>,
638         dest_align: Align,
639         size: Size,
640         length: u64,
641         nonoverlapping: bool,
642     ) -> EvalResult<'tcx> {
643         if size.bytes() == 0 {
644             // Nothing to do for ZST, other than checking alignment and non-NULLness.
645             self.check_align(src, src_align)?;
646             self.check_align(dest, dest_align)?;
647             return Ok(());
648         }
649         let src = src.to_ptr()?;
650         let dest = dest.to_ptr()?;
651
652         // first copy the relocations to a temporary buffer, because
653         // `get_bytes_mut` will clear the relocations, which is correct,
654         // since we don't want to keep any relocations at the target.
655         // (`get_bytes_with_undef_and_ptr` below checks that there are no
656         // relocations overlapping the edges; those would not be handled correctly).
657         let relocations = {
658             let relocations = self.relocations(src, size)?;
659             let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
660             for i in 0..length {
661                 new_relocations.extend(
662                     relocations
663                     .iter()
664                     .map(|&(offset, reloc)| {
665                     (offset + dest.offset - src.offset + (i * size * relocations.len() as u64),
666                      reloc)
667                     })
668                 );
669             }
670
671             new_relocations
672         };
673
674         // This also checks alignment, and relocation edges on the src.
675         let src_bytes = self.get_bytes_with_undef_and_ptr(src, size, src_align)?.as_ptr();
676         let dest_bytes = self.get_bytes_mut(dest, size * length, dest_align)?.as_mut_ptr();
677
678         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
679         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
680         // `dest` could possibly overlap.
681         // The pointers above remain valid even if the `HashMap` table is moved around because they
682         // point into the `Vec` storing the bytes.
683         unsafe {
684             assert_eq!(size.bytes() as usize as u64, size.bytes());
685             if src.alloc_id == dest.alloc_id {
686                 if nonoverlapping {
687                     if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
688                         (dest.offset <= src.offset && dest.offset + size > src.offset)
689                     {
690                         return err!(Intrinsic(
691                             "copy_nonoverlapping called on overlapping ranges".to_string(),
692                         ));
693                     }
694                 }
695
696                 for i in 0..length {
697                     ptr::copy(src_bytes,
698                               dest_bytes.offset((size.bytes() * i) as isize),
699                               size.bytes() as usize);
700                 }
701             } else {
702                 for i in 0..length {
703                     ptr::copy_nonoverlapping(src_bytes,
704                                              dest_bytes.offset((size.bytes() * i) as isize),
705                                              size.bytes() as usize);
706                 }
707             }
708         }
709
710         // copy definedness to the destination
711         self.copy_undef_mask(src, dest, size, length)?;
712         // copy the relocations to the destination
713         self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
714
715         Ok(())
716     }
717
718     pub fn read_c_str(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, &[u8]> {
719         let alloc = self.get(ptr.alloc_id)?;
720         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
721         let offset = ptr.offset.bytes() as usize;
722         match alloc.bytes[offset..].iter().position(|&c| c == 0) {
723             Some(size) => {
724                 let p1 = Size::from_bytes((size + 1) as u64);
725                 self.check_relocations(ptr, p1)?;
726                 self.check_defined(ptr, p1)?;
727                 Ok(&alloc.bytes[offset..offset + size])
728             }
729             None => err!(UnterminatedCString(ptr.erase_tag())),
730         }
731     }
732
733     pub fn check_bytes(
734         &self,
735         ptr: Scalar<M::PointerTag>,
736         size: Size,
737         allow_ptr_and_undef: bool,
738     ) -> EvalResult<'tcx> {
739         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
740         let align = Align::from_bytes(1).unwrap();
741         if size.bytes() == 0 {
742             self.check_align(ptr, align)?;
743             return Ok(());
744         }
745         let ptr = ptr.to_ptr()?;
746         // Check bounds, align and relocations on the edges
747         self.get_bytes_with_undef_and_ptr(ptr, size, align)?;
748         // Check undef and ptr
749         if !allow_ptr_and_undef {
750             self.check_defined(ptr, size)?;
751             self.check_relocations(ptr, size)?;
752         }
753         Ok(())
754     }
755
756     pub fn read_bytes(&self, ptr: Scalar<M::PointerTag>, size: Size) -> EvalResult<'tcx, &[u8]> {
757         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
758         let align = Align::from_bytes(1).unwrap();
759         if size.bytes() == 0 {
760             self.check_align(ptr, align)?;
761             return Ok(&[]);
762         }
763         self.get_bytes(ptr.to_ptr()?, size, align)
764     }
765
766     pub fn write_bytes(&mut self, ptr: Scalar<M::PointerTag>, src: &[u8]) -> EvalResult<'tcx> {
767         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
768         let align = Align::from_bytes(1).unwrap();
769         if src.is_empty() {
770             self.check_align(ptr, align)?;
771             return Ok(());
772         }
773         let bytes = self.get_bytes_mut(ptr.to_ptr()?, Size::from_bytes(src.len() as u64), align)?;
774         bytes.clone_from_slice(src);
775         Ok(())
776     }
777
778     pub fn write_repeat(
779         &mut self,
780         ptr: Scalar<M::PointerTag>,
781         val: u8,
782         count: Size
783     ) -> EvalResult<'tcx> {
784         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
785         let align = Align::from_bytes(1).unwrap();
786         if count.bytes() == 0 {
787             self.check_align(ptr, align)?;
788             return Ok(());
789         }
790         let bytes = self.get_bytes_mut(ptr.to_ptr()?, count, align)?;
791         for b in bytes {
792             *b = val;
793         }
794         Ok(())
795     }
796
797     /// Read a *non-ZST* scalar
798     pub fn read_scalar(
799         &self,
800         ptr: Pointer<M::PointerTag>,
801         ptr_align: Align,
802         size: Size
803     ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
804         // get_bytes_unchecked tests alignment and relocation edges
805         let bytes = self.get_bytes_with_undef_and_ptr(
806             ptr, size, ptr_align.min(self.int_align(size))
807         )?;
808         // Undef check happens *after* we established that the alignment is correct.
809         // We must not return Ok() for unaligned pointers!
810         if self.check_defined(ptr, size).is_err() {
811             // this inflates undefined bytes to the entire scalar, even if only a few
812             // bytes are undefined
813             return Ok(ScalarMaybeUndef::Undef);
814         }
815         // Now we do the actual reading
816         let bits = read_target_uint(self.tcx.data_layout.endian, bytes).unwrap();
817         // See if we got a pointer
818         if size != self.pointer_size() {
819             // *Now* better make sure that the inside also is free of relocations.
820             self.check_relocations(ptr, size)?;
821         } else {
822             let alloc = self.get(ptr.alloc_id)?;
823             match alloc.relocations.get(&ptr.offset) {
824                 Some(&(tag, alloc_id)) => {
825                     let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits as u64), tag);
826                     return Ok(ScalarMaybeUndef::Scalar(ptr.into()))
827                 }
828                 None => {},
829             }
830         }
831         // We don't. Just return the bits.
832         Ok(ScalarMaybeUndef::Scalar(Scalar::from_uint(bits, size)))
833     }
834
835     pub fn read_ptr_sized(
836         &self,
837         ptr: Pointer<M::PointerTag>,
838         ptr_align: Align
839     ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
840         self.read_scalar(ptr, ptr_align, self.pointer_size())
841     }
842
843     /// Write a *non-ZST* scalar
844     pub fn write_scalar(
845         &mut self,
846         ptr: Pointer<M::PointerTag>,
847         ptr_align: Align,
848         val: ScalarMaybeUndef<M::PointerTag>,
849         type_size: Size,
850     ) -> EvalResult<'tcx> {
851         let val = match val {
852             ScalarMaybeUndef::Scalar(scalar) => scalar,
853             ScalarMaybeUndef::Undef => return self.mark_definedness(ptr, type_size, false),
854         };
855
856         let bytes = match val {
857             Scalar::Ptr(val) => {
858                 assert_eq!(type_size, self.pointer_size());
859                 val.offset.bytes() as u128
860             }
861
862             Scalar::Bits { bits, size } => {
863                 assert_eq!(size as u64, type_size.bytes());
864                 debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
865                     "Unexpected value of size {} when writing to memory", size);
866                 bits
867             },
868         };
869
870         {
871             // get_bytes_mut checks alignment
872             let endian = self.tcx.data_layout.endian;
873             let dst = self.get_bytes_mut(ptr, type_size, ptr_align)?;
874             write_target_uint(endian, dst, bytes).unwrap();
875         }
876
877         // See if we have to also write a relocation
878         match val {
879             Scalar::Ptr(val) => {
880                 self.get_mut(ptr.alloc_id)?.relocations.insert(
881                     ptr.offset,
882                     (val.tag, val.alloc_id),
883                 );
884             }
885             _ => {}
886         }
887
888         Ok(())
889     }
890
891     pub fn write_ptr_sized(
892         &mut self,
893         ptr: Pointer<M::PointerTag>,
894         ptr_align: Align,
895         val: ScalarMaybeUndef<M::PointerTag>
896     ) -> EvalResult<'tcx> {
897         let ptr_size = self.pointer_size();
898         self.write_scalar(ptr.into(), ptr_align, val, ptr_size)
899     }
900
901     fn int_align(&self, size: Size) -> Align {
902         // We assume pointer-sized integers have the same alignment as pointers.
903         // We also assume signed and unsigned integers of the same size have the same alignment.
904         let ity = match size.bytes() {
905             1 => layout::I8,
906             2 => layout::I16,
907             4 => layout::I32,
908             8 => layout::I64,
909             16 => layout::I128,
910             _ => bug!("bad integer size: {}", size.bytes()),
911         };
912         ity.align(self).abi
913     }
914 }
915
916 /// Undefined bytes
917 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
918     // FIXME: Add a fast version for the common, nonoverlapping case
919     fn copy_undef_mask(
920         &mut self,
921         src: Pointer<M::PointerTag>,
922         dest: Pointer<M::PointerTag>,
923         size: Size,
924         repeat: u64,
925     ) -> EvalResult<'tcx> {
926         // The bits have to be saved locally before writing to dest in case src and dest overlap.
927         assert_eq!(size.bytes() as usize as u64, size.bytes());
928
929         let undef_mask = self.get(src.alloc_id)?.undef_mask.clone();
930         let dest_allocation = self.get_mut(dest.alloc_id)?;
931
932         for i in 0..size.bytes() {
933             let defined = undef_mask.get(src.offset + Size::from_bytes(i));
934
935             for j in 0..repeat {
936                 dest_allocation.undef_mask.set(
937                     dest.offset + Size::from_bytes(i + (size.bytes() * j)),
938                     defined
939                 );
940             }
941         }
942
943         Ok(())
944     }
945 }