]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/memory.rs
Rollup merge of #55343 - Keruspe:remap-debuginfo-release, r=alexcrichton
[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, ConstValue, GlobalId,
32     EvalResult, Scalar, EvalErrorKind, AllocType, PointerArithmetic,
33     Machine, MemoryAccess, AllocMap, MayLeak, ScalarMaybeUndef,
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<'b, 'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
81     for &'b Memory<'a, 'mir, 'tcx, M>
82 {
83     #[inline]
84     fn data_layout(&self) -> &TargetDataLayout {
85         &self.tcx.data_layout
86     }
87 }
88 impl<'a, 'b, 'c, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
89     for &'b &'c mut Memory<'a, 'mir, 'tcx, M>
90 {
91     #[inline]
92     fn data_layout(&self) -> &TargetDataLayout {
93         &self.tcx.data_layout
94     }
95 }
96
97 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
98 // carefully copy only the reachable parts.
99 impl<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>>
100     Clone for Memory<'a, 'mir, 'tcx, M>
101 {
102     fn clone(&self) -> Self {
103         Memory {
104             alloc_map: self.alloc_map.clone(),
105             dead_alloc_map: self.dead_alloc_map.clone(),
106             tcx: self.tcx,
107         }
108     }
109 }
110
111 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
112     pub fn new(tcx: TyCtxtAt<'a, 'tcx, 'tcx>) -> Self {
113         Memory {
114             alloc_map: Default::default(),
115             dead_alloc_map: FxHashMap::default(),
116             tcx,
117         }
118     }
119
120     pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer<M::PointerTag> {
121         Pointer::from(self.tcx.alloc_map.lock().create_fn_alloc(instance)).with_default_tag()
122     }
123
124     pub fn allocate_static_bytes(&mut self, bytes: &[u8]) -> Pointer<M::PointerTag> {
125         Pointer::from(self.tcx.allocate_bytes(bytes)).with_default_tag()
126     }
127
128     pub fn allocate_with(
129         &mut self,
130         alloc: Allocation<M::PointerTag, M::AllocExtra>,
131         kind: MemoryKind<M::MemoryKinds>,
132     ) -> EvalResult<'tcx, AllocId> {
133         let id = self.tcx.alloc_map.lock().reserve();
134         self.alloc_map.insert(id, (kind, alloc));
135         Ok(id)
136     }
137
138     pub fn allocate(
139         &mut self,
140         size: Size,
141         align: Align,
142         kind: MemoryKind<M::MemoryKinds>,
143     ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
144         let ptr = Pointer::from(self.allocate_with(Allocation::undef(size, align), kind)?);
145         Ok(ptr.with_default_tag())
146     }
147
148     pub fn reallocate(
149         &mut self,
150         ptr: Pointer<M::PointerTag>,
151         old_size: Size,
152         old_align: Align,
153         new_size: Size,
154         new_align: Align,
155         kind: MemoryKind<M::MemoryKinds>,
156     ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
157         if ptr.offset.bytes() != 0 {
158             return err!(ReallocateNonBasePtr);
159         }
160
161         // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc"
162         let new_ptr = self.allocate(new_size, new_align, kind)?;
163         self.copy(
164             ptr.into(),
165             old_align,
166             new_ptr.into(),
167             new_align,
168             old_size.min(new_size),
169             /*nonoverlapping*/ true,
170         )?;
171         self.deallocate(ptr, Some((old_size, old_align)), kind)?;
172
173         Ok(new_ptr)
174     }
175
176     /// Deallocate a local, or do nothing if that local has been made into a static
177     pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx> {
178         // The allocation might be already removed by static interning.
179         // This can only really happen in the CTFE instance, not in miri.
180         if self.alloc_map.contains_key(&ptr.alloc_id) {
181             self.deallocate(ptr, None, MemoryKind::Stack)
182         } else {
183             Ok(())
184         }
185     }
186
187     pub fn deallocate(
188         &mut self,
189         ptr: Pointer<M::PointerTag>,
190         size_and_align: Option<(Size, Align)>,
191         kind: MemoryKind<M::MemoryKinds>,
192     ) -> EvalResult<'tcx> {
193         trace!("deallocating: {}", ptr.alloc_id);
194
195         if ptr.offset.bytes() != 0 {
196             return err!(DeallocateNonBasePtr);
197         }
198
199         let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
200             Some(alloc) => alloc,
201             None => {
202                 // Deallocating static memory -- always an error
203                 return match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
204                     Some(AllocType::Function(..)) => err!(DeallocatedWrongMemoryKind(
205                         "function".to_string(),
206                         format!("{:?}", kind),
207                     )),
208                     Some(AllocType::Static(..)) |
209                     Some(AllocType::Memory(..)) => err!(DeallocatedWrongMemoryKind(
210                         "static".to_string(),
211                         format!("{:?}", kind),
212                     )),
213                     None => err!(DoubleFree)
214                 }
215             }
216         };
217
218         if alloc_kind != kind {
219             return err!(DeallocatedWrongMemoryKind(
220                 format!("{:?}", alloc_kind),
221                 format!("{:?}", kind),
222             ));
223         }
224         if let Some((size, align)) = size_and_align {
225             if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align {
226                 let bytes = Size::from_bytes(alloc.bytes.len() as u64);
227                 return err!(IncorrectAllocationInformation(size,
228                                                            bytes,
229                                                            align,
230                                                            alloc.align));
231             }
232         }
233
234         // Let the machine take some extra action
235         M::memory_deallocated(&mut alloc, ptr)?;
236
237         // Don't forget to remember size and align of this now-dead allocation
238         let old = self.dead_alloc_map.insert(
239             ptr.alloc_id,
240             (Size::from_bytes(alloc.bytes.len() as u64), alloc.align)
241         );
242         if old.is_some() {
243             bug!("Nothing can be deallocated twice");
244         }
245
246         Ok(())
247     }
248
249     /// Check that the pointer is aligned AND non-NULL. This supports ZSTs in two ways:
250     /// You can pass a scalar, and a `Pointer` does not have to actually still be allocated.
251     pub fn check_align(
252         &self,
253         ptr: Scalar<M::PointerTag>,
254         required_align: Align
255     ) -> EvalResult<'tcx> {
256         // Check non-NULL/Undef, extract offset
257         let (offset, alloc_align) = match ptr {
258             Scalar::Ptr(ptr) => {
259                 let (size, align) = self.get_size_and_align(ptr.alloc_id);
260                 // check this is not NULL -- which we can ensure only if this is in-bounds
261                 // of some (potentially dead) allocation.
262                 if ptr.offset > size {
263                     return err!(PointerOutOfBounds {
264                         ptr: ptr.erase_tag(),
265                         access: true,
266                         allocation_size: size,
267                     });
268                 };
269                 // keep data for alignment check
270                 (ptr.offset.bytes(), align)
271             }
272             Scalar::Bits { bits, size } => {
273                 assert_eq!(size as u64, self.pointer_size().bytes());
274                 assert!(bits < (1u128 << self.pointer_size().bits()));
275                 // check this is not NULL
276                 if bits == 0 {
277                     return err!(InvalidNullPointerUsage);
278                 }
279                 // the "base address" is 0 and hence always aligned
280                 (bits as u64, required_align)
281             }
282         };
283         // Check alignment
284         if alloc_align.abi() < required_align.abi() {
285             return err!(AlignmentCheckFailed {
286                 has: alloc_align,
287                 required: required_align,
288             });
289         }
290         if offset % required_align.abi() == 0 {
291             Ok(())
292         } else {
293             let has = offset % required_align.abi();
294             err!(AlignmentCheckFailed {
295                 has: Align::from_bytes(has, has).unwrap(),
296                 required: required_align,
297             })
298         }
299     }
300
301     /// Check if the pointer is "in-bounds". Notice that a pointer pointing at the end
302     /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
303     /// in-bounds!  This follows C's/LLVM's rules.  The `access` boolean is just used
304     /// for the error message.
305     /// If you want to check bounds before doing a memory access, be sure to
306     /// check the pointer one past the end of your access, then everything will
307     /// work out exactly.
308     pub fn check_bounds_ptr(&self, ptr: Pointer<M::PointerTag>, access: bool) -> EvalResult<'tcx> {
309         let alloc = self.get(ptr.alloc_id)?;
310         let allocation_size = alloc.bytes.len() as u64;
311         if ptr.offset.bytes() > allocation_size {
312             return err!(PointerOutOfBounds {
313                 ptr: ptr.erase_tag(),
314                 access,
315                 allocation_size: Size::from_bytes(allocation_size),
316             });
317         }
318         Ok(())
319     }
320
321     /// Check if the memory range beginning at `ptr` and of size `Size` is "in-bounds".
322     #[inline(always)]
323     pub fn check_bounds(
324         &self,
325         ptr: Pointer<M::PointerTag>,
326         size: Size,
327         access: bool
328     ) -> EvalResult<'tcx> {
329         // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
330         self.check_bounds_ptr(ptr.offset(size, &*self)?, access)
331     }
332 }
333
334 /// Allocation accessors
335 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
336     /// Helper function to obtain the global (tcx) allocation for a static.
337     /// This attempts to return a reference to an existing allocation if
338     /// one can be found in `tcx`. That, however, is only possible if `tcx` and
339     /// this machine use the same pointer tag, so it is indirected through
340     /// `M::static_with_default_tag`.
341     fn get_static_alloc(
342         tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
343         id: AllocId,
344     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
345         let alloc = tcx.alloc_map.lock().get(id);
346         let def_id = match alloc {
347             Some(AllocType::Memory(mem)) => {
348                 // We got tcx memory. Let the machine figure out whether and how to
349                 // turn that into memory with the right pointer tag.
350                 return Ok(M::static_with_default_tag(mem))
351             }
352             Some(AllocType::Function(..)) => {
353                 return err!(DerefFunctionPointer)
354             }
355             Some(AllocType::Static(did)) => {
356                 did
357             }
358             None =>
359                 return err!(DanglingPointerDeref),
360         };
361         // We got a "lazy" static that has not been computed yet, do some work
362         trace!("static_alloc: Need to compute {:?}", def_id);
363         if tcx.is_foreign_item(def_id) {
364             return M::find_foreign_static(tcx, def_id);
365         }
366         let instance = Instance::mono(tcx.tcx, def_id);
367         let gid = GlobalId {
368             instance,
369             promoted: None,
370         };
371         tcx.const_eval(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
372             // no need to report anything, the const_eval call takes care of that for statics
373             assert!(tcx.is_static(def_id).is_some());
374             EvalErrorKind::ReferencedConstant(err).into()
375         }).map(|const_val| {
376             if let ConstValue::ByRef(_, allocation, _) = const_val.val {
377                 // We got tcx memory. Let the machine figure out whether and how to
378                 // turn that into memory with the right pointer tag.
379                 M::static_with_default_tag(allocation)
380             } else {
381                 bug!("Matching on non-ByRef static")
382             }
383         })
384     }
385
386     pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
387         // The error type of the inner closure here is somewhat funny.  We have two
388         // ways of "erroring": An actual error, or because we got a reference from
389         // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
390         // So the error type is `EvalResult<'tcx, &Allocation<M::PointerTag>>`.
391         let a = self.alloc_map.get_or(id, || {
392             let alloc = Self::get_static_alloc(self.tcx, id).map_err(Err)?;
393             match alloc {
394                 Cow::Borrowed(alloc) => {
395                     // We got a ref, cheaply return that as an "error" so that the
396                     // map does not get mutated.
397                     Err(Ok(alloc))
398                 }
399                 Cow::Owned(alloc) => {
400                     // Need to put it into the map and return a ref to that
401                     let kind = M::STATIC_KIND.expect(
402                         "I got an owned allocation that I have to copy but the machine does \
403                             not expect that to happen"
404                     );
405                     Ok((MemoryKind::Machine(kind), alloc))
406                 }
407             }
408         });
409         // Now unpack that funny error type
410         match a {
411             Ok(a) => Ok(&a.1),
412             Err(a) => a
413         }
414     }
415
416     pub fn get_mut(
417         &mut self,
418         id: AllocId,
419     ) -> EvalResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
420         let tcx = self.tcx;
421         let a = self.alloc_map.get_mut_or(id, || {
422             // Need to make a copy, even if `get_static_alloc` is able
423             // to give us a cheap reference.
424             let alloc = Self::get_static_alloc(tcx, id)?;
425             if alloc.mutability == Mutability::Immutable {
426                 return err!(ModifiedConstantMemory);
427             }
428             let kind = M::STATIC_KIND.expect(
429                 "An allocation is being mutated but the machine does not expect that to happen"
430             );
431             Ok((MemoryKind::Machine(kind), alloc.into_owned()))
432         });
433         // Unpack the error type manually because type inference doesn't
434         // work otherwise (and we cannot help it because `impl Trait`)
435         match a {
436             Err(e) => Err(e),
437             Ok(a) => {
438                 let a = &mut a.1;
439                 if a.mutability == Mutability::Immutable {
440                     return err!(ModifiedConstantMemory);
441                 }
442                 Ok(a)
443             }
444         }
445     }
446
447     pub fn get_size_and_align(&self, id: AllocId) -> (Size, Align) {
448         if let Ok(alloc) = self.get(id) {
449             return (Size::from_bytes(alloc.bytes.len() as u64), alloc.align);
450         }
451         // Could also be a fn ptr or extern static
452         match self.tcx.alloc_map.lock().get(id) {
453             Some(AllocType::Function(..)) => (Size::ZERO, Align::from_bytes(1, 1).unwrap()),
454             Some(AllocType::Static(did)) => {
455                 // The only way `get` couldn't have worked here is if this is an extern static
456                 assert!(self.tcx.is_foreign_item(did));
457                 // Use size and align of the type
458                 let ty = self.tcx.type_of(did);
459                 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
460                 (layout.size, layout.align)
461             }
462             _ => {
463                 // Must be a deallocated pointer
464                 *self.dead_alloc_map.get(&id).expect(
465                     "allocation missing in dead_alloc_map"
466                 )
467             }
468         }
469     }
470
471     pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
472         if ptr.offset.bytes() != 0 {
473             return err!(InvalidFunctionPointer);
474         }
475         trace!("reading fn ptr: {}", ptr.alloc_id);
476         match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
477             Some(AllocType::Function(instance)) => Ok(instance),
478             _ => Err(EvalErrorKind::ExecuteMemory.into()),
479         }
480     }
481
482     pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
483         self.get_mut(id)?.mutability = Mutability::Immutable;
484         Ok(())
485     }
486
487     /// For debugging, print an allocation and all allocations it points to, recursively.
488     pub fn dump_alloc(&self, id: AllocId) {
489         self.dump_allocs(vec![id]);
490     }
491
492     fn dump_alloc_helper<Tag, Extra>(
493         &self,
494         allocs_seen: &mut FxHashSet<AllocId>,
495         allocs_to_print: &mut VecDeque<AllocId>,
496         mut msg: String,
497         alloc: &Allocation<Tag, Extra>,
498         extra: String,
499     ) {
500         use std::fmt::Write;
501
502         let prefix_len = msg.len();
503         let mut relocations = vec![];
504
505         for i in 0..(alloc.bytes.len() as u64) {
506             let i = Size::from_bytes(i);
507             if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
508                 if allocs_seen.insert(target_id) {
509                     allocs_to_print.push_back(target_id);
510                 }
511                 relocations.push((i, target_id));
512             }
513             if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
514                 // this `as usize` is fine, since `i` came from a `usize`
515                 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
516             } else {
517                 msg.push_str("__ ");
518             }
519         }
520
521         trace!(
522             "{}({} bytes, alignment {}){}",
523             msg,
524             alloc.bytes.len(),
525             alloc.align.abi(),
526             extra
527         );
528
529         if !relocations.is_empty() {
530             msg.clear();
531             write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
532             let mut pos = Size::ZERO;
533             let relocation_width = (self.pointer_size().bytes() - 1) * 3;
534             for (i, target_id) in relocations {
535                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
536                 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
537                 let target = format!("({})", target_id);
538                 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
539                 write!(msg, "â””{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
540                 pos = i + self.pointer_size();
541             }
542             trace!("{}", msg);
543         }
544     }
545
546     /// For debugging, print a list of allocations and all allocations they point to, recursively.
547     pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
548         if !log_enabled!(::log::Level::Trace) {
549             return;
550         }
551         allocs.sort();
552         allocs.dedup();
553         let mut allocs_to_print = VecDeque::from(allocs);
554         let mut allocs_seen = FxHashSet::default();
555
556         while let Some(id) = allocs_to_print.pop_front() {
557             let msg = format!("Alloc {:<5} ", format!("{}:", id));
558
559             // normal alloc?
560             match self.alloc_map.get_or(id, || Err(())) {
561                 Ok((kind, alloc)) => {
562                     let extra = match kind {
563                         MemoryKind::Stack => " (stack)".to_owned(),
564                         MemoryKind::Vtable => " (vtable)".to_owned(),
565                         MemoryKind::Machine(m) => format!(" ({:?})", m),
566                     };
567                     self.dump_alloc_helper(
568                         &mut allocs_seen, &mut allocs_to_print,
569                         msg, alloc, extra
570                     );
571                 },
572                 Err(()) => {
573                     // static alloc?
574                     match self.tcx.alloc_map.lock().get(id) {
575                         Some(AllocType::Memory(alloc)) => {
576                             self.dump_alloc_helper(
577                                 &mut allocs_seen, &mut allocs_to_print,
578                                 msg, alloc, " (immutable)".to_owned()
579                             );
580                         }
581                         Some(AllocType::Function(func)) => {
582                             trace!("{} {}", msg, func);
583                         }
584                         Some(AllocType::Static(did)) => {
585                             trace!("{} {:?}", msg, did);
586                         }
587                         None => {
588                             trace!("{} (deallocated)", msg);
589                         }
590                     }
591                 },
592             };
593
594         }
595     }
596
597     pub fn leak_report(&self) -> usize {
598         trace!("### LEAK REPORT ###");
599         let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
600             if kind.may_leak() { None } else { Some(id) }
601         });
602         let n = leaks.len();
603         self.dump_allocs(leaks);
604         n
605     }
606
607     /// This is used by [priroda](https://github.com/oli-obk/priroda)
608     pub fn alloc_map(&self) -> &M::MemoryMap {
609         &self.alloc_map
610     }
611 }
612
613 /// Byte accessors
614 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
615     /// The last argument controls whether we error out when there are undefined
616     /// or pointer bytes.  You should never call this, call `get_bytes` or
617     /// `get_bytes_with_undef_and_ptr` instead,
618     ///
619     /// This function also guarantees that the resulting pointer will remain stable
620     /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies
621     /// on that.
622     fn get_bytes_internal(
623         &self,
624         ptr: Pointer<M::PointerTag>,
625         size: Size,
626         align: Align,
627         check_defined_and_ptr: bool,
628     ) -> EvalResult<'tcx, &[u8]> {
629         assert_ne!(size.bytes(), 0, "0-sized accesses should never even get a `Pointer`");
630         self.check_align(ptr.into(), align)?;
631         self.check_bounds(ptr, size, true)?;
632
633         if check_defined_and_ptr {
634             self.check_defined(ptr, size)?;
635             self.check_relocations(ptr, size)?;
636         } else {
637             // We still don't want relocations on the *edges*
638             self.check_relocation_edges(ptr, size)?;
639         }
640
641         let alloc = self.get(ptr.alloc_id)?;
642         M::memory_accessed(alloc, ptr, size, MemoryAccess::Read)?;
643
644         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
645         assert_eq!(size.bytes() as usize as u64, size.bytes());
646         let offset = ptr.offset.bytes() as usize;
647         Ok(&alloc.bytes[offset..offset + size.bytes() as usize])
648     }
649
650     #[inline]
651     fn get_bytes(
652         &self,
653         ptr: Pointer<M::PointerTag>,
654         size: Size,
655         align: Align
656     ) -> EvalResult<'tcx, &[u8]> {
657         self.get_bytes_internal(ptr, size, align, true)
658     }
659
660     /// It is the caller's responsibility to handle undefined and pointer bytes.
661     /// However, this still checks that there are no relocations on the *edges*.
662     #[inline]
663     fn get_bytes_with_undef_and_ptr(
664         &self,
665         ptr: Pointer<M::PointerTag>,
666         size: Size,
667         align: Align
668     ) -> EvalResult<'tcx, &[u8]> {
669         self.get_bytes_internal(ptr, size, align, false)
670     }
671
672     /// Just calling this already marks everything as defined and removes relocations,
673     /// so be sure to actually put data there!
674     fn get_bytes_mut(
675         &mut self,
676         ptr: Pointer<M::PointerTag>,
677         size: Size,
678         align: Align,
679     ) -> EvalResult<'tcx, &mut [u8]> {
680         assert_ne!(size.bytes(), 0, "0-sized accesses should never even get a `Pointer`");
681         self.check_align(ptr.into(), align)?;
682         self.check_bounds(ptr, size, true)?;
683
684         self.mark_definedness(ptr, size, true)?;
685         self.clear_relocations(ptr, size)?;
686
687         let alloc = self.get_mut(ptr.alloc_id)?;
688         M::memory_accessed(alloc, ptr, size, MemoryAccess::Write)?;
689
690         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
691         assert_eq!(size.bytes() as usize as u64, size.bytes());
692         let offset = ptr.offset.bytes() as usize;
693         Ok(&mut alloc.bytes[offset..offset + size.bytes() as usize])
694     }
695 }
696
697 /// Interning (for CTFE)
698 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
699 where
700     M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=()>,
701     M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
702 {
703     /// mark an allocation as static and initialized, either mutable or not
704     pub fn intern_static(
705         &mut self,
706         alloc_id: AllocId,
707         mutability: Mutability,
708     ) -> EvalResult<'tcx> {
709         trace!(
710             "mark_static_initialized {:?}, mutability: {:?}",
711             alloc_id,
712             mutability
713         );
714         // remove allocation
715         let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
716         match kind {
717             MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
718             MemoryKind::Stack | MemoryKind::Vtable => {},
719         }
720         // ensure llvm knows not to put this into immutable memory
721         alloc.mutability = mutability;
722         let alloc = self.tcx.intern_const_alloc(alloc);
723         self.tcx.alloc_map.lock().set_id_memory(alloc_id, alloc);
724         // recurse into inner allocations
725         for &(_, alloc) in alloc.relocations.values() {
726             // FIXME: Reusing the mutability here is likely incorrect.  It is originally
727             // determined via `is_freeze`, and data is considered frozen if there is no
728             // `UnsafeCell` *immediately* in that data -- however, this search stops
729             // at references.  So whenever we follow a reference, we should likely
730             // assume immutability -- and we should make sure that the compiler
731             // does not permit code that would break this!
732             if self.alloc_map.contains_key(&alloc) {
733                 // Not yet interned, so proceed recursively
734                 self.intern_static(alloc, mutability)?;
735             }
736         }
737         Ok(())
738     }
739 }
740
741 /// Reading and writing
742 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
743     pub fn copy(
744         &mut self,
745         src: Scalar<M::PointerTag>,
746         src_align: Align,
747         dest: Scalar<M::PointerTag>,
748         dest_align: Align,
749         size: Size,
750         nonoverlapping: bool,
751     ) -> EvalResult<'tcx> {
752         self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
753     }
754
755     pub fn copy_repeatedly(
756         &mut self,
757         src: Scalar<M::PointerTag>,
758         src_align: Align,
759         dest: Scalar<M::PointerTag>,
760         dest_align: Align,
761         size: Size,
762         length: u64,
763         nonoverlapping: bool,
764     ) -> EvalResult<'tcx> {
765         if size.bytes() == 0 {
766             // Nothing to do for ZST, other than checking alignment and non-NULLness.
767             self.check_align(src, src_align)?;
768             self.check_align(dest, dest_align)?;
769             return Ok(());
770         }
771         let src = src.to_ptr()?;
772         let dest = dest.to_ptr()?;
773
774         // first copy the relocations to a temporary buffer, because
775         // `get_bytes_mut` will clear the relocations, which is correct,
776         // since we don't want to keep any relocations at the target.
777         // (`get_bytes_with_undef_and_ptr` below checks that there are no
778         // relocations overlapping the edges; those would not be handled correctly).
779         let relocations = {
780             let relocations = self.relocations(src, size)?;
781             let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
782             for i in 0..length {
783                 new_relocations.extend(
784                     relocations
785                     .iter()
786                     .map(|&(offset, reloc)| {
787                     (offset + dest.offset - src.offset + (i * size * relocations.len() as u64),
788                      reloc)
789                     })
790                 );
791             }
792
793             new_relocations
794         };
795
796         // This also checks alignment, and relocation edges on the src.
797         let src_bytes = self.get_bytes_with_undef_and_ptr(src, size, src_align)?.as_ptr();
798         let dest_bytes = self.get_bytes_mut(dest, size * length, dest_align)?.as_mut_ptr();
799
800         // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
801         // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
802         // `dest` could possibly overlap.
803         // The pointers above remain valid even if the `HashMap` table is moved around because they
804         // point into the `Vec` storing the bytes.
805         unsafe {
806             assert_eq!(size.bytes() as usize as u64, size.bytes());
807             if src.alloc_id == dest.alloc_id {
808                 if nonoverlapping {
809                     if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
810                         (dest.offset <= src.offset && dest.offset + size > src.offset)
811                     {
812                         return err!(Intrinsic(
813                             "copy_nonoverlapping called on overlapping ranges".to_string(),
814                         ));
815                     }
816                 }
817
818                 for i in 0..length {
819                     ptr::copy(src_bytes,
820                               dest_bytes.offset((size.bytes() * i) as isize),
821                               size.bytes() as usize);
822                 }
823             } else {
824                 for i in 0..length {
825                     ptr::copy_nonoverlapping(src_bytes,
826                                              dest_bytes.offset((size.bytes() * i) as isize),
827                                              size.bytes() as usize);
828                 }
829             }
830         }
831
832         // copy definedness to the destination
833         self.copy_undef_mask(src, dest, size, length)?;
834         // copy the relocations to the destination
835         self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
836
837         Ok(())
838     }
839
840     pub fn read_c_str(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, &[u8]> {
841         let alloc = self.get(ptr.alloc_id)?;
842         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
843         let offset = ptr.offset.bytes() as usize;
844         match alloc.bytes[offset..].iter().position(|&c| c == 0) {
845             Some(size) => {
846                 let p1 = Size::from_bytes((size + 1) as u64);
847                 self.check_relocations(ptr, p1)?;
848                 self.check_defined(ptr, p1)?;
849                 Ok(&alloc.bytes[offset..offset + size])
850             }
851             None => err!(UnterminatedCString(ptr.erase_tag())),
852         }
853     }
854
855     pub fn check_bytes(
856         &self,
857         ptr: Scalar<M::PointerTag>,
858         size: Size,
859         allow_ptr_and_undef: bool,
860     ) -> EvalResult<'tcx> {
861         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
862         let align = Align::from_bytes(1, 1).unwrap();
863         if size.bytes() == 0 {
864             self.check_align(ptr, align)?;
865             return Ok(());
866         }
867         let ptr = ptr.to_ptr()?;
868         // Check bounds, align and relocations on the edges
869         self.get_bytes_with_undef_and_ptr(ptr, size, align)?;
870         // Check undef and ptr
871         if !allow_ptr_and_undef {
872             self.check_defined(ptr, size)?;
873             self.check_relocations(ptr, size)?;
874         }
875         Ok(())
876     }
877
878     pub fn read_bytes(&self, ptr: Scalar<M::PointerTag>, size: Size) -> EvalResult<'tcx, &[u8]> {
879         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
880         let align = Align::from_bytes(1, 1).unwrap();
881         if size.bytes() == 0 {
882             self.check_align(ptr, align)?;
883             return Ok(&[]);
884         }
885         self.get_bytes(ptr.to_ptr()?, size, align)
886     }
887
888     pub fn write_bytes(&mut self, ptr: Scalar<M::PointerTag>, src: &[u8]) -> EvalResult<'tcx> {
889         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
890         let align = Align::from_bytes(1, 1).unwrap();
891         if src.is_empty() {
892             self.check_align(ptr, align)?;
893             return Ok(());
894         }
895         let bytes = self.get_bytes_mut(ptr.to_ptr()?, Size::from_bytes(src.len() as u64), align)?;
896         bytes.clone_from_slice(src);
897         Ok(())
898     }
899
900     pub fn write_repeat(
901         &mut self,
902         ptr: Scalar<M::PointerTag>,
903         val: u8,
904         count: Size
905     ) -> EvalResult<'tcx> {
906         // Empty accesses don't need to be valid pointers, but they should still be non-NULL
907         let align = Align::from_bytes(1, 1).unwrap();
908         if count.bytes() == 0 {
909             self.check_align(ptr, align)?;
910             return Ok(());
911         }
912         let bytes = self.get_bytes_mut(ptr.to_ptr()?, count, align)?;
913         for b in bytes {
914             *b = val;
915         }
916         Ok(())
917     }
918
919     /// Read a *non-ZST* scalar
920     pub fn read_scalar(
921         &self,
922         ptr: Pointer<M::PointerTag>,
923         ptr_align: Align,
924         size: Size
925     ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
926         // get_bytes_unchecked tests alignment and relocation edges
927         let bytes = self.get_bytes_with_undef_and_ptr(
928             ptr, size, ptr_align.min(self.int_align(size))
929         )?;
930         // Undef check happens *after* we established that the alignment is correct.
931         // We must not return Ok() for unaligned pointers!
932         if self.check_defined(ptr, size).is_err() {
933             // this inflates undefined bytes to the entire scalar, even if only a few
934             // bytes are undefined
935             return Ok(ScalarMaybeUndef::Undef);
936         }
937         // Now we do the actual reading
938         let bits = read_target_uint(self.tcx.data_layout.endian, bytes).unwrap();
939         // See if we got a pointer
940         if size != self.pointer_size() {
941             // *Now* better make sure that the inside also is free of relocations.
942             self.check_relocations(ptr, size)?;
943         } else {
944             let alloc = self.get(ptr.alloc_id)?;
945             match alloc.relocations.get(&ptr.offset) {
946                 Some(&(tag, alloc_id)) => {
947                     let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits as u64), tag);
948                     return Ok(ScalarMaybeUndef::Scalar(ptr.into()))
949                 }
950                 None => {},
951             }
952         }
953         // We don't. Just return the bits.
954         Ok(ScalarMaybeUndef::Scalar(Scalar::from_uint(bits, size)))
955     }
956
957     pub fn read_ptr_sized(
958         &self,
959         ptr: Pointer<M::PointerTag>,
960         ptr_align: Align
961     ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
962         self.read_scalar(ptr, ptr_align, self.pointer_size())
963     }
964
965     /// Write a *non-ZST* scalar
966     pub fn write_scalar(
967         &mut self,
968         ptr: Pointer<M::PointerTag>,
969         ptr_align: Align,
970         val: ScalarMaybeUndef<M::PointerTag>,
971         type_size: Size,
972     ) -> EvalResult<'tcx> {
973         let val = match val {
974             ScalarMaybeUndef::Scalar(scalar) => scalar,
975             ScalarMaybeUndef::Undef => return self.mark_definedness(ptr, type_size, false),
976         };
977
978         let bytes = match val {
979             Scalar::Ptr(val) => {
980                 assert_eq!(type_size, self.pointer_size());
981                 val.offset.bytes() as u128
982             }
983
984             Scalar::Bits { bits, size } => {
985                 assert_eq!(size as u64, type_size.bytes());
986                 debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
987                     "Unexpected value of size {} when writing to memory", size);
988                 bits
989             },
990         };
991
992         {
993             // get_bytes_mut checks alignment
994             let endian = self.tcx.data_layout.endian;
995             let dst = self.get_bytes_mut(ptr, type_size, ptr_align)?;
996             write_target_uint(endian, dst, bytes).unwrap();
997         }
998
999         // See if we have to also write a relocation
1000         match val {
1001             Scalar::Ptr(val) => {
1002                 self.get_mut(ptr.alloc_id)?.relocations.insert(
1003                     ptr.offset,
1004                     (val.tag, val.alloc_id),
1005                 );
1006             }
1007             _ => {}
1008         }
1009
1010         Ok(())
1011     }
1012
1013     pub fn write_ptr_sized(
1014         &mut self,
1015         ptr: Pointer<M::PointerTag>,
1016         ptr_align: Align,
1017         val: ScalarMaybeUndef<M::PointerTag>
1018     ) -> EvalResult<'tcx> {
1019         let ptr_size = self.pointer_size();
1020         self.write_scalar(ptr.into(), ptr_align, val, ptr_size)
1021     }
1022
1023     fn int_align(&self, size: Size) -> Align {
1024         // We assume pointer-sized integers have the same alignment as pointers.
1025         // We also assume signed and unsigned integers of the same size have the same alignment.
1026         let ity = match size.bytes() {
1027             1 => layout::I8,
1028             2 => layout::I16,
1029             4 => layout::I32,
1030             8 => layout::I64,
1031             16 => layout::I128,
1032             _ => bug!("bad integer size: {}", size.bytes()),
1033         };
1034         ity.align(self)
1035     }
1036 }
1037
1038 /// Relocations
1039 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
1040     /// Return all relocations overlapping with the given ptr-offset pair.
1041     fn relocations(
1042         &self,
1043         ptr: Pointer<M::PointerTag>,
1044         size: Size,
1045     ) -> EvalResult<'tcx, &[(Size, (M::PointerTag, AllocId))]> {
1046         // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
1047         // the beginning of this range.
1048         let start = ptr.offset.bytes().saturating_sub(self.pointer_size().bytes() - 1);
1049         let end = ptr.offset + size; // this does overflow checking
1050         Ok(self.get(ptr.alloc_id)?.relocations.range(Size::from_bytes(start)..end))
1051     }
1052
1053     /// Check that there ar eno relocations overlapping with the given range.
1054     #[inline(always)]
1055     fn check_relocations(&self, ptr: Pointer<M::PointerTag>, size: Size) -> EvalResult<'tcx> {
1056         if self.relocations(ptr, size)?.len() != 0 {
1057             err!(ReadPointerAsBytes)
1058         } else {
1059             Ok(())
1060         }
1061     }
1062
1063     /// Remove all relocations inside the given range.
1064     /// If there are relocations overlapping with the edges, they
1065     /// are removed as well *and* the bytes they cover are marked as
1066     /// uninitialized.  This is a somewhat odd "spooky action at a distance",
1067     /// but it allows strictly more code to run than if we would just error
1068     /// immediately in that case.
1069     fn clear_relocations(&mut self, ptr: Pointer<M::PointerTag>, size: Size) -> EvalResult<'tcx> {
1070         // Find the start and end of the given range and its outermost relocations.
1071         let (first, last) = {
1072             // Find all relocations overlapping the given range.
1073             let relocations = self.relocations(ptr, size)?;
1074             if relocations.is_empty() {
1075                 return Ok(());
1076             }
1077
1078             (relocations.first().unwrap().0,
1079              relocations.last().unwrap().0 + self.pointer_size())
1080         };
1081         let start = ptr.offset;
1082         let end = start + size;
1083
1084         let alloc = self.get_mut(ptr.alloc_id)?;
1085
1086         // Mark parts of the outermost relocations as undefined if they partially fall outside the
1087         // given range.
1088         if first < start {
1089             alloc.undef_mask.set_range(first, start, false);
1090         }
1091         if last > end {
1092             alloc.undef_mask.set_range(end, last, false);
1093         }
1094
1095         // Forget all the relocations.
1096         alloc.relocations.remove_range(first..last);
1097
1098         Ok(())
1099     }
1100
1101     /// Error if there are relocations overlapping with the edges of the
1102     /// given memory range.
1103     #[inline]
1104     fn check_relocation_edges(&self, ptr: Pointer<M::PointerTag>, size: Size) -> EvalResult<'tcx> {
1105         self.check_relocations(ptr, Size::ZERO)?;
1106         self.check_relocations(ptr.offset(size, self)?, Size::ZERO)?;
1107         Ok(())
1108     }
1109 }
1110
1111 /// Undefined bytes
1112 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
1113     // FIXME: Add a fast version for the common, nonoverlapping case
1114     fn copy_undef_mask(
1115         &mut self,
1116         src: Pointer<M::PointerTag>,
1117         dest: Pointer<M::PointerTag>,
1118         size: Size,
1119         repeat: u64,
1120     ) -> EvalResult<'tcx> {
1121         // The bits have to be saved locally before writing to dest in case src and dest overlap.
1122         assert_eq!(size.bytes() as usize as u64, size.bytes());
1123
1124         let undef_mask = self.get(src.alloc_id)?.undef_mask.clone();
1125         let dest_allocation = self.get_mut(dest.alloc_id)?;
1126
1127         for i in 0..size.bytes() {
1128             let defined = undef_mask.get(src.offset + Size::from_bytes(i));
1129
1130             for j in 0..repeat {
1131                 dest_allocation.undef_mask.set(
1132                     dest.offset + Size::from_bytes(i + (size.bytes() * j)),
1133                     defined
1134                 );
1135             }
1136         }
1137
1138         Ok(())
1139     }
1140
1141     /// Checks that a range of bytes is defined. If not, returns the `ReadUndefBytes`
1142     /// error which will report the first byte which is undefined.
1143     #[inline]
1144     fn check_defined(&self, ptr: Pointer<M::PointerTag>, size: Size) -> EvalResult<'tcx> {
1145         let alloc = self.get(ptr.alloc_id)?;
1146         alloc.undef_mask.is_range_defined(
1147             ptr.offset,
1148             ptr.offset + size,
1149         ).or_else(|idx| err!(ReadUndefBytes(idx)))
1150     }
1151
1152     pub fn mark_definedness(
1153         &mut self,
1154         ptr: Pointer<M::PointerTag>,
1155         size: Size,
1156         new_state: bool,
1157     ) -> EvalResult<'tcx> {
1158         if size.bytes() == 0 {
1159             return Ok(());
1160         }
1161         let alloc = self.get_mut(ptr.alloc_id)?;
1162         alloc.undef_mask.set_range(
1163             ptr.offset,
1164             ptr.offset + size,
1165             new_state,
1166         );
1167         Ok(())
1168     }
1169 }