1 //! The memory subsystem.
3 //! Generally, we use `Pointer` to denote memory addresses. However, some operations
4 //! have a "size"-like parameter, and they take `Scalar` for the address because
5 //! if the size is 0, then the pointer can also be a (properly aligned, non-NULL)
6 //! integer. It is crucial that these operations call `check_align` *before*
7 //! short-circuiting the empty case!
9 use std::collections::VecDeque;
13 use rustc::ty::{self, Instance, ParamEnv, query::TyCtxtAt};
14 use rustc::ty::layout::{Align, TargetDataLayout, Size, HasDataLayout};
15 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
17 use syntax::ast::Mutability;
20 Pointer, AllocId, Allocation, GlobalId, AllocationExtra,
21 InterpResult, Scalar, InterpError, GlobalAlloc, PointerArithmetic,
22 Machine, AllocMap, MayLeak, ErrorHandled, CheckInAllocMsg,
25 #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
26 pub enum MemoryKind<T> {
27 /// Error if deallocated except during a stack pop
29 /// Error if ever deallocated
31 /// Additional memory kinds a machine wishes to distinguish from the builtin ones
35 impl<T: MayLeak> MayLeak for MemoryKind<T> {
37 fn may_leak(self) -> bool {
39 MemoryKind::Stack => false,
40 MemoryKind::Vtable => true,
41 MemoryKind::Machine(k) => k.may_leak()
46 /// Used by `get_size_and_align` to indicate whether the allocation needs to be live.
47 #[derive(Debug, Copy, Clone)]
49 /// Allocation must be live and not a function pointer.
51 /// Allocations needs to be live, but may be a function pointer.
53 /// Allocation may be dead.
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<'mir, 'tcx, M: Machine<'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 // FIXME: this should not be public, but interning currently needs access to it
70 pub(super) alloc_map: M::MemoryMap,
72 /// To be able to compare pointers with NULL, and to check alignment for accesses
73 /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
74 /// that do not exist any more.
75 pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
77 /// Extra data added by the machine.
78 pub extra: M::MemoryExtra,
80 /// Lets us implement `HasDataLayout`, which is awfully convenient.
81 pub(super) tcx: TyCtxtAt<'tcx>,
84 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> {
86 fn data_layout(&self) -> &TargetDataLayout {
91 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
92 // carefully copy only the reachable parts.
93 impl<'mir, 'tcx, M> Clone for Memory<'mir, 'tcx, M>
95 M: Machine<'mir, 'tcx, PointerTag = (), AllocExtra = (), MemoryExtra = ()>,
96 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
98 fn clone(&self) -> Self {
100 alloc_map: self.alloc_map.clone(),
101 dead_alloc_map: self.dead_alloc_map.clone(),
108 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
109 pub fn new(tcx: TyCtxtAt<'tcx>) -> Self {
111 alloc_map: M::MemoryMap::default(),
112 dead_alloc_map: FxHashMap::default(),
113 extra: M::MemoryExtra::default(),
119 pub fn tag_static_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
120 ptr.with_tag(M::tag_static_base_pointer(ptr.alloc_id, &self))
123 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer<M::PointerTag> {
124 let id = self.tcx.alloc_map.lock().create_fn_alloc(instance);
125 self.tag_static_base_pointer(Pointer::from(id))
132 kind: MemoryKind<M::MemoryKinds>,
133 ) -> Pointer<M::PointerTag> {
134 let alloc = Allocation::undef(size, align);
135 self.allocate_with(alloc, kind)
138 pub fn allocate_static_bytes(
141 kind: MemoryKind<M::MemoryKinds>,
142 ) -> Pointer<M::PointerTag> {
143 let alloc = Allocation::from_byte_aligned_bytes(bytes);
144 self.allocate_with(alloc, kind)
147 pub fn allocate_with(
150 kind: MemoryKind<M::MemoryKinds>,
151 ) -> Pointer<M::PointerTag> {
152 let id = self.tcx.alloc_map.lock().reserve();
153 let (alloc, tag) = M::tag_allocation(id, Cow::Owned(alloc), Some(kind), &self);
154 self.alloc_map.insert(id, (kind, alloc.into_owned()));
155 Pointer::from(id).with_tag(tag)
160 ptr: Pointer<M::PointerTag>,
161 old_size_and_align: Option<(Size, Align)>,
164 kind: MemoryKind<M::MemoryKinds>,
165 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
166 if ptr.offset.bytes() != 0 {
167 return err!(ReallocateNonBasePtr);
170 // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
171 // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
172 let new_ptr = self.allocate(new_size, new_align, kind);
173 let old_size = match old_size_and_align {
174 Some((size, _align)) => size,
175 None => Size::from_bytes(self.get(ptr.alloc_id)?.bytes.len() as u64),
179 Align::from_bytes(1).unwrap(), // old_align anyway gets checked below by `deallocate`
182 old_size.min(new_size),
183 /*nonoverlapping*/ true,
185 self.deallocate(ptr, old_size_and_align, kind)?;
190 /// Deallocate a local, or do nothing if that local has been made into a static
191 pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx> {
192 // The allocation might be already removed by static interning.
193 // This can only really happen in the CTFE instance, not in miri.
194 if self.alloc_map.contains_key(&ptr.alloc_id) {
195 self.deallocate(ptr, None, MemoryKind::Stack)
203 ptr: Pointer<M::PointerTag>,
204 old_size_and_align: Option<(Size, Align)>,
205 kind: MemoryKind<M::MemoryKinds>,
206 ) -> InterpResult<'tcx> {
207 trace!("deallocating: {}", ptr.alloc_id);
209 if ptr.offset.bytes() != 0 {
210 return err!(DeallocateNonBasePtr);
213 let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
214 Some(alloc) => alloc,
216 // Deallocating static memory -- always an error
217 return match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
218 Some(GlobalAlloc::Function(..)) => err!(DeallocatedWrongMemoryKind(
219 "function".to_string(),
220 format!("{:?}", kind),
222 Some(GlobalAlloc::Static(..)) |
223 Some(GlobalAlloc::Memory(..)) => err!(DeallocatedWrongMemoryKind(
224 "static".to_string(),
225 format!("{:?}", kind),
227 None => err!(DoubleFree)
232 if alloc_kind != kind {
233 return err!(DeallocatedWrongMemoryKind(
234 format!("{:?}", alloc_kind),
235 format!("{:?}", kind),
238 if let Some((size, align)) = old_size_and_align {
239 if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align {
240 let bytes = Size::from_bytes(alloc.bytes.len() as u64);
241 return err!(IncorrectAllocationInformation(size,
248 // Let the machine take some extra action
249 let size = Size::from_bytes(alloc.bytes.len() as u64);
250 AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?;
252 // Don't forget to remember size and align of this now-dead allocation
253 let old = self.dead_alloc_map.insert(
255 (Size::from_bytes(alloc.bytes.len() as u64), alloc.align)
258 bug!("Nothing can be deallocated twice");
264 /// Check if the given scalar is allowed to do a memory access of given `size`
265 /// and `align`. On success, returns `None` for zero-sized accesses (where
266 /// nothing else is left to do) and a `Pointer` to use for the actual access otherwise.
267 /// Crucially, if the input is a `Pointer`, we will test it for liveness
268 /// *even of* the size is 0.
270 /// Everyone accessing memory based on a `Scalar` should use this method to get the
271 /// `Pointer` they need. And even if you already have a `Pointer`, call this method
272 /// to make sure it is sufficiently aligned and not dangling. Not doing that may
274 pub fn check_ptr_access(
276 sptr: Scalar<M::PointerTag>,
279 ) -> InterpResult<'tcx, Option<Pointer<M::PointerTag>>> {
280 fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> {
281 if offset % align.bytes() == 0 {
284 // The biggest power of two through which `offset` is divisible.
285 let offset_pow2 = 1 << offset.trailing_zeros();
286 err!(AlignmentCheckFailed {
287 has: Align::from_bytes(offset_pow2).unwrap(),
293 // Normalize to a `Pointer` if we definitely need one.
294 let normalized = if size.bytes() == 0 {
295 // Can be an integer, just take what we got. We do NOT `force_bits` here;
296 // if this is already a `Pointer` we want to do the bounds checks!
299 // A "real" access, we must get a pointer.
300 Scalar::Ptr(self.force_ptr(sptr)?)
302 Ok(match normalized.to_bits_or_ptr(self.pointer_size(), self) {
304 let bits = bits as u64; // it's ptr-sized
305 assert!(size.bytes() == 0);
306 // Must be non-NULL and aligned.
308 return err!(InvalidNullPointerUsage);
310 check_offset_align(bits, align)?;
314 let (allocation_size, alloc_align) =
315 self.get_size_and_align(ptr.alloc_id, AllocCheck::Dereferencable)?;
316 // Test bounds. This also ensures non-NULL.
317 // It is sufficient to check this for the end pointer. The addition
318 // checks for overflow.
319 let end_ptr = ptr.offset(size, self)?;
320 end_ptr.check_in_alloc(allocation_size, CheckInAllocMsg::MemoryAccessTest)?;
321 // Test align. Check this last; if both bounds and alignment are violated
322 // we want the error to be about the bounds.
323 if alloc_align.bytes() < align.bytes() {
324 // The allocation itself is not aligned enough.
325 // FIXME: Alignment check is too strict, depending on the base address that
326 // got picked we might be aligned even if this check fails.
327 // We instead have to fall back to converting to an integer and checking
328 // the "real" alignment.
329 return err!(AlignmentCheckFailed {
334 check_offset_align(ptr.offset.bytes(), align)?;
336 // We can still be zero-sized in this branch, in which case we have to
338 if size.bytes() == 0 { None } else { Some(ptr) }
343 /// Test if the pointer might be NULL.
344 pub fn ptr_may_be_null(
346 ptr: Pointer<M::PointerTag>,
348 let (size, _align) = self.get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead)
349 .expect("alloc info with MaybeDead cannot fail");
350 ptr.check_in_alloc(size, CheckInAllocMsg::NullPointerTest).is_err()
354 /// Allocation accessors
355 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
356 /// Helper function to obtain the global (tcx) allocation for a static.
357 /// This attempts to return a reference to an existing allocation if
358 /// one can be found in `tcx`. That, however, is only possible if `tcx` and
359 /// this machine use the same pointer tag, so it is indirected through
360 /// `M::tag_allocation`.
362 /// Notice that every static has two `AllocId` that will resolve to the same
363 /// thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
364 /// and the other one is maps to `GlobalAlloc::Memory`, this is returned by
365 /// `const_eval_raw` and it is the "resolved" ID.
366 /// The resolved ID is never used by the interpreted progrma, it is hidden.
367 /// The `GlobalAlloc::Memory` branch here is still reachable though; when a static
368 /// contains a reference to memory that was created during its evaluation (i.e., not to
369 /// another static), those inner references only exist in "resolved" form.
373 memory: &Memory<'mir, 'tcx, M>,
374 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
375 let alloc = tcx.alloc_map.lock().get(id);
376 let alloc = match alloc {
377 Some(GlobalAlloc::Memory(mem)) =>
379 Some(GlobalAlloc::Function(..)) =>
380 return err!(DerefFunctionPointer),
382 return err!(DanglingPointerDeref),
383 Some(GlobalAlloc::Static(def_id)) => {
384 // We got a "lazy" static that has not been computed yet.
385 if tcx.is_foreign_item(def_id) {
386 trace!("static_alloc: foreign item {:?}", def_id);
387 M::find_foreign_static(def_id, tcx)?
389 trace!("static_alloc: Need to compute {:?}", def_id);
390 let instance = Instance::mono(tcx.tcx, def_id);
395 // use the raw query here to break validation cycles. Later uses of the static
396 // will call the full query anyway
397 let raw_const = tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid))
399 // no need to report anything, the const_eval call takes care of that
401 assert!(tcx.is_static(def_id));
403 ErrorHandled::Reported => InterpError::ReferencedConstant,
404 ErrorHandled::TooGeneric => InterpError::TooGeneric,
407 // Make sure we use the ID of the resolved memory, not the lazy one!
408 let id = raw_const.alloc_id;
409 let allocation = tcx.alloc_map.lock().unwrap_memory(id);
410 Cow::Borrowed(allocation)
414 // We got tcx memory. Let the machine figure out whether and how to
415 // turn that into memory with the right pointer tag.
416 Ok(M::tag_allocation(
417 id, // always use the ID we got as input, not the "hidden" one.
419 M::STATIC_KIND.map(MemoryKind::Machine),
427 ) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
428 // The error type of the inner closure here is somewhat funny. We have two
429 // ways of "erroring": An actual error, or because we got a reference from
430 // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
431 // So the error type is `InterpResult<'tcx, &Allocation<M::PointerTag>>`.
432 let a = self.alloc_map.get_or(id, || {
433 let alloc = Self::get_static_alloc(id, self.tcx, &self).map_err(Err)?;
435 Cow::Borrowed(alloc) => {
436 // We got a ref, cheaply return that as an "error" so that the
437 // map does not get mutated.
440 Cow::Owned(alloc) => {
441 // Need to put it into the map and return a ref to that
442 let kind = M::STATIC_KIND.expect(
443 "I got an owned allocation that I have to copy but the machine does \
444 not expect that to happen"
446 Ok((MemoryKind::Machine(kind), alloc))
450 // Now unpack that funny error type
460 ) -> InterpResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
462 let alloc = Self::get_static_alloc(id, tcx, &self);
463 let a = self.alloc_map.get_mut_or(id, || {
464 // Need to make a copy, even if `get_static_alloc` is able
465 // to give us a cheap reference.
467 if alloc.mutability == Mutability::Immutable {
468 return err!(ModifiedConstantMemory);
470 match M::STATIC_KIND {
471 Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())),
472 None => err!(ModifiedStatic),
475 // Unpack the error type manually because type inference doesn't
476 // work otherwise (and we cannot help it because `impl Trait`)
481 if a.mutability == Mutability::Immutable {
482 return err!(ModifiedConstantMemory);
489 /// Obtain the size and alignment of an allocation, even if that allocation has
490 /// been deallocated.
492 /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`.
493 pub fn get_size_and_align(
496 liveness: AllocCheck,
497 ) -> InterpResult<'static, (Size, Align)> {
498 if let Ok(alloc) = self.get(id) {
499 return Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align));
501 // can't do this in the match argument, we may get cycle errors since the lock would get
502 // dropped after the match.
503 let alloc = self.tcx.alloc_map.lock().get(id);
504 // Could also be a fn ptr or extern static
506 Some(GlobalAlloc::Function(..)) => {
507 if let AllocCheck::Dereferencable = liveness {
508 // The caller requested no function pointers.
509 err!(DerefFunctionPointer)
511 Ok((Size::ZERO, Align::from_bytes(1).unwrap()))
514 // `self.get` would also work, but can cause cycles if a static refers to itself
515 Some(GlobalAlloc::Static(did)) => {
516 // The only way `get` couldn't have worked here is if this is an extern static
517 assert!(self.tcx.is_foreign_item(did));
518 // Use size and align of the type
519 let ty = self.tcx.type_of(did);
520 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
521 Ok((layout.size, layout.align.abi))
524 if let Ok(alloc) = self.get(id) {
525 Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align))
527 else if let AllocCheck::MaybeDead = liveness {
528 // Deallocated pointers are allowed, we should be able to find
530 Ok(*self.dead_alloc_map.get(&id)
531 .expect("deallocated pointers should all be recorded in `dead_alloc_map`"))
533 err!(DanglingPointerDeref)
539 pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> InterpResult<'tcx, Instance<'tcx>> {
540 if ptr.offset.bytes() != 0 {
541 return err!(InvalidFunctionPointer);
543 trace!("reading fn ptr: {}", ptr.alloc_id);
544 match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
545 Some(GlobalAlloc::Function(instance)) => Ok(instance),
546 _ => Err(InterpError::ExecuteMemory.into()),
550 pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
551 self.get_mut(id)?.mutability = Mutability::Immutable;
555 /// For debugging, print an allocation and all allocations it points to, recursively.
556 pub fn dump_alloc(&self, id: AllocId) {
557 self.dump_allocs(vec![id]);
560 fn dump_alloc_helper<Tag, Extra>(
562 allocs_seen: &mut FxHashSet<AllocId>,
563 allocs_to_print: &mut VecDeque<AllocId>,
565 alloc: &Allocation<Tag, Extra>,
570 let prefix_len = msg.len();
571 let mut relocations = vec![];
573 for i in 0..(alloc.bytes.len() as u64) {
574 let i = Size::from_bytes(i);
575 if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
576 if allocs_seen.insert(target_id) {
577 allocs_to_print.push_back(target_id);
579 relocations.push((i, target_id));
581 if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
582 // this `as usize` is fine, since `i` came from a `usize`
583 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
590 "{}({} bytes, alignment {}){}",
597 if !relocations.is_empty() {
599 write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
600 let mut pos = Size::ZERO;
601 let relocation_width = (self.pointer_size().bytes() - 1) * 3;
602 for (i, target_id) in relocations {
603 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
604 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
605 let target = format!("({})", target_id);
606 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
607 write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
608 pos = i + self.pointer_size();
614 /// For debugging, print a list of allocations and all allocations they point to, recursively.
615 pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
616 if !log_enabled!(::log::Level::Trace) {
621 let mut allocs_to_print = VecDeque::from(allocs);
622 let mut allocs_seen = FxHashSet::default();
624 while let Some(id) = allocs_to_print.pop_front() {
625 let msg = format!("Alloc {:<5} ", format!("{}:", id));
628 match self.alloc_map.get_or(id, || Err(())) {
629 Ok((kind, alloc)) => {
630 let extra = match kind {
631 MemoryKind::Stack => " (stack)".to_owned(),
632 MemoryKind::Vtable => " (vtable)".to_owned(),
633 MemoryKind::Machine(m) => format!(" ({:?})", m),
635 self.dump_alloc_helper(
636 &mut allocs_seen, &mut allocs_to_print,
642 match self.tcx.alloc_map.lock().get(id) {
643 Some(GlobalAlloc::Memory(alloc)) => {
644 self.dump_alloc_helper(
645 &mut allocs_seen, &mut allocs_to_print,
646 msg, alloc, " (immutable)".to_owned()
649 Some(GlobalAlloc::Function(func)) => {
650 trace!("{} {}", msg, func);
652 Some(GlobalAlloc::Static(did)) => {
653 trace!("{} {:?}", msg, did);
656 trace!("{} (deallocated)", msg);
665 pub fn leak_report(&self) -> usize {
666 trace!("### LEAK REPORT ###");
667 let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
668 if kind.may_leak() { None } else { Some(id) }
671 self.dump_allocs(leaks);
675 /// This is used by [priroda](https://github.com/oli-obk/priroda)
676 pub fn alloc_map(&self) -> &M::MemoryMap {
681 /// Reading and writing.
682 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
683 /// Performs appropriate bounds checks.
686 ptr: Scalar<M::PointerTag>,
688 ) -> InterpResult<'tcx, &[u8]> {
689 let ptr = match self.check_ptr_access(ptr, size, Align::from_bytes(1).unwrap())? {
691 None => return Ok(&[]), // zero-sized access
693 self.get(ptr.alloc_id)?.get_bytes(self, ptr, size)
696 /// Performs appropriate bounds checks.
699 src: Scalar<M::PointerTag>,
701 dest: Scalar<M::PointerTag>,
704 nonoverlapping: bool,
705 ) -> InterpResult<'tcx> {
706 self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
709 /// Performs appropriate bounds checks.
710 pub fn copy_repeatedly(
712 src: Scalar<M::PointerTag>,
714 dest: Scalar<M::PointerTag>,
718 nonoverlapping: bool,
719 ) -> InterpResult<'tcx> {
720 // We need to check *both* before early-aborting due to the size being 0.
721 let (src, dest) = match (self.check_ptr_access(src, size, src_align)?,
722 self.check_ptr_access(dest, size * length, dest_align)?)
724 (Some(src), Some(dest)) => (src, dest),
725 // One of the two sizes is 0.
729 // first copy the relocations to a temporary buffer, because
730 // `get_bytes_mut` will clear the relocations, which is correct,
731 // since we don't want to keep any relocations at the target.
732 // (`get_bytes_with_undef_and_ptr` below checks that there are no
733 // relocations overlapping the edges; those would not be handled correctly).
735 let relocations = self.get(src.alloc_id)?.relocations(self, src, size);
736 if relocations.is_empty() {
737 // nothing to copy, ignore even the `length` loop
740 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
742 new_relocations.extend(
745 .map(|&(offset, reloc)| {
746 // compute offset for current repetition
747 let dest_offset = dest.offset + (i * size);
749 // shift offsets from source allocation to destination allocation
750 offset + dest_offset - src.offset,
761 let tcx = self.tcx.tcx;
763 // This checks relocation edges on the src.
764 let src_bytes = self.get(src.alloc_id)?
765 .get_bytes_with_undef_and_ptr(&tcx, src, size)?
767 let dest_bytes = self.get_mut(dest.alloc_id)?
768 .get_bytes_mut(&tcx, dest, size * length)?
771 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
772 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
773 // `dest` could possibly overlap.
774 // The pointers above remain valid even if the `HashMap` table is moved around because they
775 // point into the `Vec` storing the bytes.
777 assert_eq!(size.bytes() as usize as u64, size.bytes());
778 if src.alloc_id == dest.alloc_id {
780 if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
781 (dest.offset <= src.offset && dest.offset + size > src.offset)
783 return err!(Intrinsic(
784 "copy_nonoverlapping called on overlapping ranges".to_string(),
791 dest_bytes.offset((size.bytes() * i) as isize),
792 size.bytes() as usize);
796 ptr::copy_nonoverlapping(src_bytes,
797 dest_bytes.offset((size.bytes() * i) as isize),
798 size.bytes() as usize);
803 // copy definedness to the destination
804 self.copy_undef_mask(src, dest, size, length)?;
805 // copy the relocations to the destination
806 self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
813 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
814 // FIXME: Add a fast version for the common, nonoverlapping case
817 src: Pointer<M::PointerTag>,
818 dest: Pointer<M::PointerTag>,
821 ) -> InterpResult<'tcx> {
822 // The bits have to be saved locally before writing to dest in case src and dest overlap.
823 assert_eq!(size.bytes() as usize as u64, size.bytes());
825 let undef_mask = &self.get(src.alloc_id)?.undef_mask;
827 // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
828 // a naive undef mask copying algorithm would repeatedly have to read the undef mask from
829 // the source and write it to the destination. Even if we optimized the memory accesses,
830 // we'd be doing all of this `repeat` times.
831 // Therefor we precompute a compressed version of the undef mask of the source value and
832 // then write it back `repeat` times without computing any more information from the source.
834 // a precomputed cache for ranges of defined/undefined bits
835 // 0000010010001110 will become
836 // [5, 1, 2, 1, 3, 3, 1]
837 // where each element toggles the state
838 let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
839 let first = undef_mask.get(src.offset);
842 for i in 1..size.bytes() {
843 // FIXME: optimize to bitshift the current undef block's bits and read the top bit
844 if undef_mask.get(src.offset + Size::from_bytes(i)) == cur {
847 ranges.push(cur_len);
853 // now fill in all the data
854 let dest_allocation = self.get_mut(dest.alloc_id)?;
855 // an optimization where we can just overwrite an entire range of definedness bits if
856 // they are going to be uniformly `1` or `0`.
857 if ranges.is_empty() {
858 dest_allocation.undef_mask.set_range_inbounds(
860 dest.offset + size * repeat,
866 // remember to fill in the trailing bits
867 ranges.push(cur_len);
869 for mut j in 0..repeat {
871 j += dest.offset.bytes();
873 for range in &ranges {
876 dest_allocation.undef_mask.set_range_inbounds(
877 Size::from_bytes(old_j),
889 scalar: Scalar<M::PointerTag>,
890 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
892 Scalar::Ptr(ptr) => Ok(ptr),
893 _ => M::int_to_ptr(scalar.to_usize(self)?, self)
899 scalar: Scalar<M::PointerTag>,
901 ) -> InterpResult<'tcx, u128> {
902 match scalar.to_bits_or_ptr(size, self) {
903 Ok(bits) => Ok(bits),
904 Err(ptr) => Ok(M::ptr_to_int(ptr, self)? as u128)