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.
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.
11 //! The memory subsystem.
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!
19 use std::collections::VecDeque;
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};
28 use syntax::ast::Mutability;
31 Pointer, AllocId, Allocation, ConstValue, GlobalId,
32 EvalResult, Scalar, EvalErrorKind, AllocType, PointerArithmetic,
33 Machine, MemoryAccess, AllocMap, MayLeak, ScalarMaybeUndef,
36 #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
37 pub enum MemoryKind<T> {
38 /// Error if deallocated except during a stack pop
40 /// Error if ever deallocated
42 /// Additional memory kinds a machine wishes to distinguish from the builtin ones
46 impl<T: MayLeak> MayLeak for MemoryKind<T> {
48 fn may_leak(self) -> bool {
50 MemoryKind::Stack => false,
51 MemoryKind::Vtable => true,
52 MemoryKind::Machine(k) => k.may_leak()
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,
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)>,
76 /// Lets us implement `HasDataLayout`, which is awfully convenient.
77 pub(super) tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
80 impl<'b, 'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
81 for &'b Memory<'a, 'mir, 'tcx, M>
84 fn data_layout(&self) -> &TargetDataLayout {
88 impl<'a, 'b, 'c, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
89 for &'b &'c mut Memory<'a, 'mir, 'tcx, M>
92 fn data_layout(&self) -> &TargetDataLayout {
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>
102 fn clone(&self) -> Self {
104 alloc_map: self.alloc_map.clone(),
105 dead_alloc_map: self.dead_alloc_map.clone(),
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 {
114 alloc_map: Default::default(),
115 dead_alloc_map: FxHashMap::default(),
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()
124 pub fn allocate_static_bytes(&mut self, bytes: &[u8]) -> Pointer<M::PointerTag> {
125 Pointer::from(self.tcx.allocate_bytes(bytes)).with_default_tag()
128 pub fn allocate_with(
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));
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())
150 ptr: Pointer<M::PointerTag>,
155 kind: MemoryKind<M::MemoryKinds>,
156 ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
157 if ptr.offset.bytes() != 0 {
158 return err!(ReallocateNonBasePtr);
161 // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc"
162 let new_ptr = self.allocate(new_size, new_align, kind)?;
168 old_size.min(new_size),
169 /*nonoverlapping*/ true,
171 self.deallocate(ptr, Some((old_size, old_align)), kind)?;
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)
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);
195 if ptr.offset.bytes() != 0 {
196 return err!(DeallocateNonBasePtr);
199 let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
200 Some(alloc) => alloc,
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),
208 Some(AllocType::Static(..)) |
209 Some(AllocType::Memory(..)) => err!(DeallocatedWrongMemoryKind(
210 "static".to_string(),
211 format!("{:?}", kind),
213 None => err!(DoubleFree)
218 if alloc_kind != kind {
219 return err!(DeallocatedWrongMemoryKind(
220 format!("{:?}", alloc_kind),
221 format!("{:?}", kind),
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,
234 // Let the machine take some extra action
235 M::memory_deallocated(&mut alloc, ptr)?;
237 // Don't forget to remember size and align of this now-dead allocation
238 let old = self.dead_alloc_map.insert(
240 (Size::from_bytes(alloc.bytes.len() as u64), alloc.align)
243 bug!("Nothing can be deallocated twice");
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.
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(),
266 allocation_size: size,
269 // keep data for alignment check
270 (ptr.offset.bytes(), align)
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
277 return err!(InvalidNullPointerUsage);
279 // the "base address" is 0 and hence always aligned
280 (bits as u64, required_align)
284 if alloc_align.abi() < required_align.abi() {
285 return err!(AlignmentCheckFailed {
287 required: required_align,
290 if offset % required_align.abi() == 0 {
293 let has = offset % required_align.abi();
294 err!(AlignmentCheckFailed {
295 has: Align::from_bytes(has, has).unwrap(),
296 required: required_align,
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(),
315 allocation_size: Size::from_bytes(allocation_size),
321 /// Check if the memory range beginning at `ptr` and of size `Size` is "in-bounds".
325 ptr: Pointer<M::PointerTag>,
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)
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`.
342 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
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))
352 Some(AllocType::Function(..)) => {
353 return err!(DerefFunctionPointer)
355 Some(AllocType::Static(did)) => {
359 return err!(DanglingPointerDeref),
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);
366 let instance = Instance::mono(tcx.tcx, def_id);
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()
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)
381 bug!("Matching on non-ByRef static")
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)?;
394 Cow::Borrowed(alloc) => {
395 // We got a ref, cheaply return that as an "error" so that the
396 // map does not get mutated.
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"
405 Ok((MemoryKind::Machine(kind), alloc))
409 // Now unpack that funny error type
419 ) -> EvalResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
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);
428 let kind = M::STATIC_KIND.expect(
429 "An allocation is being mutated but the machine does not expect that to happen"
431 Ok((MemoryKind::Machine(kind), alloc.into_owned()))
433 // Unpack the error type manually because type inference doesn't
434 // work otherwise (and we cannot help it because `impl Trait`)
439 if a.mutability == Mutability::Immutable {
440 return err!(ModifiedConstantMemory);
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);
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)
463 // Must be a deallocated pointer
464 *self.dead_alloc_map.get(&id).expect(
465 "allocation missing in dead_alloc_map"
471 pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
472 if ptr.offset.bytes() != 0 {
473 return err!(InvalidFunctionPointer);
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()),
482 pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
483 self.get_mut(id)?.mutability = Mutability::Immutable;
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]);
492 fn dump_alloc_helper<Tag, Extra>(
494 allocs_seen: &mut FxHashSet<AllocId>,
495 allocs_to_print: &mut VecDeque<AllocId>,
497 alloc: &Allocation<Tag, Extra>,
502 let prefix_len = msg.len();
503 let mut relocations = vec![];
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);
511 relocations.push((i, target_id));
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();
522 "{}({} bytes, alignment {}){}",
529 if !relocations.is_empty() {
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();
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) {
553 let mut allocs_to_print = VecDeque::from(allocs);
554 let mut allocs_seen = FxHashSet::default();
556 while let Some(id) = allocs_to_print.pop_front() {
557 let msg = format!("Alloc {:<5} ", format!("{}:", id));
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),
567 self.dump_alloc_helper(
568 &mut allocs_seen, &mut allocs_to_print,
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()
581 Some(AllocType::Function(func)) => {
582 trace!("{} {}", msg, func);
584 Some(AllocType::Static(did)) => {
585 trace!("{} {:?}", msg, did);
588 trace!("{} (deallocated)", msg);
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) }
603 self.dump_allocs(leaks);
607 /// This is used by [priroda](https://github.com/oli-obk/priroda)
608 pub fn alloc_map(&self) -> &M::MemoryMap {
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,
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
622 fn get_bytes_internal(
624 ptr: Pointer<M::PointerTag>,
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)?;
633 if check_defined_and_ptr {
634 self.check_defined(ptr, size)?;
635 self.check_relocations(ptr, size)?;
637 // We still don't want relocations on the *edges*
638 self.check_relocation_edges(ptr, size)?;
641 let alloc = self.get(ptr.alloc_id)?;
642 M::memory_accessed(alloc, ptr, size, MemoryAccess::Read)?;
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])
653 ptr: Pointer<M::PointerTag>,
656 ) -> EvalResult<'tcx, &[u8]> {
657 self.get_bytes_internal(ptr, size, align, true)
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*.
663 fn get_bytes_with_undef_and_ptr(
665 ptr: Pointer<M::PointerTag>,
668 ) -> EvalResult<'tcx, &[u8]> {
669 self.get_bytes_internal(ptr, size, align, false)
672 /// Just calling this already marks everything as defined and removes relocations,
673 /// so be sure to actually put data there!
676 ptr: Pointer<M::PointerTag>,
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)?;
684 self.mark_definedness(ptr, size, true)?;
685 self.clear_relocations(ptr, size)?;
687 let alloc = self.get_mut(ptr.alloc_id)?;
688 M::memory_accessed(alloc, ptr, size, MemoryAccess::Write)?;
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])
697 /// Interning (for CTFE)
698 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
700 M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=()>,
701 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
703 /// mark an allocation as static and initialized, either mutable or not
704 pub fn intern_static(
707 mutability: Mutability,
708 ) -> EvalResult<'tcx> {
710 "mark_static_initialized {:?}, mutability: {:?}",
715 let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
717 MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
718 MemoryKind::Stack | MemoryKind::Vtable => {},
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)?;
741 /// Reading and writing
742 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
745 src: Scalar<M::PointerTag>,
747 dest: Scalar<M::PointerTag>,
750 nonoverlapping: bool,
751 ) -> EvalResult<'tcx> {
752 self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
755 pub fn copy_repeatedly(
757 src: Scalar<M::PointerTag>,
759 dest: Scalar<M::PointerTag>,
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)?;
771 let src = src.to_ptr()?;
772 let dest = dest.to_ptr()?;
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).
780 let relocations = self.relocations(src, size)?;
781 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
783 new_relocations.extend(
786 .map(|&(offset, reloc)| {
787 (offset + dest.offset - src.offset + (i * size * relocations.len() as u64),
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();
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.
806 assert_eq!(size.bytes() as usize as u64, size.bytes());
807 if src.alloc_id == dest.alloc_id {
809 if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
810 (dest.offset <= src.offset && dest.offset + size > src.offset)
812 return err!(Intrinsic(
813 "copy_nonoverlapping called on overlapping ranges".to_string(),
820 dest_bytes.offset((size.bytes() * i) as isize),
821 size.bytes() as usize);
825 ptr::copy_nonoverlapping(src_bytes,
826 dest_bytes.offset((size.bytes() * i) as isize),
827 size.bytes() as usize);
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);
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) {
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])
851 None => err!(UnterminatedCString(ptr.erase_tag())),
857 ptr: Scalar<M::PointerTag>,
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)?;
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)?;
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)?;
885 self.get_bytes(ptr.to_ptr()?, size, align)
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();
892 self.check_align(ptr, align)?;
895 let bytes = self.get_bytes_mut(ptr.to_ptr()?, Size::from_bytes(src.len() as u64), align)?;
896 bytes.clone_from_slice(src);
902 ptr: Scalar<M::PointerTag>,
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)?;
912 let bytes = self.get_bytes_mut(ptr.to_ptr()?, count, align)?;
919 /// Read a *non-ZST* scalar
922 ptr: Pointer<M::PointerTag>,
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))
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);
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)?;
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()))
953 // We don't. Just return the bits.
954 Ok(ScalarMaybeUndef::Scalar(Scalar::from_uint(bits, size)))
957 pub fn read_ptr_sized(
959 ptr: Pointer<M::PointerTag>,
961 ) -> EvalResult<'tcx, ScalarMaybeUndef<M::PointerTag>> {
962 self.read_scalar(ptr, ptr_align, self.pointer_size())
965 /// Write a *non-ZST* scalar
968 ptr: Pointer<M::PointerTag>,
970 val: ScalarMaybeUndef<M::PointerTag>,
972 ) -> EvalResult<'tcx> {
973 let val = match val {
974 ScalarMaybeUndef::Scalar(scalar) => scalar,
975 ScalarMaybeUndef::Undef => return self.mark_definedness(ptr, type_size, false),
978 let bytes = match val {
979 Scalar::Ptr(val) => {
980 assert_eq!(type_size, self.pointer_size());
981 val.offset.bytes() as u128
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);
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();
999 // See if we have to also write a relocation
1001 Scalar::Ptr(val) => {
1002 self.get_mut(ptr.alloc_id)?.relocations.insert(
1004 (val.tag, val.alloc_id),
1013 pub fn write_ptr_sized(
1015 ptr: Pointer<M::PointerTag>,
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)
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() {
1032 _ => bug!("bad integer size: {}", size.bytes()),
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.
1043 ptr: Pointer<M::PointerTag>,
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))
1053 /// Check that there ar eno relocations overlapping with the given range.
1055 fn check_relocations(&self, ptr: Pointer<M::PointerTag>, size: Size) -> EvalResult<'tcx> {
1056 if self.relocations(ptr, size)?.len() != 0 {
1057 err!(ReadPointerAsBytes)
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() {
1078 (relocations.first().unwrap().0,
1079 relocations.last().unwrap().0 + self.pointer_size())
1081 let start = ptr.offset;
1082 let end = start + size;
1084 let alloc = self.get_mut(ptr.alloc_id)?;
1086 // Mark parts of the outermost relocations as undefined if they partially fall outside the
1089 alloc.undef_mask.set_range(first, start, false);
1092 alloc.undef_mask.set_range(end, last, false);
1095 // Forget all the relocations.
1096 alloc.relocations.remove_range(first..last);
1101 /// Error if there are relocations overlapping with the edges of the
1102 /// given memory range.
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)?;
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
1116 src: Pointer<M::PointerTag>,
1117 dest: Pointer<M::PointerTag>,
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());
1124 let undef_mask = self.get(src.alloc_id)?.undef_mask.clone();
1125 let dest_allocation = self.get_mut(dest.alloc_id)?;
1127 for i in 0..size.bytes() {
1128 let defined = undef_mask.get(src.offset + Size::from_bytes(i));
1130 for j in 0..repeat {
1131 dest_allocation.undef_mask.set(
1132 dest.offset + Size::from_bytes(i + (size.bytes() * j)),
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.
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(
1149 ).or_else(|idx| err!(ReadUndefBytes(idx)))
1152 pub fn mark_definedness(
1154 ptr: Pointer<M::PointerTag>,
1157 ) -> EvalResult<'tcx> {
1158 if size.bytes() == 0 {
1161 let alloc = self.get_mut(ptr.alloc_id)?;
1162 alloc.undef_mask.set_range(