]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_const_eval/src/interpret/memory.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_const_eval / src / interpret / memory.rs
CommitLineData
b7449926
XL
1//! The memory subsystem.
2//!
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
17df50a5 5//! if the size is 0, then the pointer can also be a (properly aligned, non-null)
9fa01778 6//! integer. It is crucial that these operations call `check_align` *before*
b7449926
XL
7//! short-circuiting the empty case!
8
17df50a5 9use std::assert_matches::assert_matches;
dfeec247 10use std::borrow::Cow;
94b46f34 11use std::collections::VecDeque;
ba9703b0 12use std::fmt;
94b46f34 13use std::ptr;
ff7c6d11 14
3dfed10e 15use rustc_ast::Mutability;
ba9703b0 16use rustc_data_structures::fx::{FxHashMap, FxHashSet};
c295e0f8 17use rustc_middle::mir::display_allocation;
064997fb 18use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TyCtxt};
04454e1e 19use rustc_target::abi::{Align, HasDataLayout, Size};
ff7c6d11 20
9c376795
FG
21use crate::const_eval::CheckAlignment;
22
0bf4aa26 23use super::{
04454e1e 24 alloc_range, AllocId, AllocMap, AllocRange, Allocation, CheckInAllocMsg, GlobalAlloc, InterpCx,
136023e0 25 InterpResult, Machine, MayLeak, Pointer, PointerArithmetic, Provenance, Scalar,
0bf4aa26 26};
ff7c6d11 27
e74abb32 28#[derive(Debug, PartialEq, Copy, Clone)]
ff7c6d11 29pub enum MemoryKind<T> {
60c5eb7d 30 /// Stack memory. Error if deallocated except during a stack pop.
ff7c6d11 31 Stack,
60c5eb7d
XL
32 /// Memory allocated by `caller_location` intrinsic. Error if ever deallocated.
33 CallerLocation,
34 /// Additional memory kinds a machine wishes to distinguish from the builtin ones.
ff7c6d11
XL
35 Machine(T),
36}
37
0bf4aa26
XL
38impl<T: MayLeak> MayLeak for MemoryKind<T> {
39 #[inline]
40 fn may_leak(self) -> bool {
41 match self {
42 MemoryKind::Stack => false,
60c5eb7d 43 MemoryKind::CallerLocation => true,
dfeec247 44 MemoryKind::Machine(k) => k.may_leak(),
0bf4aa26
XL
45 }
46 }
47}
ff7c6d11 48
ba9703b0
XL
49impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match self {
52 MemoryKind::Stack => write!(f, "stack variable"),
ba9703b0
XL
53 MemoryKind::CallerLocation => write!(f, "caller location"),
54 MemoryKind::Machine(m) => write!(f, "{}", m),
55 }
56 }
57}
58
064997fb
FG
59/// The return value of `get_alloc_info` indicates the "kind" of the allocation.
60pub enum AllocKind {
61 /// A regular live data allocation.
62 LiveData,
63 /// A function allocation (that fn ptrs point to).
64 Function,
65 /// A (symbolic) vtable allocation.
66 VTable,
67 /// A dead allocation.
68 Dead,
dc9dc135
XL
69}
70
416331ca
XL
71/// The value of a function pointer.
72#[derive(Debug, Copy, Clone)]
73pub enum FnVal<'tcx, Other> {
74 Instance(Instance<'tcx>),
75 Other(Other),
76}
77
78impl<'tcx, Other> FnVal<'tcx, Other> {
79 pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
80 match self {
dfeec247
XL
81 FnVal::Instance(instance) => Ok(instance),
82 FnVal::Other(_) => {
83 throw_unsup_format!("'foreign' function pointers are not supported in this context")
84 }
416331ca
XL
85 }
86 }
87}
88
0bf4aa26 89// `Memory` has to depend on the `Machine` because some of its operations
0731742a 90// (e.g., `get`) call a `Machine` hook.
dc9dc135 91pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
9fa01778 92 /// Allocations local to this instance of the miri engine. The kind
b7449926 93 /// helps ensure that the same mechanism is used for allocation and
9fa01778 94 /// deallocation. When an allocation is not found here, it is a
ba9703b0
XL
95 /// global and looked up in the `tcx` for read access. Some machines may
96 /// have to mutate this map even on a read-only access to a global (because
0bf4aa26
XL
97 /// they do pointer provenance tracking and the allocations in `tcx` have
98 /// the wrong type), so we let the machine override this type.
ba9703b0
XL
99 /// Either way, if the machine allows writing to a global, doing so will
100 /// create a copy of the global allocation here.
dc9dc135
XL
101 // FIXME: this should not be public, but interning currently needs access to it
102 pub(super) alloc_map: M::MemoryMap,
ff7c6d11 103
416331ca
XL
104 /// Map for "extra" function pointers.
105 extra_fn_ptr_map: FxHashMap<AllocId, M::ExtraFnVal>,
106
17df50a5 107 /// To be able to compare pointers with null, and to check alignment for accesses
b7449926
XL
108 /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
109 /// that do not exist any more.
416331ca 110 // FIXME: this should not be public, but interning currently needs access to it
dc9dc135 111 pub(super) dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
8faf50e0
XL
112}
113
17df50a5
XL
114/// A reference to some allocation that was already bounds-checked for the given region
115/// and had the on-access machine hooks run.
116#[derive(Copy, Clone)]
487cf647 117pub struct AllocRef<'a, 'tcx, Prov: Provenance, Extra> {
064997fb 118 alloc: &'a Allocation<Prov, Extra>,
17df50a5
XL
119 range: AllocRange,
120 tcx: TyCtxt<'tcx>,
121 alloc_id: AllocId,
122}
123/// A reference to some allocation that was already bounds-checked for the given region
124/// and had the on-access machine hooks run.
487cf647 125pub struct AllocRefMut<'a, 'tcx, Prov: Provenance, Extra> {
064997fb 126 alloc: &'a mut Allocation<Prov, Extra>,
17df50a5
XL
127 range: AllocRange,
128 tcx: TyCtxt<'tcx>,
129 alloc_id: AllocId,
130}
131
dc9dc135 132impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
04454e1e 133 pub fn new() -> Self {
0bf4aa26 134 Memory {
a1dfa0c6 135 alloc_map: M::MemoryMap::default(),
416331ca 136 extra_fn_ptr_map: FxHashMap::default(),
b7449926 137 dead_alloc_map: FxHashMap::default(),
ff7c6d11
XL
138 }
139 }
140
04454e1e
FG
141 /// This is used by [priroda](https://github.com/oli-obk/priroda)
142 pub fn alloc_map(&self) -> &M::MemoryMap {
143 &self.alloc_map
144 }
145}
146
147impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
60c5eb7d 148 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
9c376795 149 /// the machine pointer to the allocation. Must never be used
3dfed10e 150 /// for any other pointers, nor for TLS statics.
60c5eb7d 151 ///
3dfed10e
XL
152 /// Using the resulting pointer represents a *direct* access to that memory
153 /// (e.g. by directly using a `static`),
154 /// as opposed to access through a pointer that was created by the program.
155 ///
156 /// This function can fail only if `ptr` points to an `extern static`.
dc9dc135 157 #[inline]
3dfed10e
XL
158 pub fn global_base_pointer(
159 &self,
136023e0 160 ptr: Pointer<AllocId>,
064997fb 161 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
04454e1e 162 let alloc_id = ptr.provenance;
3dfed10e 163 // We need to handle `extern static`.
064997fb 164 match self.tcx.try_get_global_alloc(alloc_id) {
3dfed10e
XL
165 Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
166 bug!("global memory cannot point to thread-local static")
167 }
168 Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
136023e0 169 return M::extern_static_base_pointer(self, def_id);
3dfed10e 170 }
136023e0
XL
171 _ => {}
172 }
064997fb
FG
173 // And we need to get the provenance.
174 Ok(M::adjust_alloc_base_pointer(self, ptr))
ff7c6d11
XL
175 }
176
04454e1e 177 pub fn create_fn_alloc_ptr(
416331ca
XL
178 &mut self,
179 fn_val: FnVal<'tcx, M::ExtraFnVal>,
064997fb 180 ) -> Pointer<M::Provenance> {
416331ca 181 let id = match fn_val {
f9f354fc 182 FnVal::Instance(instance) => self.tcx.create_fn_alloc(instance),
416331ca
XL
183 FnVal::Other(extra) => {
184 // FIXME(RalfJung): Should we have a cache here?
f9f354fc 185 let id = self.tcx.reserve_alloc_id();
04454e1e 186 let old = self.memory.extra_fn_ptr_map.insert(id, extra);
416331ca
XL
187 assert!(old.is_none());
188 id
189 }
190 };
3dfed10e
XL
191 // Functions are global allocations, so make sure we get the right base pointer.
192 // We know this is not an `extern static` so this cannot fail.
193 self.global_base_pointer(Pointer::from(id)).unwrap()
ff7c6d11
XL
194 }
195
04454e1e 196 pub fn allocate_ptr(
ff7c6d11 197 &mut self,
dc9dc135
XL
198 size: Size,
199 align: Align,
ba9703b0 200 kind: MemoryKind<M::MemoryKind>,
064997fb 201 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
136023e0 202 let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?;
923072b8
FG
203 // We can `unwrap` since `alloc` contains no pointers.
204 Ok(self.allocate_raw_ptr(alloc, kind).unwrap())
94b46f34
XL
205 }
206
04454e1e 207 pub fn allocate_bytes_ptr(
94b46f34 208 &mut self,
dc9dc135 209 bytes: &[u8],
17df50a5 210 align: Align,
ba9703b0 211 kind: MemoryKind<M::MemoryKind>,
17df50a5 212 mutability: Mutability,
064997fb 213 ) -> Pointer<M::Provenance> {
17df50a5 214 let alloc = Allocation::from_bytes(bytes, align, mutability);
923072b8
FG
215 // We can `unwrap` since `alloc` contains no pointers.
216 self.allocate_raw_ptr(alloc, kind).unwrap()
dc9dc135
XL
217 }
218
f2b60f7d 219 /// This can fail only of `alloc` contains provenance.
04454e1e 220 pub fn allocate_raw_ptr(
dc9dc135
XL
221 &mut self,
222 alloc: Allocation,
ba9703b0 223 kind: MemoryKind<M::MemoryKind>,
064997fb 224 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
f9f354fc 225 let id = self.tcx.reserve_alloc_id();
dfeec247
XL
226 debug_assert_ne!(
227 Some(kind),
ba9703b0
XL
228 M::GLOBAL_KIND.map(MemoryKind::Machine),
229 "dynamically allocating global memory"
dfeec247 230 );
064997fb 231 let alloc = M::adjust_allocation(self, id, Cow::Owned(alloc), Some(kind))?;
04454e1e 232 self.memory.alloc_map.insert(id, (kind, alloc.into_owned()));
064997fb 233 Ok(M::adjust_alloc_base_pointer(self, Pointer::from(id)))
ff7c6d11
XL
234 }
235
04454e1e 236 pub fn reallocate_ptr(
ff7c6d11 237 &mut self,
064997fb 238 ptr: Pointer<Option<M::Provenance>>,
416331ca 239 old_size_and_align: Option<(Size, Align)>,
94b46f34 240 new_size: Size,
ff7c6d11 241 new_align: Align,
ba9703b0 242 kind: MemoryKind<M::MemoryKind>,
064997fb
FG
243 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
244 let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr)?;
136023e0 245 if offset.bytes() != 0 {
ba9703b0
XL
246 throw_ub_format!(
247 "reallocating {:?} which does not point to the beginning of an object",
248 ptr
249 );
ff7c6d11 250 }
ff7c6d11 251
a1dfa0c6
XL
252 // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
253 // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
04454e1e 254 let new_ptr = self.allocate_ptr(new_size, new_align, kind)?;
416331ca
XL
255 let old_size = match old_size_and_align {
256 Some((size, _align)) => size,
04454e1e 257 None => self.get_alloc_raw(alloc_id)?.size(),
416331ca 258 };
17df50a5 259 // This will also call the access hooks.
04454e1e
FG
260 self.mem_copy(
261 ptr,
17df50a5
XL
262 Align::ONE,
263 new_ptr.into(),
264 Align::ONE,
265 old_size.min(new_size),
266 /*nonoverlapping*/ true,
267 )?;
04454e1e 268 self.deallocate_ptr(ptr, old_size_and_align, kind)?;
ff7c6d11
XL
269
270 Ok(new_ptr)
271 }
272
5e7ed085 273 #[instrument(skip(self), level = "debug")]
04454e1e 274 pub fn deallocate_ptr(
ff7c6d11 275 &mut self,
064997fb 276 ptr: Pointer<Option<M::Provenance>>,
416331ca 277 old_size_and_align: Option<(Size, Align)>,
ba9703b0 278 kind: MemoryKind<M::MemoryKind>,
dc9dc135 279 ) -> InterpResult<'tcx> {
064997fb
FG
280 let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr)?;
281 trace!("deallocating: {alloc_id:?}");
b7449926 282
136023e0 283 if offset.bytes() != 0 {
ba9703b0
XL
284 throw_ub_format!(
285 "deallocating {:?} which does not point to the beginning of an object",
286 ptr
287 );
ff7c6d11
XL
288 }
289
04454e1e 290 let Some((alloc_kind, mut alloc)) = self.memory.alloc_map.remove(&alloc_id) else {
5e7ed085 291 // Deallocating global memory -- always an error
064997fb 292 return Err(match self.tcx.try_get_global_alloc(alloc_id) {
5e7ed085 293 Some(GlobalAlloc::Function(..)) => {
064997fb
FG
294 err_ub_format!("deallocating {alloc_id:?}, which is a function")
295 }
296 Some(GlobalAlloc::VTable(..)) => {
297 err_ub_format!("deallocating {alloc_id:?}, which is a vtable")
5e7ed085
FG
298 }
299 Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
064997fb 300 err_ub_format!("deallocating {alloc_id:?}, which is static memory")
94b46f34 301 }
5e7ed085 302 None => err_ub!(PointerUseAfterFree(alloc_id)),
94b46f34 303 }
5e7ed085 304 .into());
ff7c6d11
XL
305 };
306
17df50a5 307 if alloc.mutability == Mutability::Not {
064997fb 308 throw_ub_format!("deallocating immutable allocation {alloc_id:?}");
17df50a5 309 }
ff7c6d11 310 if alloc_kind != kind {
ba9703b0 311 throw_ub_format!(
064997fb 312 "deallocating {alloc_id:?}, which is {alloc_kind} memory, using {kind} deallocation operation"
ba9703b0 313 );
ff7c6d11 314 }
416331ca 315 if let Some((size, align)) = old_size_and_align {
17df50a5 316 if size != alloc.size() || align != alloc.align {
ba9703b0 317 throw_ub_format!(
064997fb 318 "incorrect layout on deallocation: {alloc_id:?} has size {} and alignment {}, but gave size {} and alignment {}",
17df50a5 319 alloc.size().bytes(),
ba9703b0
XL
320 alloc.align.bytes(),
321 size.bytes(),
322 align.bytes(),
323 )
ff7c6d11
XL
324 }
325 }
326
0bf4aa26 327 // Let the machine take some extra action
17df50a5 328 let size = alloc.size();
f2b60f7d 329 M::before_memory_deallocation(
04454e1e
FG
330 *self.tcx,
331 &mut self.machine,
136023e0 332 &mut alloc.extra,
064997fb 333 (alloc_id, prov),
136023e0
XL
334 alloc_range(Size::ZERO, size),
335 )?;
0bf4aa26 336
b7449926 337 // Don't forget to remember size and align of this now-dead allocation
04454e1e 338 let old = self.memory.dead_alloc_map.insert(alloc_id, (size, alloc.align));
b7449926
XL
339 if old.is_some() {
340 bug!("Nothing can be deallocated twice");
341 }
ff7c6d11
XL
342
343 Ok(())
344 }
345
136023e0 346 /// Internal helper function to determine the allocation and offset of a pointer (if any).
416331ca 347 #[inline(always)]
136023e0 348 fn get_ptr_access(
0bf4aa26 349 &self,
064997fb 350 ptr: Pointer<Option<M::Provenance>>,
dc9dc135
XL
351 size: Size,
352 align: Align,
064997fb 353 ) -> InterpResult<'tcx, Option<(AllocId, Size, M::ProvenanceExtra)>> {
136023e0
XL
354 self.check_and_deref_ptr(
355 ptr,
356 size,
357 align,
9c376795 358 M::enforce_alignment(self),
136023e0 359 CheckInAllocMsg::MemoryAccessTest,
064997fb
FG
360 |alloc_id, offset, prov| {
361 let (size, align) = self.get_live_alloc_size_and_align(alloc_id)?;
362 Ok((size, align, (alloc_id, offset, prov)))
136023e0
XL
363 },
364 )
416331ca
XL
365 }
366
136023e0 367 /// Check if the given pointer points to live memory of given `size` and `align`
17df50a5
XL
368 /// (ignoring `M::enforce_alignment`). The caller can control the error message for the
369 /// out-of-bounds case.
370 #[inline(always)]
60c5eb7d 371 pub fn check_ptr_access_align(
17df50a5 372 &self,
064997fb 373 ptr: Pointer<Option<M::Provenance>>,
17df50a5
XL
374 size: Size,
375 align: Align,
376 msg: CheckInAllocMsg,
377 ) -> InterpResult<'tcx> {
9c376795
FG
378 self.check_and_deref_ptr(
379 ptr,
380 size,
381 align,
382 CheckAlignment::Error,
383 msg,
384 |alloc_id, _, _| {
385 let (size, align) = self.get_live_alloc_size_and_align(alloc_id)?;
386 Ok((size, align, ()))
387 },
388 )?;
17df50a5
XL
389 Ok(())
390 }
391
392 /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference
136023e0 393 /// to the allocation it points to. Supports both shared and mutable references, as the actual
17df50a5
XL
394 /// checking is offloaded to a helper closure. `align` defines whether and which alignment check
395 /// is done. Returns `None` for size 0, and otherwise `Some` of what `alloc_size` returned.
396 fn check_and_deref_ptr<T>(
416331ca 397 &self,
064997fb 398 ptr: Pointer<Option<M::Provenance>>,
416331ca 399 size: Size,
9c376795
FG
400 align: Align,
401 check: CheckAlignment,
60c5eb7d 402 msg: CheckInAllocMsg,
064997fb
FG
403 alloc_size: impl FnOnce(
404 AllocId,
405 Size,
406 M::ProvenanceExtra,
407 ) -> InterpResult<'tcx, (Size, Align, T)>,
17df50a5 408 ) -> InterpResult<'tcx, Option<T>> {
04454e1e 409 Ok(match self.ptr_try_get_alloc_id(ptr) {
136023e0 410 Err(addr) => {
5e7ed085
FG
411 // We couldn't get a proper allocation. This is only okay if the access size is 0,
412 // and the address is not null.
413 if size.bytes() > 0 || addr == 0 {
414 throw_ub!(DanglingIntPointer(addr, msg));
416331ca
XL
415 }
416 // Must be aligned.
9c376795
FG
417 if check.should_check() {
418 self.check_offset_align(addr, align, check)?;
ff7c6d11 419 }
dc9dc135 420 None
ff7c6d11 421 }
064997fb
FG
422 Ok((alloc_id, offset, prov)) => {
423 let (alloc_size, alloc_align, ret_val) = alloc_size(alloc_id, offset, prov)?;
17df50a5 424 // Test bounds. This also ensures non-null.
136023e0
XL
425 // It is sufficient to check this for the end pointer. Also check for overflow!
426 if offset.checked_add(size, &self.tcx).map_or(true, |end| end > alloc_size) {
427 throw_ub!(PointerOutOfBounds {
428 alloc_id,
429 alloc_size,
430 ptr_offset: self.machine_usize_to_isize(offset.bytes()),
431 ptr_size: size,
432 msg,
433 })
ba9703b0 434 }
f2b60f7d 435 // Ensure we never consider the null pointer dereferenceable.
064997fb 436 if M::Provenance::OFFSET_IS_ADDR {
923072b8
FG
437 assert_ne!(ptr.addr(), Size::ZERO);
438 }
dc9dc135
XL
439 // Test align. Check this last; if both bounds and alignment are violated
440 // we want the error to be about the bounds.
9c376795 441 if check.should_check() {
f2b60f7d
FG
442 if M::use_addr_for_alignment_check(self) {
443 // `use_addr_for_alignment_check` can only be true if `OFFSET_IS_ADDR` is true.
9c376795 444 self.check_offset_align(ptr.addr().bytes(), align, check)?;
3dfed10e
XL
445 } else {
446 // Check allocation alignment and offset alignment.
447 if alloc_align.bytes() < align.bytes() {
9c376795 448 M::alignment_check_failed(self, alloc_align, align, check)?;
3dfed10e 449 }
9c376795 450 self.check_offset_align(offset.bytes(), align, check)?;
416331ca 451 }
dc9dc135 452 }
dc9dc135
XL
453
454 // We can still be zero-sized in this branch, in which case we have to
455 // return `None`.
17df50a5 456 if size.bytes() == 0 { None } else { Some(ret_val) }
dc9dc135
XL
457 }
458 })
ff7c6d11 459 }
9c376795
FG
460
461 fn check_offset_align(
462 &self,
463 offset: u64,
464 align: Align,
465 check: CheckAlignment,
466 ) -> InterpResult<'tcx> {
467 if offset % align.bytes() == 0 {
468 Ok(())
469 } else {
470 // The biggest power of two through which `offset` is divisible.
471 let offset_pow2 = 1 << offset.trailing_zeros();
472 M::alignment_check_failed(self, Align::from_bytes(offset_pow2).unwrap(), align, check)
473 }
474 }
ff7c6d11
XL
475}
476
477/// Allocation accessors
04454e1e 478impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
ba9703b0 479 /// Helper function to obtain a global (tcx) allocation.
0bf4aa26
XL
480 /// This attempts to return a reference to an existing allocation if
481 /// one can be found in `tcx`. That, however, is only possible if `tcx` and
064997fb
FG
482 /// this machine use the same pointer provenance, so it is indirected through
483 /// `M::adjust_allocation`.
ba9703b0 484 fn get_global_alloc(
136023e0 485 &self,
416331ca 486 id: AllocId,
ba9703b0 487 is_write: bool,
064997fb
FG
488 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::Provenance, M::AllocExtra>>> {
489 let (alloc, def_id) = match self.tcx.try_get_global_alloc(id) {
ba9703b0
XL
490 Some(GlobalAlloc::Memory(mem)) => {
491 // Memory of a constant or promoted or anonymous memory referenced by a static.
492 (mem, None)
493 }
494 Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)),
064997fb 495 Some(GlobalAlloc::VTable(..)) => throw_ub!(DerefVTablePointer(id)),
ba9703b0 496 None => throw_ub!(PointerUseAfterFree(id)),
dc9dc135 497 Some(GlobalAlloc::Static(def_id)) => {
136023e0
XL
498 assert!(self.tcx.is_static(def_id));
499 assert!(!self.tcx.is_thread_local_static(def_id));
ba9703b0
XL
500 // Notice that every static has two `AllocId` that will resolve to the same
501 // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
502 // and the other one is maps to `GlobalAlloc::Memory`, this is returned by
1b1a35ee 503 // `eval_static_initializer` and it is the "resolved" ID.
f9f354fc
XL
504 // The resolved ID is never used by the interpreted program, it is hidden.
505 // This is relied upon for soundness of const-patterns; a pointer to the resolved
506 // ID would "sidestep" the checks that make sure consts do not point to statics!
ba9703b0
XL
507 // The `GlobalAlloc::Memory` branch here is still reachable though; when a static
508 // contains a reference to memory that was created during its evaluation (i.e., not
509 // to another static), those inner references only exist in "resolved" form.
136023e0 510 if self.tcx.is_foreign_item(def_id) {
064997fb
FG
511 // This is unreachable in Miri, but can happen in CTFE where we actually *do* support
512 // referencing arbitrary (declared) extern statics.
3dfed10e 513 throw_unsup!(ReadExternStatic(def_id));
dc9dc135 514 }
3dfed10e 515
487cf647
FG
516 // We don't give a span -- statics don't need that, they cannot be generic or associated.
517 let val = self.ctfe_query(None, |tcx| tcx.eval_static_initializer(def_id))?;
518 (val, Some(def_id))
b7449926 519 }
dc9dc135 520 };
04454e1e 521 M::before_access_global(*self.tcx, &self.machine, id, alloc, def_id, is_write)?;
60c5eb7d 522 // We got tcx memory. Let the machine initialize its "extra" stuff.
064997fb 523 M::adjust_allocation(
136023e0 524 self,
dc9dc135 525 id, // always use the ID we got as input, not the "hidden" one.
5e7ed085 526 Cow::Borrowed(alloc.inner()),
ba9703b0 527 M::GLOBAL_KIND.map(MemoryKind::Machine),
923072b8 528 )
94b46f34
XL
529 }
530
60c5eb7d 531 /// Gives raw access to the `Allocation`, without bounds or alignment checks.
17df50a5 532 /// The caller is responsible for calling the access hooks!
f2b60f7d
FG
533 ///
534 /// You almost certainly want to use `get_ptr_alloc`/`get_ptr_alloc_mut` instead.
04454e1e 535 fn get_alloc_raw(
dc9dc135
XL
536 &self,
537 id: AllocId,
064997fb 538 ) -> InterpResult<'tcx, &Allocation<M::Provenance, M::AllocExtra>> {
9c376795 539 // The error type of the inner closure here is somewhat funny. We have two
0bf4aa26 540 // ways of "erroring": An actual error, or because we got a reference from
ba9703b0 541 // `get_global_alloc` that we can actually use directly without inserting anything anywhere.
064997fb 542 // So the error type is `InterpResult<'tcx, &Allocation<M::Provenance>>`.
04454e1e 543 let a = self.memory.alloc_map.get_or(id, || {
136023e0 544 let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?;
0bf4aa26
XL
545 match alloc {
546 Cow::Borrowed(alloc) => {
547 // We got a ref, cheaply return that as an "error" so that the
548 // map does not get mutated.
549 Err(Ok(alloc))
550 }
551 Cow::Owned(alloc) => {
552 // Need to put it into the map and return a ref to that
ba9703b0
XL
553 let kind = M::GLOBAL_KIND.expect(
554 "I got a global allocation that I have to copy but the machine does \
dfeec247 555 not expect that to happen",
0bf4aa26
XL
556 );
557 Ok((MemoryKind::Machine(kind), alloc))
558 }
b7449926 559 }
0bf4aa26
XL
560 });
561 // Now unpack that funny error type
562 match a {
563 Ok(a) => Ok(&a.1),
dfeec247 564 Err(a) => a,
0bf4aa26 565 }
ff7c6d11
XL
566 }
567
17df50a5 568 /// "Safe" (bounds and align-checked) allocation access.
04454e1e 569 pub fn get_ptr_alloc<'a>(
17df50a5 570 &'a self,
064997fb 571 ptr: Pointer<Option<M::Provenance>>,
17df50a5
XL
572 size: Size,
573 align: Align,
064997fb 574 ) -> InterpResult<'tcx, Option<AllocRef<'a, 'tcx, M::Provenance, M::AllocExtra>>> {
17df50a5 575 let ptr_and_alloc = self.check_and_deref_ptr(
136023e0 576 ptr,
17df50a5
XL
577 size,
578 align,
9c376795 579 M::enforce_alignment(self),
17df50a5 580 CheckInAllocMsg::MemoryAccessTest,
064997fb 581 |alloc_id, offset, prov| {
04454e1e 582 let alloc = self.get_alloc_raw(alloc_id)?;
064997fb 583 Ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc)))
17df50a5
XL
584 },
585 )?;
064997fb 586 if let Some((alloc_id, offset, prov, alloc)) = ptr_and_alloc {
136023e0 587 let range = alloc_range(offset, size);
f2b60f7d 588 M::before_memory_read(*self.tcx, &self.machine, &alloc.extra, (alloc_id, prov), range)?;
04454e1e 589 Ok(Some(AllocRef { alloc, range, tcx: *self.tcx, alloc_id }))
17df50a5
XL
590 } else {
591 // Even in this branch we have to be sure that we actually access the allocation, in
592 // order to ensure that `static FOO: Type = FOO;` causes a cycle error instead of
593 // magically pulling *any* ZST value from the ether. However, the `get_raw` above is
136023e0 594 // always called when `ptr` has an `AllocId`.
17df50a5
XL
595 Ok(None)
596 }
597 }
598
599 /// Return the `extra` field of the given allocation.
600 pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> {
04454e1e 601 Ok(&self.get_alloc_raw(id)?.extra)
17df50a5
XL
602 }
603
f2b60f7d
FG
604 /// Return the `mutability` field of the given allocation.
605 pub fn get_alloc_mutability<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, Mutability> {
606 Ok(self.get_alloc_raw(id)?.mutability)
607 }
608
60c5eb7d 609 /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
17df50a5
XL
610 /// The caller is responsible for calling the access hooks!
611 ///
612 /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the
613 /// allocation.
04454e1e 614 fn get_alloc_raw_mut(
ff7c6d11
XL
615 &mut self,
616 id: AllocId,
064997fb 617 ) -> InterpResult<'tcx, (&mut Allocation<M::Provenance, M::AllocExtra>, &mut M)> {
136023e0
XL
618 // We have "NLL problem case #3" here, which cannot be worked around without loss of
619 // efficiency even for the common case where the key is in the map.
620 // <https://rust-lang.github.io/rfcs/2094-nll.html#problem-case-3-conditional-control-flow-across-functions>
621 // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`.)
04454e1e 622 if self.memory.alloc_map.get_mut(id).is_none() {
136023e0
XL
623 // Slow path.
624 // Allocation not found locally, go look global.
625 let alloc = self.get_global_alloc(id, /*is_write*/ true)?;
ba9703b0
XL
626 let kind = M::GLOBAL_KIND.expect(
627 "I got a global allocation that I have to copy but the machine does \
628 not expect that to happen",
629 );
04454e1e 630 self.memory.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned()));
136023e0
XL
631 }
632
04454e1e 633 let (_kind, alloc) = self.memory.alloc_map.get_mut(id).unwrap();
136023e0
XL
634 if alloc.mutability == Mutability::Not {
635 throw_ub!(WriteToReadOnly(id))
b7449926 636 }
04454e1e 637 Ok((alloc, &mut self.machine))
0bf4aa26
XL
638 }
639
17df50a5 640 /// "Safe" (bounds and align-checked) allocation access.
04454e1e 641 pub fn get_ptr_alloc_mut<'a>(
17df50a5 642 &'a mut self,
064997fb 643 ptr: Pointer<Option<M::Provenance>>,
17df50a5
XL
644 size: Size,
645 align: Align,
064997fb 646 ) -> InterpResult<'tcx, Option<AllocRefMut<'a, 'tcx, M::Provenance, M::AllocExtra>>> {
136023e0 647 let parts = self.get_ptr_access(ptr, size, align)?;
064997fb 648 if let Some((alloc_id, offset, prov)) = parts {
04454e1e 649 let tcx = *self.tcx;
17df50a5
XL
650 // FIXME: can we somehow avoid looking up the allocation twice here?
651 // We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`.
04454e1e 652 let (alloc, machine) = self.get_alloc_raw_mut(alloc_id)?;
136023e0 653 let range = alloc_range(offset, size);
f2b60f7d 654 M::before_memory_write(tcx, machine, &mut alloc.extra, (alloc_id, prov), range)?;
136023e0 655 Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id }))
17df50a5
XL
656 } else {
657 Ok(None)
658 }
659 }
660
661 /// Return the `extra` field of the given allocation.
662 pub fn get_alloc_extra_mut<'a>(
663 &'a mut self,
664 id: AllocId,
04454e1e
FG
665 ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M)> {
666 let (alloc, machine) = self.get_alloc_raw_mut(id)?;
667 Ok((&mut alloc.extra, machine))
17df50a5
XL
668 }
669
dc9dc135
XL
670 /// Obtain the size and alignment of an allocation, even if that allocation has
671 /// been deallocated.
064997fb 672 pub fn get_alloc_info(&self, id: AllocId) -> (Size, Align, AllocKind) {
dc9dc135 673 // # Regular allocations
60c5eb7d 674 // Don't use `self.get_raw` here as that will
dc9dc135 675 // a) cause cycles in case `id` refers to a static
ba9703b0 676 // b) duplicate a global's allocation in miri
04454e1e 677 if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
064997fb 678 return (alloc.size(), alloc.align, AllocKind::LiveData);
0bf4aa26 679 }
dc9dc135 680
416331ca
XL
681 // # Function pointers
682 // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
74b04a01 683 if self.get_fn_alloc(id).is_some() {
064997fb 684 return (Size::ZERO, Align::ONE, AllocKind::Function);
416331ca
XL
685 }
686
687 // # Statics
dc9dc135
XL
688 // Can't do this in the match argument, we may get cycle errors since the lock would
689 // be held throughout the match.
064997fb
FG
690 match self.tcx.try_get_global_alloc(id) {
691 Some(GlobalAlloc::Static(def_id)) => {
692 assert!(self.tcx.is_static(def_id));
693 assert!(!self.tcx.is_thread_local_static(def_id));
dc9dc135 694 // Use size and align of the type.
064997fb 695 let ty = self.tcx.type_of(def_id);
0bf4aa26 696 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
487cf647 697 assert!(layout.is_sized());
064997fb 698 (layout.size, layout.align.abi, AllocKind::LiveData)
dfeec247
XL
699 }
700 Some(GlobalAlloc::Memory(alloc)) => {
dc9dc135
XL
701 // Need to duplicate the logic here, because the global allocations have
702 // different associated types than the interpreter-local ones.
5e7ed085 703 let alloc = alloc.inner();
064997fb 704 (alloc.size(), alloc.align, AllocKind::LiveData)
dfeec247
XL
705 }
706 Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"),
064997fb
FG
707 Some(GlobalAlloc::VTable(..)) => {
708 // No data to be accessed here. But vtables are pointer-aligned.
709 return (Size::ZERO, self.tcx.data_layout.pointer_align.abi, AllocKind::VTable);
710 }
dc9dc135 711 // The rest must be dead.
dfeec247 712 None => {
064997fb
FG
713 // Deallocated pointers are allowed, we should be able to find
714 // them in the map.
715 let (size, align) = *self
716 .memory
717 .dead_alloc_map
718 .get(&id)
719 .expect("deallocated pointers should all be recorded in `dead_alloc_map`");
720 (size, align, AllocKind::Dead)
dfeec247 721 }
ff7c6d11
XL
722 }
723 }
724
064997fb
FG
725 /// Obtain the size and alignment of a live allocation.
726 pub fn get_live_alloc_size_and_align(&self, id: AllocId) -> InterpResult<'tcx, (Size, Align)> {
727 let (size, align, kind) = self.get_alloc_info(id);
728 if matches!(kind, AllocKind::Dead) {
729 throw_ub!(PointerUseAfterFree(id))
730 }
731 Ok((size, align))
732 }
733
74b04a01 734 fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
04454e1e 735 if let Some(extra) = self.memory.extra_fn_ptr_map.get(&id) {
74b04a01 736 Some(FnVal::Other(*extra))
416331ca 737 } else {
064997fb 738 match self.tcx.try_get_global_alloc(id) {
74b04a01
XL
739 Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)),
740 _ => None,
416331ca 741 }
ff7c6d11 742 }
416331ca
XL
743 }
744
04454e1e 745 pub fn get_ptr_fn(
416331ca 746 &self,
064997fb 747 ptr: Pointer<Option<M::Provenance>>,
416331ca 748 ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
064997fb
FG
749 trace!("get_ptr_fn({:?})", ptr);
750 let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr)?;
136023e0
XL
751 if offset.bytes() != 0 {
752 throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset)))
94b46f34 753 }
136023e0
XL
754 self.get_fn_alloc(alloc_id)
755 .ok_or_else(|| err_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))).into())
ff7c6d11
XL
756 }
757
064997fb
FG
758 pub fn get_ptr_vtable(
759 &self,
760 ptr: Pointer<Option<M::Provenance>>,
761 ) -> InterpResult<'tcx, (Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>)> {
762 trace!("get_ptr_vtable({:?})", ptr);
763 let (alloc_id, offset, _tag) = self.ptr_get_alloc_id(ptr)?;
764 if offset.bytes() != 0 {
765 throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset)))
766 }
767 match self.tcx.try_get_global_alloc(alloc_id) {
768 Some(GlobalAlloc::VTable(ty, trait_ref)) => Ok((ty, trait_ref)),
769 _ => throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset))),
770 }
771 }
772
04454e1e
FG
773 pub fn alloc_mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
774 self.get_alloc_raw_mut(id)?.0.mutability = Mutability::Not;
0bf4aa26
XL
775 Ok(())
776 }
777
3dfed10e
XL
778 /// Create a lazy debug printer that prints the given allocation and all allocations it points
779 /// to, recursively.
780 #[must_use]
781 pub fn dump_alloc<'a>(&'a self, id: AllocId) -> DumpAllocs<'a, 'mir, 'tcx, M> {
782 self.dump_allocs(vec![id])
783 }
784
785 /// Create a lazy debug printer for a list of allocations and all allocations they point to,
786 /// recursively.
787 #[must_use]
788 pub fn dump_allocs<'a>(&'a self, mut allocs: Vec<AllocId>) -> DumpAllocs<'a, 'mir, 'tcx, M> {
789 allocs.sort();
790 allocs.dedup();
04454e1e 791 DumpAllocs { ecx: self, allocs }
3dfed10e
XL
792 }
793
794 /// Print leaked memory. Allocations reachable from `static_roots` or a `Global` allocation
795 /// are not considered leaked. Leaks whose kind `may_leak()` returns true are not reported.
796 pub fn leak_report(&self, static_roots: &[AllocId]) -> usize {
797 // Collect the set of allocations that are *reachable* from `Global` allocations.
798 let reachable = {
799 let mut reachable = FxHashSet::default();
800 let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
04454e1e
FG
801 let mut todo: Vec<_> =
802 self.memory.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
803 if Some(kind) == global_kind { Some(id) } else { None }
804 });
3dfed10e
XL
805 todo.extend(static_roots);
806 while let Some(id) = todo.pop() {
807 if reachable.insert(id) {
2b03887a 808 // This is a new allocation, add the allocation it points to `todo`.
04454e1e
FG
809 if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
810 todo.extend(
487cf647 811 alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id()),
04454e1e 812 );
3dfed10e
XL
813 }
814 }
815 }
816 reachable
817 };
818
819 // All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking.
04454e1e 820 let leaks: Vec<_> = self.memory.alloc_map.filter_map_collect(|&id, &(kind, _)| {
3dfed10e
XL
821 if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
822 });
823 let n = leaks.len();
824 if n > 0 {
825 eprintln!("The following memory was leaked: {:?}", self.dump_allocs(leaks));
826 }
827 n
ff7c6d11 828 }
3dfed10e
XL
829}
830
831#[doc(hidden)]
832/// There's no way to use this directly, it's just a helper struct for the `dump_alloc(s)` methods.
833pub struct DumpAllocs<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
04454e1e 834 ecx: &'a InterpCx<'mir, 'tcx, M>,
3dfed10e
XL
835 allocs: Vec<AllocId>,
836}
837
838impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a, 'mir, 'tcx, M> {
839 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
064997fb
FG
840 // Cannot be a closure because it is generic in `Prov`, `Extra`.
841 fn write_allocation_track_relocs<'tcx, Prov: Provenance, Extra>(
3dfed10e 842 fmt: &mut std::fmt::Formatter<'_>,
f035d41b 843 tcx: TyCtxt<'tcx>,
ba9703b0 844 allocs_to_print: &mut VecDeque<AllocId>,
064997fb 845 alloc: &Allocation<Prov, Extra>,
3dfed10e 846 ) -> std::fmt::Result {
487cf647
FG
847 for alloc_id in alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id())
848 {
136023e0 849 allocs_to_print.push_back(alloc_id);
ba9703b0 850 }
c295e0f8 851 write!(fmt, "{}", display_allocation(tcx, alloc))
ba9703b0
XL
852 }
853
3dfed10e 854 let mut allocs_to_print: VecDeque<_> = self.allocs.iter().copied().collect();
ba9703b0
XL
855 // `allocs_printed` contains all allocations that we have already printed.
856 let mut allocs_printed = FxHashSet::default();
ff7c6d11
XL
857
858 while let Some(id) = allocs_to_print.pop_front() {
ba9703b0
XL
859 if !allocs_printed.insert(id) {
860 // Already printed, so skip this.
861 continue;
862 }
863
064997fb 864 write!(fmt, "{id:?}")?;
04454e1e 865 match self.ecx.memory.alloc_map.get(id) {
9c376795 866 Some((kind, alloc)) => {
ba9703b0 867 // normal alloc
3dfed10e
XL
868 write!(fmt, " ({}, ", kind)?;
869 write_allocation_track_relocs(
870 &mut *fmt,
04454e1e 871 *self.ecx.tcx,
3dfed10e
XL
872 &mut allocs_to_print,
873 alloc,
874 )?;
dfeec247 875 }
ba9703b0
XL
876 None => {
877 // global alloc
064997fb 878 match self.ecx.tcx.try_get_global_alloc(id) {
dc9dc135 879 Some(GlobalAlloc::Memory(alloc)) => {
3dfed10e
XL
880 write!(fmt, " (unchanged global, ")?;
881 write_allocation_track_relocs(
882 &mut *fmt,
04454e1e 883 *self.ecx.tcx,
3dfed10e 884 &mut allocs_to_print,
5e7ed085 885 alloc.inner(),
3dfed10e 886 )?;
0bf4aa26 887 }
dc9dc135 888 Some(GlobalAlloc::Function(func)) => {
064997fb
FG
889 write!(fmt, " (fn: {func})")?;
890 }
891 Some(GlobalAlloc::VTable(ty, Some(trait_ref))) => {
892 write!(fmt, " (vtable: impl {trait_ref} for {ty})")?;
893 }
894 Some(GlobalAlloc::VTable(ty, None)) => {
895 write!(fmt, " (vtable: impl <auto trait> for {ty})")?;
0bf4aa26 896 }
dc9dc135 897 Some(GlobalAlloc::Static(did)) => {
04454e1e 898 write!(fmt, " (static: {})", self.ecx.tcx.def_path_str(did))?;
0bf4aa26
XL
899 }
900 None => {
3dfed10e 901 write!(fmt, " (deallocated)")?;
8faf50e0 902 }
ff7c6d11 903 }
dfeec247 904 }
ba9703b0 905 }
3dfed10e 906 writeln!(fmt)?;
ff7c6d11 907 }
3dfed10e 908 Ok(())
0bf4aa26 909 }
ff7c6d11
XL
910}
911
dc9dc135 912/// Reading and writing.
064997fb
FG
913impl<'tcx, 'a, Prov: Provenance, Extra> AllocRefMut<'a, 'tcx, Prov, Extra> {
914 /// `range` is relative to this allocation reference, not the base of the allocation.
f2b60f7d 915 pub fn write_scalar(&mut self, range: AllocRange, val: Scalar<Prov>) -> InterpResult<'tcx> {
04454e1e 916 let range = self.range.subrange(range);
064997fb 917 debug!("write_scalar at {:?}{range:?}: {val:?}", self.alloc_id);
17df50a5
XL
918 Ok(self
919 .alloc
04454e1e 920 .write_scalar(&self.tcx, range, val)
17df50a5 921 .map_err(|e| e.to_interp_error(self.alloc_id))?)
ff7c6d11
XL
922 }
923
064997fb 924 /// `offset` is relative to this allocation reference, not the base of the allocation.
f2b60f7d 925 pub fn write_ptr_sized(&mut self, offset: Size, val: Scalar<Prov>) -> InterpResult<'tcx> {
17df50a5 926 self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val)
416331ca 927 }
04454e1e 928
f2b60f7d 929 /// Mark the entire referenced range as uninitialized
04454e1e
FG
930 pub fn write_uninit(&mut self) -> InterpResult<'tcx> {
931 Ok(self
932 .alloc
933 .write_uninit(&self.tcx, self.range)
934 .map_err(|e| e.to_interp_error(self.alloc_id))?)
935 }
17df50a5 936}
416331ca 937
064997fb
FG
938impl<'tcx, 'a, Prov: Provenance, Extra> AllocRef<'a, 'tcx, Prov, Extra> {
939 /// `range` is relative to this allocation reference, not the base of the allocation.
923072b8
FG
940 pub fn read_scalar(
941 &self,
942 range: AllocRange,
943 read_provenance: bool,
f2b60f7d 944 ) -> InterpResult<'tcx, Scalar<Prov>> {
04454e1e
FG
945 let range = self.range.subrange(range);
946 let res = self
17df50a5 947 .alloc
923072b8 948 .read_scalar(&self.tcx, range, read_provenance)
04454e1e 949 .map_err(|e| e.to_interp_error(self.alloc_id))?;
064997fb 950 debug!("read_scalar at {:?}{range:?}: {res:?}", self.alloc_id);
04454e1e 951 Ok(res)
74b04a01
XL
952 }
953
064997fb 954 /// `range` is relative to this allocation reference, not the base of the allocation.
f2b60f7d 955 pub fn read_integer(&self, range: AllocRange) -> InterpResult<'tcx, Scalar<Prov>> {
064997fb 956 self.read_scalar(range, /*read_provenance*/ false)
923072b8
FG
957 }
958
064997fb 959 /// `offset` is relative to this allocation reference, not the base of the allocation.
f2b60f7d 960 pub fn read_pointer(&self, offset: Size) -> InterpResult<'tcx, Scalar<Prov>> {
923072b8
FG
961 self.read_scalar(
962 alloc_range(offset, self.tcx.data_layout().pointer_size),
963 /*read_provenance*/ true,
964 )
17df50a5
XL
965 }
966
064997fb 967 /// `range` is relative to this allocation reference, not the base of the allocation.
f2b60f7d 968 pub fn get_bytes_strip_provenance<'b>(&'b self) -> InterpResult<'tcx, &'a [u8]> {
17df50a5
XL
969 Ok(self
970 .alloc
f2b60f7d 971 .get_bytes_strip_provenance(&self.tcx, self.range)
17df50a5
XL
972 .map_err(|e| e.to_interp_error(self.alloc_id))?)
973 }
064997fb 974
f2b60f7d
FG
975 /// Returns whether the allocation has provenance anywhere in the range of the `AllocRef`.
976 pub(crate) fn has_provenance(&self) -> bool {
487cf647 977 !self.alloc.provenance().range_empty(self.range, &self.tcx)
064997fb 978 }
17df50a5
XL
979}
980
04454e1e 981impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
f2b60f7d
FG
982 /// Reads the given number of bytes from memory, and strips their provenance if possible.
983 /// Returns them as a slice.
e74abb32
XL
984 ///
985 /// Performs appropriate bounds checks.
f2b60f7d 986 pub fn read_bytes_ptr_strip_provenance(
136023e0 987 &self,
064997fb 988 ptr: Pointer<Option<M::Provenance>>,
136023e0
XL
989 size: Size,
990 ) -> InterpResult<'tcx, &[u8]> {
04454e1e 991 let Some(alloc_ref) = self.get_ptr_alloc(ptr, size, Align::ONE)? else {
5e7ed085
FG
992 // zero-sized access
993 return Ok(&[]);
e74abb32 994 };
17df50a5
XL
995 // Side-step AllocRef and directly access the underlying bytes more efficiently.
996 // (We are staying inside the bounds here so all is good.)
997 Ok(alloc_ref
998 .alloc
f2b60f7d 999 .get_bytes_strip_provenance(&alloc_ref.tcx, alloc_ref.range)
17df50a5 1000 .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?)
e74abb32
XL
1001 }
1002
17df50a5 1003 /// Writes the given stream of bytes into memory.
ba9703b0
XL
1004 ///
1005 /// Performs appropriate bounds checks.
04454e1e 1006 pub fn write_bytes_ptr(
ba9703b0 1007 &mut self,
064997fb 1008 ptr: Pointer<Option<M::Provenance>>,
17df50a5 1009 src: impl IntoIterator<Item = u8>,
ba9703b0
XL
1010 ) -> InterpResult<'tcx> {
1011 let mut src = src.into_iter();
1012 let (lower, upper) = src.size_hint();
1013 let len = upper.expect("can only write bounded iterators");
1014 assert_eq!(lower, len, "can only write iterators with a precise length");
1015
17df50a5 1016 let size = Size::from_bytes(len);
04454e1e 1017 let Some(alloc_ref) = self.get_ptr_alloc_mut(ptr, size, Align::ONE)? else {
5e7ed085
FG
1018 // zero-sized access
1019 assert_matches!(
1020 src.next(),
1021 None,
1022 "iterator said it was empty but returned an element"
1023 );
1024 return Ok(());
ba9703b0 1025 };
ba9703b0 1026
17df50a5
XL
1027 // Side-step AllocRef and directly access the underlying bytes more efficiently.
1028 // (We are staying inside the bounds here so all is good.)
94222f64
XL
1029 let alloc_id = alloc_ref.alloc_id;
1030 let bytes = alloc_ref
1031 .alloc
1032 .get_bytes_mut(&alloc_ref.tcx, alloc_ref.range)
1033 .map_err(move |e| e.to_interp_error(alloc_id))?;
17df50a5
XL
1034 // `zip` would stop when the first iterator ends; we want to definitely
1035 // cover all of `bytes`.
1036 for dest in bytes {
1037 *dest = src.next().expect("iterator was shorter than it said it would be");
ba9703b0 1038 }
17df50a5 1039 assert_matches!(src.next(), None, "iterator was longer than it said it would be");
ba9703b0
XL
1040 Ok(())
1041 }
1042
04454e1e 1043 pub fn mem_copy(
ff7c6d11 1044 &mut self,
064997fb 1045 src: Pointer<Option<M::Provenance>>,
17df50a5 1046 src_align: Align,
064997fb 1047 dest: Pointer<Option<M::Provenance>>,
17df50a5 1048 dest_align: Align,
94b46f34 1049 size: Size,
ff7c6d11 1050 nonoverlapping: bool,
dc9dc135 1051 ) -> InterpResult<'tcx> {
04454e1e 1052 self.mem_copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
8faf50e0
XL
1053 }
1054
04454e1e 1055 pub fn mem_copy_repeatedly(
8faf50e0 1056 &mut self,
064997fb 1057 src: Pointer<Option<M::Provenance>>,
17df50a5 1058 src_align: Align,
064997fb 1059 dest: Pointer<Option<M::Provenance>>,
17df50a5 1060 dest_align: Align,
8faf50e0 1061 size: Size,
17df50a5 1062 num_copies: u64,
8faf50e0 1063 nonoverlapping: bool,
dc9dc135 1064 ) -> InterpResult<'tcx> {
17df50a5
XL
1065 let tcx = self.tcx;
1066 // We need to do our own bounds-checks.
136023e0
XL
1067 let src_parts = self.get_ptr_access(src, size, src_align)?;
1068 let dest_parts = self.get_ptr_access(dest, size * num_copies, dest_align)?; // `Size` multiplication
17df50a5 1069
5e7ed085 1070 // FIXME: we look up both allocations twice here, once before for the `check_ptr_access`
17df50a5
XL
1071 // and once below to get the underlying `&[mut] Allocation`.
1072
1073 // Source alloc preparations and access hooks.
064997fb 1074 let Some((src_alloc_id, src_offset, src_prov)) = src_parts else {
487cf647 1075 // Zero-sized *source*, that means dest is also zero-sized and we have nothing to do.
5e7ed085 1076 return Ok(());
17df50a5 1077 };
04454e1e 1078 let src_alloc = self.get_alloc_raw(src_alloc_id)?;
136023e0 1079 let src_range = alloc_range(src_offset, size);
f2b60f7d
FG
1080 M::before_memory_read(
1081 *tcx,
1082 &self.machine,
1083 &src_alloc.extra,
1084 (src_alloc_id, src_prov),
1085 src_range,
1086 )?;
17df50a5
XL
1087 // We need the `dest` ptr for the next operation, so we get it now.
1088 // We already did the source checks and called the hooks so we are good to return early.
064997fb 1089 let Some((dest_alloc_id, dest_offset, dest_prov)) = dest_parts else {
5e7ed085
FG
1090 // Zero-sized *destination*.
1091 return Ok(());
17df50a5
XL
1092 };
1093
487cf647 1094 // Prepare getting source provenance.
f2b60f7d
FG
1095 let src_bytes = src_alloc.get_bytes_unchecked(src_range).as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation
1096 // first copy the provenance to a temporary buffer, because
1097 // `get_bytes_mut` will clear the provenance, which is correct,
1098 // since we don't want to keep any provenance at the target.
487cf647
FG
1099 // This will also error if copying partial provenance is not supported.
1100 let provenance = src_alloc
1101 .provenance()
1102 .prepare_copy(src_range, dest_offset, num_copies, self)
1103 .map_err(|e| e.to_interp_error(dest_alloc_id))?;
3dfed10e 1104 // Prepare a copy of the initialization mask.
487cf647 1105 let init = src_alloc.init_mask().prepare_copy(src_range);
17df50a5
XL
1106
1107 // Destination alloc preparations and access hooks.
04454e1e 1108 let (dest_alloc, extra) = self.get_alloc_raw_mut(dest_alloc_id)?;
136023e0 1109 let dest_range = alloc_range(dest_offset, size * num_copies);
f2b60f7d 1110 M::before_memory_write(
04454e1e
FG
1111 *tcx,
1112 extra,
1113 &mut dest_alloc.extra,
064997fb 1114 (dest_alloc_id, dest_prov),
04454e1e
FG
1115 dest_range,
1116 )?;
94222f64
XL
1117 let dest_bytes = dest_alloc
1118 .get_bytes_mut_ptr(&tcx, dest_range)
1119 .map_err(|e| e.to_interp_error(dest_alloc_id))?
1120 .as_mut_ptr();
dfeec247 1121
487cf647 1122 if init.no_bytes_init() {
3dfed10e
XL
1123 // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
1124 // is marked as uninitialized but we otherwise omit changing the byte representation which may
1125 // be arbitrary for uninitialized bytes.
dfeec247 1126 // This also avoids writing to the target bytes so that the backing allocation is never
3dfed10e 1127 // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
dfeec247 1128 // operating system this can avoid physically allocating the page.
04454e1e
FG
1129 dest_alloc
1130 .write_uninit(&tcx, dest_range)
1131 .map_err(|e| e.to_interp_error(dest_alloc_id))?;
f2b60f7d 1132 // We can forget about the provenance, this is all not initialized anyway.
dfeec247
XL
1133 return Ok(());
1134 }
ff7c6d11
XL
1135
1136 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
1137 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
1138 // `dest` could possibly overlap.
0bf4aa26
XL
1139 // The pointers above remain valid even if the `HashMap` table is moved around because they
1140 // point into the `Vec` storing the bytes.
ff7c6d11 1141 unsafe {
136023e0 1142 if src_alloc_id == dest_alloc_id {
ff7c6d11 1143 if nonoverlapping {
ba9703b0 1144 // `Size` additions
136023e0
XL
1145 if (src_offset <= dest_offset && src_offset + size > dest_offset)
1146 || (dest_offset <= src_offset && dest_offset + size > src_offset)
ff7c6d11 1147 {
dfeec247 1148 throw_ub_format!("copy_nonoverlapping called on overlapping ranges")
ff7c6d11
XL
1149 }
1150 }
8faf50e0 1151
17df50a5 1152 for i in 0..num_copies {
dfeec247
XL
1153 ptr::copy(
1154 src_bytes,
ba9703b0
XL
1155 dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
1156 size.bytes_usize(),
dfeec247 1157 );
8faf50e0 1158 }
ff7c6d11 1159 } else {
17df50a5 1160 for i in 0..num_copies {
dfeec247
XL
1161 ptr::copy_nonoverlapping(
1162 src_bytes,
ba9703b0
XL
1163 dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication
1164 size.bytes_usize(),
dfeec247 1165 );
8faf50e0 1166 }
ff7c6d11
XL
1167 }
1168 }
1169
17df50a5 1170 // now fill in all the "init" data
487cf647
FG
1171 dest_alloc.init_mask_apply_copy(
1172 init,
136023e0
XL
1173 alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`)
1174 num_copies,
1175 );
f2b60f7d 1176 // copy the provenance to the destination
487cf647 1177 dest_alloc.provenance_apply_copy(provenance);
ff7c6d11
XL
1178
1179 Ok(())
1180 }
ff7c6d11
XL
1181}
1182
dfeec247 1183/// Machine pointer introspection.
04454e1e 1184impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
04454e1e
FG
1185 /// Test if this value might be null.
1186 /// If the machine does not support ptr-to-int casts, this is conservative.
064997fb 1187 pub fn scalar_may_be_null(&self, scalar: Scalar<M::Provenance>) -> InterpResult<'tcx, bool> {
04454e1e
FG
1188 Ok(match scalar.try_to_int() {
1189 Ok(int) => int.is_null(),
1190 Err(_) => {
1191 // Can only happen during CTFE.
064997fb 1192 let ptr = scalar.to_pointer(self)?;
04454e1e
FG
1193 match self.ptr_try_get_alloc_id(ptr) {
1194 Ok((alloc_id, offset, _)) => {
064997fb 1195 let (size, _align, _kind) = self.get_alloc_info(alloc_id);
04454e1e
FG
1196 // If the pointer is out-of-bounds, it may be null.
1197 // Note that one-past-the-end (offset == size) is still inbounds, and never null.
1198 offset > size
1199 }
1200 Err(_offset) => bug!("a non-int scalar is always a pointer"),
94222f64 1201 }
136023e0 1202 }
04454e1e 1203 })
dc9dc135
XL
1204 }
1205
136023e0
XL
1206 /// Turning a "maybe pointer" into a proper pointer (and some information
1207 /// about where it points), or an absolute address.
04454e1e 1208 pub fn ptr_try_get_alloc_id(
dc9dc135 1209 &self,
064997fb
FG
1210 ptr: Pointer<Option<M::Provenance>>,
1211 ) -> Result<(AllocId, Size, M::ProvenanceExtra), u64> {
136023e0 1212 match ptr.into_pointer_or_addr() {
04454e1e
FG
1213 Ok(ptr) => match M::ptr_get_alloc(self, ptr) {
1214 Some((alloc_id, offset, extra)) => Ok((alloc_id, offset, extra)),
1215 None => {
064997fb 1216 assert!(M::Provenance::OFFSET_IS_ADDR);
04454e1e
FG
1217 let (_, addr) = ptr.into_parts();
1218 Err(addr.bytes())
1219 }
1220 },
136023e0 1221 Err(addr) => Err(addr.bytes()),
dc9dc135
XL
1222 }
1223 }
136023e0
XL
1224
1225 /// Turning a "maybe pointer" into a proper pointer (and some information about where it points).
1226 #[inline(always)]
04454e1e 1227 pub fn ptr_get_alloc_id(
136023e0 1228 &self,
064997fb
FG
1229 ptr: Pointer<Option<M::Provenance>>,
1230 ) -> InterpResult<'tcx, (AllocId, Size, M::ProvenanceExtra)> {
04454e1e 1231 self.ptr_try_get_alloc_id(ptr).map_err(|offset| {
136023e0
XL
1232 err_ub!(DanglingIntPointer(offset, CheckInAllocMsg::InboundsTest)).into()
1233 })
1234 }
ff7c6d11 1235}