1use std::assert_matches::assert_matches;
10use std::borrow::{Borrow, Cow};
11use std::cell::Cell;
12use std::collections::VecDeque;
13use std::{fmt, ptr};
14
15use rustc_abi::{Align, HasDataLayout, Size};
16use rustc_ast::Mutability;
17use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
18use rustc_middle::mir::display_allocation;
19use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
20use rustc_middle::{bug, throw_ub_format};
21use tracing::{debug, instrument, trace};
22
23use super::{
24 AllocBytes, AllocId, AllocInit, AllocMap, AllocRange, Allocation, CheckAlignMsg,
25 CheckInAllocMsg, CtfeProvenance, GlobalAlloc, InterpCx, InterpResult, Machine, MayLeak,
26 Misalignment, Pointer, PointerArithmetic, Provenance, Scalar, alloc_range, err_ub,
27 err_ub_custom, interp_ok, throw_ub, throw_ub_custom, throw_unsup, throw_unsup_format,
28};
29use crate::const_eval::ConstEvalErrKind;
30use crate::fluent_generated as fluent;
31
32#[derive(Debug, PartialEq, Copy, Clone)]
33pub enum MemoryKind<T> {
34 Stack,
36 CallerLocation,
38 Machine(T),
40}
41
42impl<T: MayLeak> MayLeak for MemoryKind<T> {
43 #[inline]
44 fn may_leak(self) -> bool {
45 match self {
46 MemoryKind::Stack => false,
47 MemoryKind::CallerLocation => true,
48 MemoryKind::Machine(k) => k.may_leak(),
49 }
50 }
51}
52
53impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 match self {
56 MemoryKind::Stack => write!(f, "stack variable"),
57 MemoryKind::CallerLocation => write!(f, "caller location"),
58 MemoryKind::Machine(m) => write!(f, "{m}"),
59 }
60 }
61}
62
63#[derive(Copy, Clone, PartialEq, Debug)]
65pub enum AllocKind {
66 LiveData,
68 Function,
70 VTable,
72 TypeId,
74 Dead,
76}
77
78#[derive(Copy, Clone, PartialEq, Debug)]
80pub struct AllocInfo {
81 pub size: Size,
82 pub align: Align,
83 pub kind: AllocKind,
84 pub mutbl: Mutability,
85}
86
87impl AllocInfo {
88 fn new(size: Size, align: Align, kind: AllocKind, mutbl: Mutability) -> Self {
89 Self { size, align, kind, mutbl }
90 }
91}
92
93#[derive(Debug, Copy, Clone)]
95pub enum FnVal<'tcx, Other> {
96 Instance(Instance<'tcx>),
97 Other(Other),
98}
99
100impl<'tcx, Other> FnVal<'tcx, Other> {
101 pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
102 match self {
103 FnVal::Instance(instance) => interp_ok(instance),
104 FnVal::Other(_) => {
105 throw_unsup_format!("'foreign' function pointers are not supported in this context")
106 }
107 }
108 }
109}
110
111pub struct Memory<'tcx, M: Machine<'tcx>> {
114 pub(super) alloc_map: M::MemoryMap,
125
126 extra_fn_ptr_map: FxIndexMap<AllocId, M::ExtraFnVal>,
128
129 pub(super) dead_alloc_map: FxIndexMap<AllocId, (Size, Align)>,
134
135 validation_in_progress: Cell<bool>,
139}
140
141#[derive(Copy, Clone)]
144pub struct AllocRef<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes = Box<[u8]>> {
145 alloc: &'a Allocation<Prov, Extra, Bytes>,
146 range: AllocRange,
147 tcx: TyCtxt<'tcx>,
148 alloc_id: AllocId,
149}
150pub struct AllocRefMut<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes = Box<[u8]>> {
153 alloc: &'a mut Allocation<Prov, Extra, Bytes>,
154 range: AllocRange,
155 tcx: TyCtxt<'tcx>,
156 alloc_id: AllocId,
157}
158
159impl<'tcx, M: Machine<'tcx>> Memory<'tcx, M> {
160 pub fn new() -> Self {
161 Memory {
162 alloc_map: M::MemoryMap::default(),
163 extra_fn_ptr_map: FxIndexMap::default(),
164 dead_alloc_map: FxIndexMap::default(),
165 validation_in_progress: Cell::new(false),
166 }
167 }
168
169 pub fn alloc_map(&self) -> &M::MemoryMap {
171 &self.alloc_map
172 }
173}
174
175impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
176 #[inline]
186 pub fn global_root_pointer(
187 &self,
188 ptr: Pointer<CtfeProvenance>,
189 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
190 let alloc_id = ptr.provenance.alloc_id();
191 match self.tcx.try_get_global_alloc(alloc_id) {
193 Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
194 bug!("global memory cannot point to thread-local static")
197 }
198 Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
199 return M::extern_static_pointer(self, def_id);
200 }
201 None => {
202 assert!(
203 self.memory.extra_fn_ptr_map.contains_key(&alloc_id),
204 "{alloc_id:?} is neither global nor a function pointer"
205 );
206 }
207 _ => {}
208 }
209 M::adjust_alloc_root_pointer(self, ptr, M::GLOBAL_KIND.map(MemoryKind::Machine))
211 }
212
213 pub fn fn_ptr(&mut self, fn_val: FnVal<'tcx, M::ExtraFnVal>) -> Pointer<M::Provenance> {
214 let id = match fn_val {
215 FnVal::Instance(instance) => {
216 let salt = M::get_global_alloc_salt(self, Some(instance));
217 self.tcx.reserve_and_set_fn_alloc(instance, salt)
218 }
219 FnVal::Other(extra) => {
220 let id = self.tcx.reserve_alloc_id();
222 let old = self.memory.extra_fn_ptr_map.insert(id, extra);
223 assert!(old.is_none());
224 id
225 }
226 };
227 self.global_root_pointer(Pointer::from(id)).unwrap()
230 }
231
232 pub fn allocate_ptr(
233 &mut self,
234 size: Size,
235 align: Align,
236 kind: MemoryKind<M::MemoryKind>,
237 init: AllocInit,
238 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
239 let params = self.machine.get_default_alloc_params();
240 let alloc = if M::PANIC_ON_ALLOC_FAIL {
241 Allocation::new(size, align, init, params)
242 } else {
243 Allocation::try_new(size, align, init, params)?
244 };
245 self.insert_allocation(alloc, kind)
246 }
247
248 pub fn allocate_bytes_ptr(
249 &mut self,
250 bytes: &[u8],
251 align: Align,
252 kind: MemoryKind<M::MemoryKind>,
253 mutability: Mutability,
254 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
255 let params = self.machine.get_default_alloc_params();
256 let alloc = Allocation::from_bytes(bytes, align, mutability, params);
257 self.insert_allocation(alloc, kind)
258 }
259
260 pub fn insert_allocation(
261 &mut self,
262 alloc: Allocation<M::Provenance, (), M::Bytes>,
263 kind: MemoryKind<M::MemoryKind>,
264 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
265 assert!(alloc.size() <= self.max_size_of_val());
266 let id = self.tcx.reserve_alloc_id();
267 debug_assert_ne!(
268 Some(kind),
269 M::GLOBAL_KIND.map(MemoryKind::Machine),
270 "dynamically allocating global memory"
271 );
272 let extra = M::init_local_allocation(self, id, kind, alloc.size(), alloc.align)?;
275 let alloc = alloc.with_extra(extra);
276 self.memory.alloc_map.insert(id, (kind, alloc));
277 M::adjust_alloc_root_pointer(self, Pointer::from(id), Some(kind))
278 }
279
280 pub fn reallocate_ptr(
283 &mut self,
284 ptr: Pointer<Option<M::Provenance>>,
285 old_size_and_align: Option<(Size, Align)>,
286 new_size: Size,
287 new_align: Align,
288 kind: MemoryKind<M::MemoryKind>,
289 init_growth: AllocInit,
290 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
291 let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
292 if offset.bytes() != 0 {
293 throw_ub_custom!(
294 fluent::const_eval_realloc_or_alloc_with_offset,
295 ptr = format!("{ptr:?}"),
296 kind = "realloc"
297 );
298 }
299
300 let new_ptr = self.allocate_ptr(new_size, new_align, kind, init_growth)?;
306 let old_size = match old_size_and_align {
307 Some((size, _align)) => size,
308 None => self.get_alloc_raw(alloc_id)?.size(),
309 };
310 self.mem_copy(ptr, new_ptr.into(), old_size.min(new_size), true)?;
312 self.deallocate_ptr(ptr, old_size_and_align, kind)?;
313
314 interp_ok(new_ptr)
315 }
316
317 pub fn make_const_heap_ptr_global(
319 &mut self,
320 ptr: Pointer<Option<CtfeProvenance>>,
321 ) -> InterpResult<'tcx>
322 where
323 M: Machine<'tcx, MemoryKind = crate::const_eval::MemoryKind, Provenance = CtfeProvenance>,
324 {
325 let (alloc_id, offset, _) = self.ptr_get_alloc_id(ptr, 0)?;
326 if offset.bytes() != 0 {
327 return Err(ConstEvalErrKind::ConstMakeGlobalWithOffset(ptr)).into();
328 }
329
330 if matches!(self.tcx.try_get_global_alloc(alloc_id), Some(_)) {
331 return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into();
333 }
334
335 let (kind, alloc) = self
338 .memory
339 .alloc_map
340 .get_mut_or(alloc_id, || Err(ConstEvalErrKind::ConstMakeGlobalWithDanglingPtr(ptr)))?;
341
342 match kind {
344 MemoryKind::Stack | MemoryKind::CallerLocation => {
345 return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into();
346 }
347 MemoryKind::Machine(crate::const_eval::MemoryKind::Heap { was_made_global }) => {
348 if *was_made_global {
349 return Err(ConstEvalErrKind::ConstMakeGlobalPtrAlreadyMadeGlobal(alloc_id))
350 .into();
351 }
352 *was_made_global = true;
353 }
354 }
355
356 alloc.mutability = Mutability::Not;
358
359 interp_ok(())
360 }
361
362 #[instrument(skip(self), level = "debug")]
363 pub fn deallocate_ptr(
364 &mut self,
365 ptr: Pointer<Option<M::Provenance>>,
366 old_size_and_align: Option<(Size, Align)>,
367 kind: MemoryKind<M::MemoryKind>,
368 ) -> InterpResult<'tcx> {
369 let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr, 0)?;
370 trace!("deallocating: {alloc_id:?}");
371
372 if offset.bytes() != 0 {
373 throw_ub_custom!(
374 fluent::const_eval_realloc_or_alloc_with_offset,
375 ptr = format!("{ptr:?}"),
376 kind = "dealloc",
377 );
378 }
379
380 let Some((alloc_kind, mut alloc)) = self.memory.alloc_map.remove(&alloc_id) else {
381 return Err(match self.tcx.try_get_global_alloc(alloc_id) {
383 Some(GlobalAlloc::Function { .. }) => {
384 err_ub_custom!(
385 fluent::const_eval_invalid_dealloc,
386 alloc_id = alloc_id,
387 kind = "fn",
388 )
389 }
390 Some(GlobalAlloc::VTable(..)) => {
391 err_ub_custom!(
392 fluent::const_eval_invalid_dealloc,
393 alloc_id = alloc_id,
394 kind = "vtable",
395 )
396 }
397 Some(GlobalAlloc::TypeId { .. }) => {
398 err_ub_custom!(
399 fluent::const_eval_invalid_dealloc,
400 alloc_id = alloc_id,
401 kind = "typeid",
402 )
403 }
404 Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
405 err_ub_custom!(
406 fluent::const_eval_invalid_dealloc,
407 alloc_id = alloc_id,
408 kind = "static_mem"
409 )
410 }
411 None => err_ub!(PointerUseAfterFree(alloc_id, CheckInAllocMsg::MemoryAccess)),
412 })
413 .into();
414 };
415
416 if alloc.mutability.is_not() {
417 throw_ub_custom!(fluent::const_eval_dealloc_immutable, alloc = alloc_id,);
418 }
419 if alloc_kind != kind {
420 throw_ub_custom!(
421 fluent::const_eval_dealloc_kind_mismatch,
422 alloc = alloc_id,
423 alloc_kind = format!("{alloc_kind}"),
424 kind = format!("{kind}"),
425 );
426 }
427 if let Some((size, align)) = old_size_and_align {
428 if size != alloc.size() || align != alloc.align {
429 throw_ub_custom!(
430 fluent::const_eval_dealloc_incorrect_layout,
431 alloc = alloc_id,
432 size = alloc.size().bytes(),
433 align = alloc.align.bytes(),
434 size_found = size.bytes(),
435 align_found = align.bytes(),
436 )
437 }
438 }
439
440 let size = alloc.size();
442 M::before_memory_deallocation(
443 self.tcx,
444 &mut self.machine,
445 &mut alloc.extra,
446 ptr,
447 (alloc_id, prov),
448 size,
449 alloc.align,
450 kind,
451 )?;
452
453 let old = self.memory.dead_alloc_map.insert(alloc_id, (size, alloc.align));
455 if old.is_some() {
456 bug!("Nothing can be deallocated twice");
457 }
458
459 interp_ok(())
460 }
461
462 #[inline(always)]
464 fn get_ptr_access(
465 &self,
466 ptr: Pointer<Option<M::Provenance>>,
467 size: Size,
468 ) -> InterpResult<'tcx, Option<(AllocId, Size, M::ProvenanceExtra)>> {
469 let size = i64::try_from(size.bytes()).unwrap(); Self::check_and_deref_ptr(
471 self,
472 ptr,
473 size,
474 CheckInAllocMsg::MemoryAccess,
475 |this, alloc_id, offset, prov| {
476 let (size, align) =
477 this.get_live_alloc_size_and_align(alloc_id, CheckInAllocMsg::MemoryAccess)?;
478 interp_ok((size, align, (alloc_id, offset, prov)))
479 },
480 )
481 }
482
483 #[inline(always)]
486 pub fn check_ptr_access(
487 &self,
488 ptr: Pointer<Option<M::Provenance>>,
489 size: Size,
490 msg: CheckInAllocMsg,
491 ) -> InterpResult<'tcx> {
492 let size = i64::try_from(size.bytes()).unwrap(); Self::check_and_deref_ptr(self, ptr, size, msg, |this, alloc_id, _, _| {
494 let (size, align) = this.get_live_alloc_size_and_align(alloc_id, msg)?;
495 interp_ok((size, align, ()))
496 })?;
497 interp_ok(())
498 }
499
500 pub fn check_ptr_access_signed(
504 &self,
505 ptr: Pointer<Option<M::Provenance>>,
506 size: i64,
507 msg: CheckInAllocMsg,
508 ) -> InterpResult<'tcx> {
509 Self::check_and_deref_ptr(self, ptr, size, msg, |this, alloc_id, _, _| {
510 let (size, align) = this.get_live_alloc_size_and_align(alloc_id, msg)?;
511 interp_ok((size, align, ()))
512 })?;
513 interp_ok(())
514 }
515
516 fn check_and_deref_ptr<T, R: Borrow<Self>>(
525 this: R,
526 ptr: Pointer<Option<M::Provenance>>,
527 size: i64,
528 msg: CheckInAllocMsg,
529 alloc_size: impl FnOnce(
530 R,
531 AllocId,
532 Size,
533 M::ProvenanceExtra,
534 ) -> InterpResult<'tcx, (Size, Align, T)>,
535 ) -> InterpResult<'tcx, Option<T>> {
536 if size == 0 {
538 return interp_ok(None);
539 }
540
541 interp_ok(match this.borrow().ptr_try_get_alloc_id(ptr, size) {
542 Err(addr) => {
543 throw_ub!(DanglingIntPointer { addr, inbounds_size: size, msg });
545 }
546 Ok((alloc_id, offset, prov)) => {
547 let tcx = this.borrow().tcx;
548 let (alloc_size, _alloc_align, ret_val) = alloc_size(this, alloc_id, offset, prov)?;
549 let offset = offset.bytes();
550 let (begin, end) = if size >= 0 {
552 (Some(offset), offset.checked_add(size as u64))
553 } else {
554 (offset.checked_sub(size.unsigned_abs()), Some(offset))
555 };
556 let in_bounds = begin.is_some() && end.is_some_and(|e| e <= alloc_size.bytes());
558 if !in_bounds {
559 throw_ub!(PointerOutOfBounds {
560 alloc_id,
561 alloc_size,
562 ptr_offset: tcx.sign_extend_to_target_isize(offset),
563 inbounds_size: size,
564 msg,
565 })
566 }
567
568 Some(ret_val)
569 }
570 })
571 }
572
573 pub(super) fn check_misalign(
574 &self,
575 misaligned: Option<Misalignment>,
576 msg: CheckAlignMsg,
577 ) -> InterpResult<'tcx> {
578 if let Some(misaligned) = misaligned {
579 throw_ub!(AlignmentCheckFailed(misaligned, msg))
580 }
581 interp_ok(())
582 }
583
584 pub(super) fn is_ptr_misaligned(
585 &self,
586 ptr: Pointer<Option<M::Provenance>>,
587 align: Align,
588 ) -> Option<Misalignment> {
589 if !M::enforce_alignment(self) || align.bytes() == 1 {
590 return None;
591 }
592
593 #[inline]
594 fn is_offset_misaligned(offset: u64, align: Align) -> Option<Misalignment> {
595 if offset.is_multiple_of(align.bytes()) {
596 None
597 } else {
598 let offset_pow2 = 1 << offset.trailing_zeros();
600 Some(Misalignment { has: Align::from_bytes(offset_pow2).unwrap(), required: align })
601 }
602 }
603
604 match self.ptr_try_get_alloc_id(ptr, 0) {
605 Err(addr) => is_offset_misaligned(addr, align),
606 Ok((alloc_id, offset, _prov)) => {
607 let alloc_info = self.get_alloc_info(alloc_id);
608 if let Some(misalign) = M::alignment_check(
609 self,
610 alloc_id,
611 alloc_info.align,
612 alloc_info.kind,
613 offset,
614 align,
615 ) {
616 Some(misalign)
617 } else if M::Provenance::OFFSET_IS_ADDR {
618 is_offset_misaligned(ptr.addr().bytes(), align)
619 } else {
620 if alloc_info.align.bytes() < align.bytes() {
622 Some(Misalignment { has: alloc_info.align, required: align })
623 } else {
624 is_offset_misaligned(offset.bytes(), align)
625 }
626 }
627 }
628 }
629 }
630
631 pub fn check_ptr_align(
635 &self,
636 ptr: Pointer<Option<M::Provenance>>,
637 align: Align,
638 ) -> InterpResult<'tcx> {
639 self.check_misalign(self.is_ptr_misaligned(ptr, align), CheckAlignMsg::AccessedPtr)
640 }
641}
642
643impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
644 pub fn remove_unreachable_allocs(&mut self, reachable_allocs: &FxHashSet<AllocId>) {
646 #[allow(rustc::potential_query_instability)] self.memory.dead_alloc_map.retain(|id, _| reachable_allocs.contains(id));
651 }
652}
653
654impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
656 fn get_global_alloc(
662 &self,
663 id: AllocId,
664 is_write: bool,
665 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::Provenance, M::AllocExtra, M::Bytes>>> {
666 let (alloc, def_id) = match self.tcx.try_get_global_alloc(id) {
667 Some(GlobalAlloc::Memory(mem)) => {
668 (mem, None)
670 }
671 Some(GlobalAlloc::Function { .. }) => throw_ub!(DerefFunctionPointer(id)),
672 Some(GlobalAlloc::VTable(..)) => throw_ub!(DerefVTablePointer(id)),
673 Some(GlobalAlloc::TypeId { .. }) => throw_ub!(DerefTypeIdPointer(id)),
674 None => throw_ub!(PointerUseAfterFree(id, CheckInAllocMsg::MemoryAccess)),
675 Some(GlobalAlloc::Static(def_id)) => {
676 assert!(self.tcx.is_static(def_id));
677 assert!(!self.tcx.is_thread_local_static(def_id));
680 if self.tcx.is_foreign_item(def_id) {
691 throw_unsup!(ExternStatic(def_id));
694 }
695
696 let val = self.ctfe_query(|tcx| tcx.eval_static_initializer(def_id))?;
698 (val, Some(def_id))
699 }
700 };
701 M::before_access_global(self.tcx, &self.machine, id, alloc, def_id, is_write)?;
702 M::adjust_global_allocation(
704 self,
705 id, alloc.inner(),
707 )
708 }
709
710 pub fn get_alloc_raw(
715 &self,
716 id: AllocId,
717 ) -> InterpResult<'tcx, &Allocation<M::Provenance, M::AllocExtra, M::Bytes>> {
718 let a = self.memory.alloc_map.get_or(id, || {
723 let alloc = self.get_global_alloc(id, false).report_err().map_err(Err)?;
726 match alloc {
727 Cow::Borrowed(alloc) => {
728 Err(Ok(alloc))
731 }
732 Cow::Owned(alloc) => {
733 let kind = M::GLOBAL_KIND.expect(
735 "I got a global allocation that I have to copy but the machine does \
736 not expect that to happen",
737 );
738 Ok((MemoryKind::Machine(kind), alloc))
739 }
740 }
741 });
742 match a {
744 Ok(a) => interp_ok(&a.1),
745 Err(a) => a.into(),
746 }
747 }
748
749 pub fn get_alloc_bytes_unchecked_raw(&self, id: AllocId) -> InterpResult<'tcx, *const u8> {
752 let alloc = self.get_alloc_raw(id)?;
753 interp_ok(alloc.get_bytes_unchecked_raw())
754 }
755
756 pub fn get_ptr_alloc<'a>(
758 &'a self,
759 ptr: Pointer<Option<M::Provenance>>,
760 size: Size,
761 ) -> InterpResult<'tcx, Option<AllocRef<'a, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
762 {
763 let size_i64 = i64::try_from(size.bytes()).unwrap(); let ptr_and_alloc = Self::check_and_deref_ptr(
765 self,
766 ptr,
767 size_i64,
768 CheckInAllocMsg::MemoryAccess,
769 |this, alloc_id, offset, prov| {
770 let alloc = this.get_alloc_raw(alloc_id)?;
771 interp_ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc)))
772 },
773 )?;
774 if !self.memory.validation_in_progress.get() {
778 if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(ptr, size_i64) {
779 M::before_alloc_access(self.tcx, &self.machine, alloc_id)?;
780 }
781 }
782
783 if let Some((alloc_id, offset, prov, alloc)) = ptr_and_alloc {
784 let range = alloc_range(offset, size);
785 if !self.memory.validation_in_progress.get() {
786 M::before_memory_read(
787 self.tcx,
788 &self.machine,
789 &alloc.extra,
790 ptr,
791 (alloc_id, prov),
792 range,
793 )?;
794 }
795 interp_ok(Some(AllocRef { alloc, range, tcx: *self.tcx, alloc_id }))
796 } else {
797 interp_ok(None)
798 }
799 }
800
801 pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> {
803 interp_ok(&self.get_alloc_raw(id)?.extra)
804 }
805
806 pub fn get_alloc_mutability<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, Mutability> {
808 interp_ok(self.get_alloc_raw(id)?.mutability)
809 }
810
811 pub fn get_alloc_raw_mut(
819 &mut self,
820 id: AllocId,
821 ) -> InterpResult<'tcx, (&mut Allocation<M::Provenance, M::AllocExtra, M::Bytes>, &mut M)> {
822 if self.memory.alloc_map.get_mut(id).is_none() {
830 let alloc = self.get_global_alloc(id, true)?;
833 let kind = M::GLOBAL_KIND.expect(
834 "I got a global allocation that I have to copy but the machine does \
835 not expect that to happen",
836 );
837 self.memory.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned()));
838 }
839
840 let (_kind, alloc) = self.memory.alloc_map.get_mut(id).unwrap();
841 if alloc.mutability.is_not() {
842 throw_ub!(WriteToReadOnly(id))
843 }
844 interp_ok((alloc, &mut self.machine))
845 }
846
847 pub fn get_alloc_bytes_unchecked_raw_mut(
850 &mut self,
851 id: AllocId,
852 ) -> InterpResult<'tcx, *mut u8> {
853 let alloc = self.get_alloc_raw_mut(id)?.0;
854 interp_ok(alloc.get_bytes_unchecked_raw_mut())
855 }
856
857 pub fn get_ptr_alloc_mut<'a>(
859 &'a mut self,
860 ptr: Pointer<Option<M::Provenance>>,
861 size: Size,
862 ) -> InterpResult<'tcx, Option<AllocRefMut<'a, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>>
863 {
864 let tcx = self.tcx;
865 let validation_in_progress = self.memory.validation_in_progress.get();
866
867 let size_i64 = i64::try_from(size.bytes()).unwrap(); let ptr_and_alloc = Self::check_and_deref_ptr(
869 self,
870 ptr,
871 size_i64,
872 CheckInAllocMsg::MemoryAccess,
873 |this, alloc_id, offset, prov| {
874 let (alloc, machine) = this.get_alloc_raw_mut(alloc_id)?;
875 interp_ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc, machine)))
876 },
877 )?;
878
879 if let Some((alloc_id, offset, prov, alloc, machine)) = ptr_and_alloc {
880 let range = alloc_range(offset, size);
881 if !validation_in_progress {
882 M::before_alloc_access(tcx, machine, alloc_id)?;
885 M::before_memory_write(
886 tcx,
887 machine,
888 &mut alloc.extra,
889 ptr,
890 (alloc_id, prov),
891 range,
892 )?;
893 }
894 interp_ok(Some(AllocRefMut { alloc, range, tcx: *tcx, alloc_id }))
895 } else {
896 interp_ok(None)
897 }
898 }
899
900 pub fn get_alloc_extra_mut<'a>(
902 &'a mut self,
903 id: AllocId,
904 ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M)> {
905 let (alloc, machine) = self.get_alloc_raw_mut(id)?;
906 interp_ok((&mut alloc.extra, machine))
907 }
908
909 pub fn is_alloc_live(&self, id: AllocId) -> bool {
913 self.memory.alloc_map.contains_key_ref(&id)
914 || self.memory.extra_fn_ptr_map.contains_key(&id)
915 || self.tcx.try_get_global_alloc(id).is_some()
918 }
919
920 pub fn get_alloc_info(&self, id: AllocId) -> AllocInfo {
923 if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
928 return AllocInfo::new(
929 alloc.size(),
930 alloc.align,
931 AllocKind::LiveData,
932 alloc.mutability,
933 );
934 }
935
936 if let Some(fn_val) = self.get_fn_alloc(id) {
939 let align = match fn_val {
940 FnVal::Instance(_instance) => {
941 Align::ONE
946 }
947 FnVal::Other(_) => Align::ONE,
949 };
950
951 return AllocInfo::new(Size::ZERO, align, AllocKind::Function, Mutability::Not);
952 }
953
954 if let Some(global_alloc) = self.tcx.try_get_global_alloc(id) {
956 let (size, align) = global_alloc.size_and_align(*self.tcx, self.typing_env);
958 let mutbl = global_alloc.mutability(*self.tcx, self.typing_env);
959 let kind = match global_alloc {
960 GlobalAlloc::Static { .. } | GlobalAlloc::Memory { .. } => AllocKind::LiveData,
961 GlobalAlloc::Function { .. } => bug!("We already checked function pointers above"),
962 GlobalAlloc::VTable { .. } => AllocKind::VTable,
963 GlobalAlloc::TypeId { .. } => AllocKind::TypeId,
964 };
965 return AllocInfo::new(size, align, kind, mutbl);
966 }
967
968 let (size, align) = *self
970 .memory
971 .dead_alloc_map
972 .get(&id)
973 .expect("deallocated pointers should all be recorded in `dead_alloc_map`");
974 AllocInfo::new(size, align, AllocKind::Dead, Mutability::Not)
975 }
976
977 fn get_live_alloc_size_and_align(
979 &self,
980 id: AllocId,
981 msg: CheckInAllocMsg,
982 ) -> InterpResult<'tcx, (Size, Align)> {
983 let info = self.get_alloc_info(id);
984 if matches!(info.kind, AllocKind::Dead) {
985 throw_ub!(PointerUseAfterFree(id, msg))
986 }
987 interp_ok((info.size, info.align))
988 }
989
990 fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
991 if let Some(extra) = self.memory.extra_fn_ptr_map.get(&id) {
992 Some(FnVal::Other(*extra))
993 } else {
994 match self.tcx.try_get_global_alloc(id) {
995 Some(GlobalAlloc::Function { instance, .. }) => Some(FnVal::Instance(instance)),
996 _ => None,
997 }
998 }
999 }
1000
1001 pub fn get_ptr_type_id(
1004 &self,
1005 ptr: Pointer<Option<M::Provenance>>,
1006 ) -> InterpResult<'tcx, (Ty<'tcx>, u64)> {
1007 let (alloc_id, offset, _meta) = self.ptr_get_alloc_id(ptr, 0)?;
1008 let Some(GlobalAlloc::TypeId { ty }) = self.tcx.try_get_global_alloc(alloc_id) else {
1009 throw_ub_format!("invalid `TypeId` value: not all bytes carry type id metadata")
1010 };
1011 interp_ok((ty, offset.bytes()))
1012 }
1013
1014 pub fn get_ptr_fn(
1015 &self,
1016 ptr: Pointer<Option<M::Provenance>>,
1017 ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
1018 trace!("get_ptr_fn({:?})", ptr);
1019 let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
1020 if offset.bytes() != 0 {
1021 throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset)))
1022 }
1023 self.get_fn_alloc(alloc_id)
1024 .ok_or_else(|| err_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))))
1025 .into()
1026 }
1027
1028 pub fn get_ptr_vtable_ty(
1031 &self,
1032 ptr: Pointer<Option<M::Provenance>>,
1033 expected_trait: Option<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>,
1034 ) -> InterpResult<'tcx, Ty<'tcx>> {
1035 trace!("get_ptr_vtable({:?})", ptr);
1036 let (alloc_id, offset, _tag) = self.ptr_get_alloc_id(ptr, 0)?;
1037 if offset.bytes() != 0 {
1038 throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset)))
1039 }
1040 let Some(GlobalAlloc::VTable(ty, vtable_dyn_type)) =
1041 self.tcx.try_get_global_alloc(alloc_id)
1042 else {
1043 throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset)))
1044 };
1045 if let Some(expected_dyn_type) = expected_trait {
1046 self.check_vtable_for_type(vtable_dyn_type, expected_dyn_type)?;
1047 }
1048 interp_ok(ty)
1049 }
1050
1051 pub fn alloc_mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
1052 self.get_alloc_raw_mut(id)?.0.mutability = Mutability::Not;
1053 interp_ok(())
1054 }
1055
1056 pub fn visit_reachable_allocs(
1059 &mut self,
1060 start: Vec<AllocId>,
1061 mut visit: impl FnMut(&mut Self, AllocId, &AllocInfo) -> InterpResult<'tcx>,
1062 ) -> InterpResult<'tcx> {
1063 let mut done = FxHashSet::default();
1064 let mut todo = start;
1065 while let Some(id) = todo.pop() {
1066 if !done.insert(id) {
1067 continue;
1069 }
1070 let info = self.get_alloc_info(id);
1071
1072 if matches!(info.kind, AllocKind::LiveData) {
1076 let alloc = self.get_alloc_raw(id)?;
1077 for prov in alloc.provenance().provenances() {
1078 if let Some(id) = prov.get_alloc_id() {
1079 todo.push(id);
1080 }
1081 }
1082 }
1083
1084 visit(self, id, &info)?;
1086 }
1087 interp_ok(())
1088 }
1089
1090 #[must_use]
1093 pub fn dump_alloc<'a>(&'a self, id: AllocId) -> DumpAllocs<'a, 'tcx, M> {
1094 self.dump_allocs(vec![id])
1095 }
1096
1097 #[must_use]
1100 pub fn dump_allocs<'a>(&'a self, mut allocs: Vec<AllocId>) -> DumpAllocs<'a, 'tcx, M> {
1101 allocs.sort();
1102 allocs.dedup();
1103 DumpAllocs { ecx: self, allocs }
1104 }
1105
1106 pub fn print_alloc_bytes_for_diagnostics(&self, id: AllocId) -> String {
1108 let alloc = self.get_alloc_raw(id).unwrap();
1111 let mut bytes = String::new();
1112 if alloc.size() != Size::ZERO {
1113 bytes = "\n".into();
1114 rustc_middle::mir::pretty::write_allocation_bytes(*self.tcx, alloc, &mut bytes, " ")
1116 .unwrap();
1117 }
1118 bytes
1119 }
1120
1121 pub fn take_leaked_allocations(
1127 &mut self,
1128 static_roots: impl FnOnce(&Self) -> &[AllocId],
1129 ) -> Vec<(AllocId, MemoryKind<M::MemoryKind>, Allocation<M::Provenance, M::AllocExtra, M::Bytes>)>
1130 {
1131 let reachable = {
1133 let mut reachable = FxHashSet::default();
1134 let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
1135 let mut todo: Vec<_> =
1136 self.memory.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
1137 if Some(kind) == global_kind { Some(id) } else { None }
1138 });
1139 todo.extend(static_roots(self));
1140 while let Some(id) = todo.pop() {
1141 if reachable.insert(id) {
1142 if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
1146 todo.extend(
1147 alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id()),
1148 );
1149 }
1150 }
1151 }
1152 reachable
1153 };
1154
1155 let leaked: Vec<_> = self.memory.alloc_map.filter_map_collect(|&id, &(kind, _)| {
1157 if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
1158 });
1159 let mut result = Vec::new();
1160 for &id in leaked.iter() {
1161 let (kind, alloc) = self.memory.alloc_map.remove(&id).unwrap();
1162 result.push((id, kind, alloc));
1163 }
1164 result
1165 }
1166
1167 pub fn run_for_validation_mut<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1173 assert!(
1176 self.memory.validation_in_progress.replace(true) == false,
1177 "`validation_in_progress` was already set"
1178 );
1179 let res = f(self);
1180 assert!(
1181 self.memory.validation_in_progress.replace(false) == true,
1182 "`validation_in_progress` was unset by someone else"
1183 );
1184 res
1185 }
1186
1187 pub fn run_for_validation_ref<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
1193 assert!(
1196 self.memory.validation_in_progress.replace(true) == false,
1197 "`validation_in_progress` was already set"
1198 );
1199 let res = f(self);
1200 assert!(
1201 self.memory.validation_in_progress.replace(false) == true,
1202 "`validation_in_progress` was unset by someone else"
1203 );
1204 res
1205 }
1206
1207 pub(super) fn validation_in_progress(&self) -> bool {
1208 self.memory.validation_in_progress.get()
1209 }
1210}
1211
1212#[doc(hidden)]
1213pub struct DumpAllocs<'a, 'tcx, M: Machine<'tcx>> {
1215 ecx: &'a InterpCx<'tcx, M>,
1216 allocs: Vec<AllocId>,
1217}
1218
1219impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debug for DumpAllocs<'a, 'tcx, M> {
1220 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1221 fn write_allocation_track_relocs<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1223 fmt: &mut std::fmt::Formatter<'_>,
1224 tcx: TyCtxt<'tcx>,
1225 allocs_to_print: &mut VecDeque<AllocId>,
1226 alloc: &Allocation<Prov, Extra, Bytes>,
1227 ) -> std::fmt::Result {
1228 for alloc_id in alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id())
1229 {
1230 allocs_to_print.push_back(alloc_id);
1231 }
1232 write!(fmt, "{}", display_allocation(tcx, alloc))
1233 }
1234
1235 let mut allocs_to_print: VecDeque<_> = self.allocs.iter().copied().collect();
1236 let mut allocs_printed = FxHashSet::default();
1238
1239 while let Some(id) = allocs_to_print.pop_front() {
1240 if !allocs_printed.insert(id) {
1241 continue;
1243 }
1244
1245 write!(fmt, "{id:?}")?;
1246 match self.ecx.memory.alloc_map.get(id) {
1247 Some((kind, alloc)) => {
1248 write!(fmt, " ({kind}, ")?;
1250 write_allocation_track_relocs(
1251 &mut *fmt,
1252 *self.ecx.tcx,
1253 &mut allocs_to_print,
1254 alloc,
1255 )?;
1256 }
1257 None => {
1258 match self.ecx.tcx.try_get_global_alloc(id) {
1260 Some(GlobalAlloc::Memory(alloc)) => {
1261 write!(fmt, " (unchanged global, ")?;
1262 write_allocation_track_relocs(
1263 &mut *fmt,
1264 *self.ecx.tcx,
1265 &mut allocs_to_print,
1266 alloc.inner(),
1267 )?;
1268 }
1269 Some(GlobalAlloc::Function { instance, .. }) => {
1270 write!(fmt, " (fn: {instance})")?;
1271 }
1272 Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1273 write!(fmt, " (vtable: impl {dyn_ty} for {ty})")?;
1274 }
1275 Some(GlobalAlloc::TypeId { ty }) => {
1276 write!(fmt, " (typeid for {ty})")?;
1277 }
1278 Some(GlobalAlloc::Static(did)) => {
1279 write!(fmt, " (static: {})", self.ecx.tcx.def_path_str(did))?;
1280 }
1281 None => {
1282 write!(fmt, " (deallocated)")?;
1283 }
1284 }
1285 }
1286 }
1287 writeln!(fmt)?;
1288 }
1289 Ok(())
1290 }
1291}
1292
1293impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>
1295 AllocRefMut<'a, 'tcx, Prov, Extra, Bytes>
1296{
1297 pub fn as_ref<'b>(&'b self) -> AllocRef<'b, 'tcx, Prov, Extra, Bytes> {
1298 AllocRef { alloc: self.alloc, range: self.range, tcx: self.tcx, alloc_id: self.alloc_id }
1299 }
1300
1301 pub fn write_scalar(&mut self, range: AllocRange, val: Scalar<Prov>) -> InterpResult<'tcx> {
1303 let range = self.range.subrange(range);
1304 debug!("write_scalar at {:?}{range:?}: {val:?}", self.alloc_id);
1305
1306 self.alloc
1307 .write_scalar(&self.tcx, range, val)
1308 .map_err(|e| e.to_interp_error(self.alloc_id))
1309 .into()
1310 }
1311
1312 pub fn write_ptr_sized(&mut self, offset: Size, val: Scalar<Prov>) -> InterpResult<'tcx> {
1314 self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size()), val)
1315 }
1316
1317 pub fn write_uninit(&mut self, range: AllocRange) {
1319 let range = self.range.subrange(range);
1320
1321 self.alloc.write_uninit(&self.tcx, range);
1322 }
1323
1324 pub fn write_uninit_full(&mut self) {
1326 self.alloc.write_uninit(&self.tcx, self.range);
1327 }
1328
1329 pub fn clear_provenance(&mut self) {
1331 self.alloc.clear_provenance(&self.tcx, self.range);
1332 }
1333}
1334
1335impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
1336 pub fn read_scalar(
1338 &self,
1339 range: AllocRange,
1340 read_provenance: bool,
1341 ) -> InterpResult<'tcx, Scalar<Prov>> {
1342 let range = self.range.subrange(range);
1343 self.alloc
1344 .read_scalar(&self.tcx, range, read_provenance)
1345 .map_err(|e| e.to_interp_error(self.alloc_id))
1346 .into()
1347 }
1348
1349 pub fn read_integer(&self, range: AllocRange) -> InterpResult<'tcx, Scalar<Prov>> {
1351 self.read_scalar(range, false)
1352 }
1353
1354 pub fn read_pointer(&self, offset: Size) -> InterpResult<'tcx, Scalar<Prov>> {
1356 self.read_scalar(
1357 alloc_range(offset, self.tcx.data_layout().pointer_size()),
1358 true,
1359 )
1360 }
1361
1362 pub fn get_bytes_strip_provenance<'b>(&'b self) -> InterpResult<'tcx, &'a [u8]> {
1364 self.alloc
1365 .get_bytes_strip_provenance(&self.tcx, self.range)
1366 .map_err(|e| e.to_interp_error(self.alloc_id))
1367 .into()
1368 }
1369
1370 pub fn has_provenance(&self) -> bool {
1372 !self.alloc.provenance().range_empty(self.range, &self.tcx)
1373 }
1374}
1375
1376impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1377 pub fn read_bytes_ptr_strip_provenance(
1382 &self,
1383 ptr: Pointer<Option<M::Provenance>>,
1384 size: Size,
1385 ) -> InterpResult<'tcx, &[u8]> {
1386 let Some(alloc_ref) = self.get_ptr_alloc(ptr, size)? else {
1387 return interp_ok(&[]);
1389 };
1390 interp_ok(
1393 alloc_ref
1394 .alloc
1395 .get_bytes_strip_provenance(&alloc_ref.tcx, alloc_ref.range)
1396 .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?,
1397 )
1398 }
1399
1400 pub fn write_bytes_ptr(
1404 &mut self,
1405 ptr: Pointer<Option<M::Provenance>>,
1406 src: impl IntoIterator<Item = u8>,
1407 ) -> InterpResult<'tcx> {
1408 let mut src = src.into_iter();
1409 let (lower, upper) = src.size_hint();
1410 let len = upper.expect("can only write bounded iterators");
1411 assert_eq!(lower, len, "can only write iterators with a precise length");
1412
1413 let size = Size::from_bytes(len);
1414 let Some(alloc_ref) = self.get_ptr_alloc_mut(ptr, size)? else {
1415 assert_matches!(src.next(), None, "iterator said it was empty but returned an element");
1417 return interp_ok(());
1418 };
1419
1420 let bytes =
1423 alloc_ref.alloc.get_bytes_unchecked_for_overwrite(&alloc_ref.tcx, alloc_ref.range);
1424 for dest in bytes {
1427 *dest = src.next().expect("iterator was shorter than it said it would be");
1428 }
1429 assert_matches!(src.next(), None, "iterator was longer than it said it would be");
1430 interp_ok(())
1431 }
1432
1433 pub fn mem_copy(
1434 &mut self,
1435 src: Pointer<Option<M::Provenance>>,
1436 dest: Pointer<Option<M::Provenance>>,
1437 size: Size,
1438 nonoverlapping: bool,
1439 ) -> InterpResult<'tcx> {
1440 self.mem_copy_repeatedly(src, dest, size, 1, nonoverlapping)
1441 }
1442
1443 pub fn mem_copy_repeatedly(
1449 &mut self,
1450 src: Pointer<Option<M::Provenance>>,
1451 dest: Pointer<Option<M::Provenance>>,
1452 size: Size,
1453 num_copies: u64,
1454 nonoverlapping: bool,
1455 ) -> InterpResult<'tcx> {
1456 let tcx = self.tcx;
1457 let src_parts = self.get_ptr_access(src, size)?;
1459 let dest_parts = self.get_ptr_access(dest, size * num_copies)?; if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(src, size.bytes().try_into().unwrap())
1465 {
1466 M::before_alloc_access(tcx, &self.machine, alloc_id)?;
1467 }
1468
1469 let Some((src_alloc_id, src_offset, src_prov)) = src_parts else {
1474 return interp_ok(());
1476 };
1477 let src_alloc = self.get_alloc_raw(src_alloc_id)?;
1478 let src_range = alloc_range(src_offset, size);
1479 assert!(!self.memory.validation_in_progress.get(), "we can't be copying during validation");
1480
1481 M::before_memory_read(
1485 tcx,
1486 &self.machine,
1487 &src_alloc.extra,
1488 src,
1489 (src_alloc_id, src_prov),
1490 src_range,
1491 )?;
1492 let Some((dest_alloc_id, dest_offset, dest_prov)) = dest_parts else {
1495 return interp_ok(());
1497 };
1498
1499 let src_bytes = src_alloc.get_bytes_unchecked(src_range).as_ptr(); let provenance = src_alloc
1506 .provenance()
1507 .prepare_copy(src_range, self)
1508 .map_err(|e| e.to_interp_error(src_alloc_id))?;
1509 let init = src_alloc.init_mask().prepare_copy(src_range);
1511
1512 let (dest_alloc, machine) = self.get_alloc_raw_mut(dest_alloc_id)?;
1514 let dest_range = alloc_range(dest_offset, size * num_copies);
1515 M::before_alloc_access(tcx, machine, dest_alloc_id)?;
1517 M::before_memory_write(
1518 tcx,
1519 machine,
1520 &mut dest_alloc.extra,
1521 dest,
1522 (dest_alloc_id, dest_prov),
1523 dest_range,
1524 )?;
1525 let dest_bytes =
1527 dest_alloc.get_bytes_unchecked_for_overwrite_ptr(&tcx, dest_range).as_mut_ptr();
1528
1529 if init.no_bytes_init() {
1530 dest_alloc.write_uninit(&tcx, dest_range);
1537 return interp_ok(());
1539 }
1540
1541 unsafe {
1547 if src_alloc_id == dest_alloc_id {
1548 if nonoverlapping {
1549 if (src_offset <= dest_offset && src_offset + size > dest_offset)
1551 || (dest_offset <= src_offset && dest_offset + size > src_offset)
1552 {
1553 throw_ub_custom!(fluent::const_eval_copy_nonoverlapping_overlapping);
1554 }
1555 }
1556 }
1557 if num_copies > 1 {
1558 assert!(nonoverlapping, "multi-copy only supported in non-overlapping mode");
1559 }
1560
1561 let size_in_bytes = size.bytes_usize();
1562 if size_in_bytes == 1 {
1565 debug_assert!(num_copies >= 1); let value = *src_bytes;
1568 dest_bytes.write_bytes(value, (size * num_copies).bytes_usize());
1569 } else if src_alloc_id == dest_alloc_id {
1570 let mut dest_ptr = dest_bytes;
1571 for _ in 0..num_copies {
1572 ptr::copy(src_bytes, dest_ptr, size_in_bytes);
1575 dest_ptr = dest_ptr.add(size_in_bytes);
1576 }
1577 } else {
1578 let mut dest_ptr = dest_bytes;
1579 for _ in 0..num_copies {
1580 ptr::copy_nonoverlapping(src_bytes, dest_ptr, size_in_bytes);
1581 dest_ptr = dest_ptr.add(size_in_bytes);
1582 }
1583 }
1584 }
1585
1586 dest_alloc.init_mask_apply_copy(
1588 init,
1589 alloc_range(dest_offset, size), num_copies,
1591 );
1592 dest_alloc.provenance_apply_copy(provenance, alloc_range(dest_offset, size), num_copies);
1594
1595 interp_ok(())
1596 }
1597}
1598
1599impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1601 pub fn scalar_may_be_null(&self, scalar: Scalar<M::Provenance>) -> InterpResult<'tcx, bool> {
1604 match scalar.try_to_scalar_int() {
1605 Ok(int) => interp_ok(int.is_null()),
1606 Err(_) => {
1607 let ptr = scalar.to_pointer(self)?;
1609 match self.ptr_try_get_alloc_id(ptr, 0) {
1610 Ok((alloc_id, offset, _)) => {
1611 let info = self.get_alloc_info(alloc_id);
1612 if matches!(info.kind, AllocKind::TypeId) {
1613 return interp_ok(true);
1618 }
1619 if offset <= info.size {
1621 return interp_ok(false);
1622 }
1623 if !offset.bytes().is_multiple_of(info.align.bytes()) {
1627 return interp_ok(false);
1628 }
1629 interp_ok(true)
1631 }
1632 Err(_offset) => bug!("a non-int scalar is always a pointer"),
1633 }
1634 }
1635 }
1636 }
1637
1638 pub fn ptr_try_get_alloc_id(
1652 &self,
1653 ptr: Pointer<Option<M::Provenance>>,
1654 size: i64,
1655 ) -> Result<(AllocId, Size, M::ProvenanceExtra), u64> {
1656 match ptr.into_pointer_or_addr() {
1657 Ok(ptr) => match M::ptr_get_alloc(self, ptr, size) {
1658 Some((alloc_id, offset, extra)) => Ok((alloc_id, offset, extra)),
1659 None => {
1660 assert!(M::Provenance::OFFSET_IS_ADDR);
1661 let (_, addr) = ptr.into_raw_parts();
1663 Err(addr.bytes())
1664 }
1665 },
1666 Err(addr) => Err(addr.bytes()),
1667 }
1668 }
1669
1670 #[inline(always)]
1683 pub fn ptr_get_alloc_id(
1684 &self,
1685 ptr: Pointer<Option<M::Provenance>>,
1686 size: i64,
1687 ) -> InterpResult<'tcx, (AllocId, Size, M::ProvenanceExtra)> {
1688 self.ptr_try_get_alloc_id(ptr, size)
1689 .map_err(|offset| {
1690 err_ub!(DanglingIntPointer {
1691 addr: offset,
1692 inbounds_size: size,
1693 msg: CheckInAllocMsg::Dereferenceable
1694 })
1695 })
1696 .into()
1697 }
1698}