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
5//! if the size is 0, then the pointer can also be a (properly aligned, non-null)
6//! integer. It is crucial that these operations call `check_align` *before*
7//! short-circuiting the empty case!
89use std::borrow::{Borrow, Cow};
10use std::cell::Cell;
11use std::collections::VecDeque;
12use std::{fmt, ptr};
1314use rustc_abi::{Align, HasDataLayout, Size};
15use rustc_ast::Mutability;
16use rustc_data_structures::assert_matches;
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};
2223use super::{
24AllocBytes, AllocId, AllocInit, AllocMap, AllocRange, Allocation, CheckAlignMsg,
25CheckInAllocMsg, CtfeProvenance, GlobalAlloc, InterpCx, InterpResult, Machine, MayLeak,
26Misalignment, Pointer, PointerArithmetic, Provenance, Scalar, alloc_range, err_ub,
27err_ub_custom, interp_ok, throw_ub, throw_ub_custom, throw_unsup, throw_unsup_format,
28};
29use crate::const_eval::ConstEvalErrKind;
30use crate::fluent_generatedas fluent;
3132#[derive(#[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for MemoryKind<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MemoryKind::Stack =>
::core::fmt::Formatter::write_str(f, "Stack"),
MemoryKind::CallerLocation =>
::core::fmt::Formatter::write_str(f, "CallerLocation"),
MemoryKind::Machine(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Machine", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for MemoryKind<T> {
#[inline]
fn eq(&self, other: &MemoryKind<T>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(MemoryKind::Machine(__self_0), MemoryKind::Machine(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<T: ::core::marker::Copy> ::core::marker::Copy for MemoryKind<T> { }Copy, #[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for MemoryKind<T> {
#[inline]
fn clone(&self) -> MemoryKind<T> {
match self {
MemoryKind::Stack => MemoryKind::Stack,
MemoryKind::CallerLocation => MemoryKind::CallerLocation,
MemoryKind::Machine(__self_0) =>
MemoryKind::Machine(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
33pub enum MemoryKind<T> {
34/// Stack memory. Error if deallocated except during a stack pop.
35Stack,
36/// Memory allocated by `caller_location` intrinsic. Error if ever deallocated.
37CallerLocation,
38/// Additional memory kinds a machine wishes to distinguish from the builtin ones.
39Machine(T),
40}
4142impl<T: MayLeak> MayLeakfor MemoryKind<T> {
43#[inline]
44fn may_leak(self) -> bool {
45match self {
46 MemoryKind::Stack => false,
47 MemoryKind::CallerLocation => true,
48 MemoryKind::Machine(k) => k.may_leak(),
49 }
50 }
51}
5253impl<T: fmt::Display> fmt::Displayfor MemoryKind<T> {
54fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55match self {
56 MemoryKind::Stack => f.write_fmt(format_args!("stack variable"))write!(f, "stack variable"),
57 MemoryKind::CallerLocation => f.write_fmt(format_args!("caller location"))write!(f, "caller location"),
58 MemoryKind::Machine(m) => f.write_fmt(format_args!("{0}", m))write!(f, "{m}"),
59 }
60 }
61}
6263/// The return value of `get_alloc_info` indicates the "kind" of the allocation.
64#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllocKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllocKind {
#[inline]
fn clone(&self) -> AllocKind { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AllocKind {
#[inline]
fn eq(&self, other: &AllocKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AllocKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AllocKind::LiveData => "LiveData",
AllocKind::Function => "Function",
AllocKind::VTable => "VTable",
AllocKind::TypeId => "TypeId",
AllocKind::Dead => "Dead",
})
}
}Debug)]
65pub enum AllocKind {
66/// A regular live data allocation.
67LiveData,
68/// A function allocation (that fn ptrs point to).
69Function,
70/// A vtable allocation.
71VTable,
72/// A TypeId allocation.
73TypeId,
74/// A dead allocation.
75Dead,
76}
7778/// Metadata about an `AllocId`.
79#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllocInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllocInfo {
#[inline]
fn clone(&self) -> AllocInfo {
let _: ::core::clone::AssertParamIsClone<Size>;
let _: ::core::clone::AssertParamIsClone<Align>;
let _: ::core::clone::AssertParamIsClone<AllocKind>;
let _: ::core::clone::AssertParamIsClone<Mutability>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AllocInfo {
#[inline]
fn eq(&self, other: &AllocInfo) -> bool {
self.size == other.size && self.align == other.align &&
self.kind == other.kind && self.mutbl == other.mutbl
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AllocInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "AllocInfo",
"size", &self.size, "align", &self.align, "kind", &self.kind,
"mutbl", &&self.mutbl)
}
}Debug)]
80pub struct AllocInfo {
81pub size: Size,
82pub align: Align,
83pub kind: AllocKind,
84pub mutbl: Mutability,
85}
8687impl AllocInfo {
88fn new(size: Size, align: Align, kind: AllocKind, mutbl: Mutability) -> Self {
89Self { size, align, kind, mutbl }
90 }
91}
9293/// The value of a function pointer.
94#[derive(#[automatically_derived]
impl<'tcx, Other: ::core::fmt::Debug> ::core::fmt::Debug for
FnVal<'tcx, Other> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FnVal::Instance(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Instance", &__self_0),
FnVal::Other(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Other",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl<'tcx, Other: ::core::marker::Copy> ::core::marker::Copy for
FnVal<'tcx, Other> {
}Copy, #[automatically_derived]
impl<'tcx, Other: ::core::clone::Clone> ::core::clone::Clone for
FnVal<'tcx, Other> {
#[inline]
fn clone(&self) -> FnVal<'tcx, Other> {
match self {
FnVal::Instance(__self_0) =>
FnVal::Instance(::core::clone::Clone::clone(__self_0)),
FnVal::Other(__self_0) =>
FnVal::Other(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
95pub enum FnVal<'tcx, Other> {
96 Instance(Instance<'tcx>),
97 Other(Other),
98}
99100impl<'tcx, Other> FnVal<'tcx, Other> {
101pub fn as_instance(self) -> InterpResult<'tcx, Instance<'tcx>> {
102match self {
103 FnVal::Instance(instance) => interp_ok(instance),
104 FnVal::Other(_) => {
105do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'foreign\' function pointers are not supported in this context"))
})))throw_unsup_format!("'foreign' function pointers are not supported in this context")106 }
107 }
108 }
109}
110111// `Memory` has to depend on the `Machine` because some of its operations
112// (e.g., `get`) call a `Machine` hook.
113pub struct Memory<'tcx, M: Machine<'tcx>> {
114/// Allocations local to this instance of the interpreter. The kind
115 /// helps ensure that the same mechanism is used for allocation and
116 /// deallocation. When an allocation is not found here, it is a
117 /// global and looked up in the `tcx` for read access. Some machines may
118 /// have to mutate this map even on a read-only access to a global (because
119 /// they do pointer provenance tracking and the allocations in `tcx` have
120 /// the wrong type), so we let the machine override this type.
121 /// Either way, if the machine allows writing to a global, doing so will
122 /// create a copy of the global allocation here.
123// FIXME: this should not be public, but interning currently needs access to it
124pub(super) alloc_map: M::MemoryMap,
125126/// Map for "extra" function pointers.
127extra_fn_ptr_map: FxIndexMap<AllocId, M::ExtraFnVal>,
128129/// To be able to compare pointers with null, and to check alignment for accesses
130 /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
131 /// that do not exist any more.
132// FIXME: this should not be public, but interning currently needs access to it
133pub(super) dead_alloc_map: FxIndexMap<AllocId, (Size, Align)>,
134135/// This stores whether we are currently doing reads purely for the purpose of validation.
136 /// Those reads do not trigger the machine's hooks for memory reads.
137 /// Needless to say, this must only be set with great care!
138validation_in_progress: Cell<bool>,
139}
140141/// A reference to some allocation that was already bounds-checked for the given region
142/// and had the on-access machine hooks run.
143#[derive(#[automatically_derived]
impl<'a, 'tcx, Prov: ::core::marker::Copy + Provenance,
Extra: ::core::marker::Copy, Bytes: ::core::marker::Copy + AllocBytes>
::core::marker::Copy for AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
}Copy, #[automatically_derived]
impl<'a, 'tcx, Prov: ::core::clone::Clone + Provenance,
Extra: ::core::clone::Clone, Bytes: ::core::clone::Clone + AllocBytes>
::core::clone::Clone for AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
#[inline]
fn clone(&self) -> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
AllocRef {
alloc: ::core::clone::Clone::clone(&self.alloc),
range: ::core::clone::Clone::clone(&self.range),
tcx: ::core::clone::Clone::clone(&self.tcx),
alloc_id: ::core::clone::Clone::clone(&self.alloc_id),
}
}
}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}
150/// A reference to some allocation that was already bounds-checked for the given region
151/// and had the on-access machine hooks run.
152pub 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}
158159impl<'tcx, M: Machine<'tcx>> Memory<'tcx, M> {
160pub fn new() -> Self {
161Memory {
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 }
168169/// This is used by [priroda](https://github.com/oli-obk/priroda)
170pub fn alloc_map(&self) -> &M::MemoryMap {
171&self.alloc_map
172 }
173}
174175impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
176/// Call this to turn untagged "global" pointers (obtained via `tcx`) into
177 /// the machine pointer to the allocation. Must never be used
178 /// for any other pointers, nor for TLS statics.
179 ///
180 /// Using the resulting pointer represents a *direct* access to that memory
181 /// (e.g. by directly using a `static`),
182 /// as opposed to access through a pointer that was created by the program.
183 ///
184 /// This function can fail only if `ptr` points to an `extern static`.
185#[inline]
186pub fn global_root_pointer(
187&self,
188 ptr: Pointer<CtfeProvenance>,
189 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
190let alloc_id = ptr.provenance.alloc_id();
191// We need to handle `extern static`.
192match self.tcx.try_get_global_alloc(alloc_id) {
193Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
194// Thread-local statics do not have a constant address. They *must* be accessed via
195 // `ThreadLocalRef`; we can never have a pointer to them as a regular constant value.
196::rustc_middle::util::bug::bug_fmt(format_args!("global memory cannot point to thread-local static"))bug!("global memory cannot point to thread-local static")197 }
198Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
199return M::extern_static_pointer(self, def_id);
200 }
201None => {
202if !self.memory.extra_fn_ptr_map.contains_key(&alloc_id) {
{
::core::panicking::panic_fmt(format_args!("{0:?} is neither global nor a function pointer",
alloc_id));
}
};assert!(
203self.memory.extra_fn_ptr_map.contains_key(&alloc_id),
204"{alloc_id:?} is neither global nor a function pointer"
205);
206 }
207_ => {}
208 }
209// And we need to get the provenance.
210M::adjust_alloc_root_pointer(self, ptr, M::GLOBAL_KIND.map(MemoryKind::Machine))
211 }
212213pub fn fn_ptr(&mut self, fn_val: FnVal<'tcx, M::ExtraFnVal>) -> Pointer<M::Provenance> {
214let id = match fn_val {
215 FnVal::Instance(instance) => {
216let salt = M::get_global_alloc_salt(self, Some(instance));
217self.tcx.reserve_and_set_fn_alloc(instance, salt)
218 }
219 FnVal::Other(extra) => {
220// FIXME(RalfJung): Should we have a cache here?
221let id = self.tcx.reserve_alloc_id();
222let old = self.memory.extra_fn_ptr_map.insert(id, extra);
223if !old.is_none() {
::core::panicking::panic("assertion failed: old.is_none()")
};assert!(old.is_none());
224id225 }
226 };
227// Functions are global allocations, so make sure we get the right root pointer.
228 // We know this is not an `extern static` so this cannot fail.
229self.global_root_pointer(Pointer::from(id)).unwrap()
230 }
231232pub 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>> {
239let params = self.machine.get_default_alloc_params();
240let alloc = if M::PANIC_ON_ALLOC_FAIL {
241Allocation::new(size, align, init, params)
242 } else {
243Allocation::try_new(size, align, init, params)?
244};
245self.insert_allocation(alloc, kind)
246 }
247248pub 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>> {
255let params = self.machine.get_default_alloc_params();
256let alloc = Allocation::from_bytes(bytes, align, mutability, params);
257self.insert_allocation(alloc, kind)
258 }
259260pub fn insert_allocation(
261&mut self,
262 alloc: Allocation<M::Provenance, (), M::Bytes>,
263 kind: MemoryKind<M::MemoryKind>,
264 ) -> InterpResult<'tcx, Pointer<M::Provenance>> {
265if !(alloc.size() <= self.max_size_of_val()) {
::core::panicking::panic("assertion failed: alloc.size() <= self.max_size_of_val()")
};assert!(alloc.size() <= self.max_size_of_val());
266let id = self.tcx.reserve_alloc_id();
267if true {
match (&(Some(kind)), &(M::GLOBAL_KIND.map(MemoryKind::Machine))) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("dynamically allocating global memory")));
}
}
};
};debug_assert_ne!(
268Some(kind),
269 M::GLOBAL_KIND.map(MemoryKind::Machine),
270"dynamically allocating global memory"
271);
272// This cannot be merged with the `adjust_global_allocation` code path
273 // since here we have an allocation that already uses `M::Bytes`.
274let extra = M::init_local_allocation(self, id, kind, alloc.size(), alloc.align)?;
275let alloc = alloc.with_extra(extra);
276self.memory.alloc_map.insert(id, (kind, alloc));
277 M::adjust_alloc_root_pointer(self, Pointer::from(id), Some(kind))
278 }
279280/// If this grows the allocation, `init_growth` determines
281 /// whether the additional space will be initialized.
282pub 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>> {
291let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
292if offset.bytes() != 0 {
293do yeet {
let (ptr, kind) =
(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ptr))
}), "realloc");
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_realloc_or_alloc_with_offset,
add_args: Box::new(move |mut set_arg|
{
set_arg("ptr".into(),
rustc_errors::IntoDiagArg::into_diag_arg(ptr, &mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
};throw_ub_custom!(
294 fluent::const_eval_realloc_or_alloc_with_offset,
295 ptr = format!("{ptr:?}"),
296 kind = "realloc"
297);
298 }
299300// For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
301 // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
302 // If requested, we zero-init the entire allocation, to ensure that a growing
303 // allocation has its new bytes properly set. For the part that is copied,
304 // `mem_copy` below will de-initialize things as necessary.
305let new_ptr = self.allocate_ptr(new_size, new_align, kind, init_growth)?;
306let old_size = match old_size_and_align {
307Some((size, _align)) => size,
308None => self.get_alloc_raw(alloc_id)?.size(),
309 };
310// This will also call the access hooks.
311self.mem_copy(ptr, new_ptr.into(), old_size.min(new_size), /*nonoverlapping*/ true)?;
312self.deallocate_ptr(ptr, old_size_and_align, kind)?;
313314interp_ok(new_ptr)
315 }
316317/// Mark the `const_allocate`d allocation `ptr` points to as immutable so we can intern it.
318pub fn make_const_heap_ptr_global(
319&mut self,
320 ptr: Pointer<Option<CtfeProvenance>>,
321 ) -> InterpResult<'tcx>
322where
323M: Machine<'tcx, MemoryKind = crate::const_eval::MemoryKind, Provenance = CtfeProvenance>,
324 {
325let (alloc_id, offset, _) = self.ptr_get_alloc_id(ptr, 0)?;
326if offset.bytes() != 0 {
327return Err(ConstEvalErrKind::ConstMakeGlobalWithOffset(ptr)).into();
328 }
329330if self.tcx.try_get_global_alloc(alloc_id).is_some() {
331// This points to something outside the current interpreter.
332return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into();
333 }
334335// If we can't find it in `alloc_map` it must be dangling (because we don't use
336 // `extra_fn_ptr_map` in const-eval).
337let (kind, alloc) = self338 .memory
339 .alloc_map
340 .get_mut_or(alloc_id, || Err(ConstEvalErrKind::ConstMakeGlobalWithDanglingPtr(ptr)))?;
341342// Ensure this is actually a *heap* allocation, and record it as made-global.
343match kind {
344 MemoryKind::Stack | MemoryKind::CallerLocation => {
345return Err(ConstEvalErrKind::ConstMakeGlobalPtrIsNonHeap(ptr)).into();
346 }
347 MemoryKind::Machine(crate::const_eval::MemoryKind::Heap { was_made_global }) => {
348if *was_made_global {
349return Err(ConstEvalErrKind::ConstMakeGlobalPtrAlreadyMadeGlobal(alloc_id))
350 .into();
351 }
352*was_made_global = true;
353 }
354 }
355356// Prevent further mutation, this is now an immutable global.
357alloc.mutability = Mutability::Not;
358359interp_ok(())
360 }
361362#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("deallocate_ptr",
"rustc_const_eval::interpret::memory",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/memory.rs"),
::tracing_core::__macro_support::Option::Some(362u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
::tracing_core::field::FieldSet::new(&["ptr",
"old_size_and_align", "kind"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ptr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&old_size_and_align)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: InterpResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr, 0)?;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/memory.rs:370",
"rustc_const_eval::interpret::memory",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/memory.rs"),
::tracing_core::__macro_support::Option::Some(370u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("deallocating: {0:?}",
alloc_id) as &dyn Value))])
});
} else { ; }
};
if offset.bytes() != 0 {
do yeet {
let (ptr, kind) =
(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ptr))
}), "dealloc");
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_realloc_or_alloc_with_offset,
add_args: Box::new(move |mut set_arg|
{
set_arg("ptr".into(),
rustc_errors::IntoDiagArg::into_diag_arg(ptr, &mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
};
}
let Some((alloc_kind, mut alloc)) =
self.memory.alloc_map.remove(&alloc_id) else {
return Err(match self.tcx.try_get_global_alloc(alloc_id) {
Some(GlobalAlloc::Function { .. }) => {
{
let (alloc_id, kind) = (alloc_id, "fn");
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_invalid_dealloc,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc_id".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc_id,
&mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
}
}
Some(GlobalAlloc::VTable(..)) => {
{
let (alloc_id, kind) = (alloc_id, "vtable");
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_invalid_dealloc,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc_id".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc_id,
&mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
}
}
Some(GlobalAlloc::TypeId { .. }) => {
{
let (alloc_id, kind) = (alloc_id, "typeid");
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_invalid_dealloc,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc_id".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc_id,
&mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
}
}
Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
{
let (alloc_id, kind) = (alloc_id, "static_mem");
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_invalid_dealloc,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc_id".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc_id,
&mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
}
}
None =>
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerUseAfterFree(alloc_id,
CheckInAllocMsg::MemoryAccess)),
}).into();
};
if alloc.mutability.is_not() {
do yeet {
let (alloc,) = (alloc_id,);
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_dealloc_immutable,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc, &mut None));
}),
}))
};
}
if alloc_kind != kind {
do yeet {
let (alloc, alloc_kind, kind) =
(alloc_id,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", alloc_kind))
}),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", kind))
}));
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_dealloc_kind_mismatch,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc, &mut None));
set_arg("alloc_kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc_kind,
&mut None));
set_arg("kind".into(),
rustc_errors::IntoDiagArg::into_diag_arg(kind, &mut None));
}),
}))
};
}
if let Some((size, align)) = old_size_and_align {
if size != alloc.size() || align != alloc.align {
do yeet {
let (alloc, size, align, size_found, align_found) =
(alloc_id, alloc.size().bytes(), alloc.align.bytes(),
size.bytes(), align.bytes());
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_dealloc_incorrect_layout,
add_args: Box::new(move |mut set_arg|
{
set_arg("alloc".into(),
rustc_errors::IntoDiagArg::into_diag_arg(alloc, &mut None));
set_arg("size".into(),
rustc_errors::IntoDiagArg::into_diag_arg(size, &mut None));
set_arg("align".into(),
rustc_errors::IntoDiagArg::into_diag_arg(align, &mut None));
set_arg("size_found".into(),
rustc_errors::IntoDiagArg::into_diag_arg(size_found,
&mut None));
set_arg("align_found".into(),
rustc_errors::IntoDiagArg::into_diag_arg(align_found,
&mut None));
}),
}))
}
}
}
let size = alloc.size();
M::before_memory_deallocation(self.tcx, &mut self.machine,
&mut alloc.extra, ptr, (alloc_id, prov), size, alloc.align,
kind)?;
let old =
self.memory.dead_alloc_map.insert(alloc_id,
(size, alloc.align));
if old.is_some() {
::rustc_middle::util::bug::bug_fmt(format_args!("Nothing can be deallocated twice"));
}
interp_ok(())
}
}
}#[instrument(skip(self), level = "debug")]363pub 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> {
369let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr, 0)?;
370trace!("deallocating: {alloc_id:?}");
371372if offset.bytes() != 0 {
373throw_ub_custom!(
374 fluent::const_eval_realloc_or_alloc_with_offset,
375 ptr = format!("{ptr:?}"),
376 kind = "dealloc",
377 );
378 }
379380let Some((alloc_kind, mut alloc)) = self.memory.alloc_map.remove(&alloc_id) else {
381// Deallocating global memory -- always an error
382return Err(match self.tcx.try_get_global_alloc(alloc_id) {
383Some(GlobalAlloc::Function { .. }) => {
384err_ub_custom!(
385 fluent::const_eval_invalid_dealloc,
386 alloc_id = alloc_id,
387 kind = "fn",
388 )
389 }
390Some(GlobalAlloc::VTable(..)) => {
391err_ub_custom!(
392 fluent::const_eval_invalid_dealloc,
393 alloc_id = alloc_id,
394 kind = "vtable",
395 )
396 }
397Some(GlobalAlloc::TypeId { .. }) => {
398err_ub_custom!(
399 fluent::const_eval_invalid_dealloc,
400 alloc_id = alloc_id,
401 kind = "typeid",
402 )
403 }
404Some(GlobalAlloc::Static(..) | GlobalAlloc::Memory(..)) => {
405err_ub_custom!(
406 fluent::const_eval_invalid_dealloc,
407 alloc_id = alloc_id,
408 kind = "static_mem"
409)
410 }
411None => err_ub!(PointerUseAfterFree(alloc_id, CheckInAllocMsg::MemoryAccess)),
412 })
413 .into();
414 };
415416if alloc.mutability.is_not() {
417throw_ub_custom!(fluent::const_eval_dealloc_immutable, alloc = alloc_id,);
418 }
419if alloc_kind != kind {
420throw_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 }
427if let Some((size, align)) = old_size_and_align {
428if size != alloc.size() || align != alloc.align {
429throw_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 }
439440// Let the machine take some extra action
441let size = alloc.size();
442 M::before_memory_deallocation(
443self.tcx,
444&mut self.machine,
445&mut alloc.extra,
446 ptr,
447 (alloc_id, prov),
448 size,
449 alloc.align,
450 kind,
451 )?;
452453// Don't forget to remember size and align of this now-dead allocation
454let old = self.memory.dead_alloc_map.insert(alloc_id, (size, alloc.align));
455if old.is_some() {
456bug!("Nothing can be deallocated twice");
457 }
458459 interp_ok(())
460 }
461462/// Internal helper function to determine the allocation and offset of a pointer (if any).
463#[inline(always)]
464fn get_ptr_access(
465&self,
466 ptr: Pointer<Option<M::Provenance>>,
467 size: Size,
468 ) -> InterpResult<'tcx, Option<(AllocId, Size, M::ProvenanceExtra)>> {
469let size = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
470Self::check_and_deref_ptr(
471self,
472ptr,
473size,
474 CheckInAllocMsg::MemoryAccess,
475 |this, alloc_id, offset, prov| {
476let (size, align) =
477this.get_live_alloc_size_and_align(alloc_id, CheckInAllocMsg::MemoryAccess)?;
478interp_ok((size, align, (alloc_id, offset, prov)))
479 },
480 )
481 }
482483/// Check if the given pointer points to live memory of the given `size`.
484 /// The caller can control the error message for the out-of-bounds case.
485#[inline(always)]
486pub fn check_ptr_access(
487&self,
488 ptr: Pointer<Option<M::Provenance>>,
489 size: Size,
490 msg: CheckInAllocMsg,
491 ) -> InterpResult<'tcx> {
492let size = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
493Self::check_and_deref_ptr(self, ptr, size, msg, |this, alloc_id, _, _| {
494let (size, align) = this.get_live_alloc_size_and_align(alloc_id, msg)?;
495interp_ok((size, align, ()))
496 })?;
497interp_ok(())
498 }
499500/// Check whether the given pointer points to live memory for a signed amount of bytes.
501 /// A negative amounts means that the given range of memory to the left of the pointer
502 /// needs to be dereferenceable.
503pub fn check_ptr_access_signed(
504&self,
505 ptr: Pointer<Option<M::Provenance>>,
506 size: i64,
507 msg: CheckInAllocMsg,
508 ) -> InterpResult<'tcx> {
509Self::check_and_deref_ptr(self, ptr, size, msg, |this, alloc_id, _, _| {
510let (size, align) = this.get_live_alloc_size_and_align(alloc_id, msg)?;
511interp_ok((size, align, ()))
512 })?;
513interp_ok(())
514 }
515516/// Low-level helper function to check if a ptr is in-bounds and potentially return a reference
517 /// to the allocation it points to. Supports both shared and mutable references, as the actual
518 /// checking is offloaded to a helper closure. Supports signed sizes for checks "to the left" of
519 /// a pointer.
520 ///
521 /// `alloc_size` will only get called for non-zero-sized accesses.
522 ///
523 /// Returns `None` if and only if the size is 0.
524fn 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,
531AllocId,
532Size,
533 M::ProvenanceExtra,
534 ) -> InterpResult<'tcx, (Size, Align, T)>,
535 ) -> InterpResult<'tcx, Option<T>> {
536// Everything is okay with size 0.
537if size == 0 {
538return interp_ok(None);
539 }
540541interp_ok(match this.borrow().ptr_try_get_alloc_id(ptr, size) {
542Err(addr) => {
543// We couldn't get a proper allocation.
544do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DanglingIntPointer {
addr,
inbounds_size: size,
msg,
});throw_ub!(DanglingIntPointer { addr, inbounds_size: size, msg });
545 }
546Ok((alloc_id, offset, prov)) => {
547let tcx = this.borrow().tcx;
548let (alloc_size, _alloc_align, ret_val) = alloc_size(this, alloc_id, offset, prov)?;
549let offset = offset.bytes();
550// Compute absolute begin and end of the range.
551let (begin, end) = if size >= 0 {
552 (Some(offset), offset.checked_add(sizeas u64))
553 } else {
554 (offset.checked_sub(size.unsigned_abs()), Some(offset))
555 };
556// Ensure both are within bounds.
557let in_bounds = begin.is_some() && end.is_some_and(|e| e <= alloc_size.bytes());
558if !in_bounds {
559do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerOutOfBounds {
alloc_id,
alloc_size,
ptr_offset: tcx.sign_extend_to_target_isize(offset),
inbounds_size: size,
msg,
})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 }
567568Some(ret_val)
569 }
570 })
571 }
572573pub(super) fn check_misalign(
574&self,
575 misaligned: Option<Misalignment>,
576 msg: CheckAlignMsg,
577 ) -> InterpResult<'tcx> {
578if let Some(misaligned) = misaligned {
579do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::AlignmentCheckFailed(misaligned,
msg))throw_ub!(AlignmentCheckFailed(misaligned, msg))580 }
581interp_ok(())
582 }
583584pub(super) fn is_ptr_misaligned(
585&self,
586 ptr: Pointer<Option<M::Provenance>>,
587 align: Align,
588 ) -> Option<Misalignment> {
589if !M::enforce_alignment(self) || align.bytes() == 1 {
590return None;
591 }
592593#[inline]
594fn is_offset_misaligned(offset: u64, align: Align) -> Option<Misalignment> {
595if offset.is_multiple_of(align.bytes()) {
596None597 } else {
598// The biggest power of two through which `offset` is divisible.
599let offset_pow2 = 1 << offset.trailing_zeros();
600Some(Misalignment { has: Align::from_bytes(offset_pow2).unwrap(), required: align })
601 }
602 }
603604match self.ptr_try_get_alloc_id(ptr, 0) {
605Err(addr) => is_offset_misaligned(addr, align),
606Ok((alloc_id, offset, _prov)) => {
607let alloc_info = self.get_alloc_info(alloc_id);
608if let Some(misalign) = M::alignment_check(
609self,
610alloc_id,
611alloc_info.align,
612alloc_info.kind,
613offset,
614align,
615 ) {
616Some(misalign)
617 } else if M::Provenance::OFFSET_IS_ADDR {
618is_offset_misaligned(ptr.addr().bytes(), align)
619 } else {
620// Check allocation alignment and offset alignment.
621if alloc_info.align.bytes() < align.bytes() {
622Some(Misalignment { has: alloc_info.align, required: align })
623 } else {
624is_offset_misaligned(offset.bytes(), align)
625 }
626 }
627 }
628 }
629 }
630631/// Checks a pointer for misalignment.
632 ///
633 /// The error assumes this is checking the pointer used directly for an access.
634pub fn check_ptr_align(
635&self,
636 ptr: Pointer<Option<M::Provenance>>,
637 align: Align,
638 ) -> InterpResult<'tcx> {
639self.check_misalign(self.is_ptr_misaligned(ptr, align), CheckAlignMsg::AccessedPtr)
640 }
641}
642643impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
644/// This function is used by Miri's provenance GC to remove unreachable entries from the dead_alloc_map.
645pub fn remove_unreachable_allocs(&mut self, reachable_allocs: &FxHashSet<AllocId>) {
646// Unlike all the other GC helpers where we check if an `AllocId` is found in the interpreter or
647 // is live, here all the IDs in the map are for dead allocations so we don't
648 // need to check for liveness.
649#[allow(rustc::potential_query_instability)] // Only used from Miri, not queries.
650self.memory.dead_alloc_map.retain(|id, _| reachable_allocs.contains(id));
651 }
652}
653654/// Allocation accessors
655impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
656/// Helper function to obtain a global (tcx) allocation.
657 /// This attempts to return a reference to an existing allocation if
658 /// one can be found in `tcx`. That, however, is only possible if `tcx` and
659 /// this machine use the same pointer provenance, so it is indirected through
660 /// `M::adjust_allocation`.
661fn get_global_alloc(
662&self,
663 id: AllocId,
664 is_write: bool,
665 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<M::Provenance, M::AllocExtra, M::Bytes>>> {
666let (alloc, def_id) = match self.tcx.try_get_global_alloc(id) {
667Some(GlobalAlloc::Memory(mem)) => {
668// Memory of a constant or promoted or anonymous memory referenced by a static.
669(mem, None)
670 }
671Some(GlobalAlloc::Function { .. }) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DerefFunctionPointer(id))throw_ub!(DerefFunctionPointer(id)),
672Some(GlobalAlloc::VTable(..)) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DerefVTablePointer(id))throw_ub!(DerefVTablePointer(id)),
673Some(GlobalAlloc::TypeId { .. }) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DerefTypeIdPointer(id))throw_ub!(DerefTypeIdPointer(id)),
674None => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerUseAfterFree(id,
CheckInAllocMsg::MemoryAccess))throw_ub!(PointerUseAfterFree(id, CheckInAllocMsg::MemoryAccess)),
675Some(GlobalAlloc::Static(def_id)) => {
676if !self.tcx.is_static(def_id) {
::core::panicking::panic("assertion failed: self.tcx.is_static(def_id)")
};assert!(self.tcx.is_static(def_id));
677// Thread-local statics do not have a constant address. They *must* be accessed via
678 // `ThreadLocalRef`; we can never have a pointer to them as a regular constant value.
679if !!self.tcx.is_thread_local_static(def_id) {
::core::panicking::panic("assertion failed: !self.tcx.is_thread_local_static(def_id)")
};assert!(!self.tcx.is_thread_local_static(def_id));
680// Notice that every static has two `AllocId` that will resolve to the same
681 // thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
682 // and the other one is maps to `GlobalAlloc::Memory`, this is returned by
683 // `eval_static_initializer` and it is the "resolved" ID.
684 // The resolved ID is never used by the interpreted program, it is hidden.
685 // This is relied upon for soundness of const-patterns; a pointer to the resolved
686 // ID would "sidestep" the checks that make sure consts do not point to statics!
687 // The `GlobalAlloc::Memory` branch here is still reachable though; when a static
688 // contains a reference to memory that was created during its evaluation (i.e., not
689 // to another static), those inner references only exist in "resolved" form.
690if self.tcx.is_foreign_item(def_id) {
691// This is unreachable in Miri, but can happen in CTFE where we actually *do* support
692 // referencing arbitrary (declared) extern statics.
693do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
694 }
695696// We don't give a span -- statics don't need that, they cannot be generic or associated.
697let 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// We got tcx memory. Let the machine initialize its "extra" stuff.
703M::adjust_global_allocation(
704self,
705id, // always use the ID we got as input, not the "hidden" one.
706alloc.inner(),
707 )
708 }
709710/// Gives raw access to the `Allocation`, without bounds or alignment checks.
711 /// The caller is responsible for calling the access hooks!
712 ///
713 /// You almost certainly want to use `get_ptr_alloc`/`get_ptr_alloc_mut` instead.
714pub fn get_alloc_raw(
715&self,
716 id: AllocId,
717 ) -> InterpResult<'tcx, &Allocation<M::Provenance, M::AllocExtra, M::Bytes>> {
718// The error type of the inner closure here is somewhat funny. We have two
719 // ways of "erroring": An actual error, or because we got a reference from
720 // `get_global_alloc` that we can actually use directly without inserting anything anywhere.
721 // So the error type is `InterpResult<'tcx, &Allocation<M::Provenance>>`.
722let a = self.memory.alloc_map.get_or(id, || {
723// We have to funnel the `InterpErrorInfo` through a `Result` to match the `get_or` API,
724 // so we use `report_err` for that.
725let alloc = self.get_global_alloc(id, /*is_write*/ false).report_err().map_err(Err)?;
726match alloc {
727 Cow::Borrowed(alloc) => {
728// We got a ref, cheaply return that as an "error" so that the
729 // map does not get mutated.
730Err(Ok(alloc))
731 }
732 Cow::Owned(alloc) => {
733// Need to put it into the map and return a ref to that
734let 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 );
738Ok((MemoryKind::Machine(kind), alloc))
739 }
740 }
741 });
742// Now unpack that funny error type
743match a {
744Ok(a) => interp_ok(&a.1),
745Err(a) => a.into(),
746 }
747 }
748749/// Gives raw, immutable access to the `Allocation` address, without bounds or alignment checks.
750 /// The caller is responsible for calling the access hooks!
751pub fn get_alloc_bytes_unchecked_raw(&self, id: AllocId) -> InterpResult<'tcx, *const u8> {
752let alloc = self.get_alloc_raw(id)?;
753interp_ok(alloc.get_bytes_unchecked_raw())
754 }
755756/// Bounds-checked *but not align-checked* allocation access.
757pub 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 {
763let size_i64 = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
764let ptr_and_alloc = Self::check_and_deref_ptr(
765self,
766ptr,
767size_i64,
768 CheckInAllocMsg::MemoryAccess,
769 |this, alloc_id, offset, prov| {
770let alloc = this.get_alloc_raw(alloc_id)?;
771interp_ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc)))
772 },
773 )?;
774// We want to call the hook on *all* accesses that involve an AllocId, including zero-sized
775 // accesses. That means we cannot rely on the closure above or the `Some` branch below. We
776 // do this after `check_and_deref_ptr` to ensure some basic sanity has already been checked.
777if !self.memory.validation_in_progress.get() {
778if 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 }
782783if let Some((alloc_id, offset, prov, alloc)) = ptr_and_alloc {
784let range = alloc_range(offset, size);
785if !self.memory.validation_in_progress.get() {
786 M::before_memory_read(
787self.tcx,
788&self.machine,
789&alloc.extra,
790ptr,
791 (alloc_id, prov),
792range,
793 )?;
794 }
795interp_ok(Some(AllocRef { alloc, range, tcx: *self.tcx, alloc_id }))
796 } else {
797interp_ok(None)
798 }
799 }
800801/// Return the `extra` field of the given allocation.
802pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> {
803interp_ok(&self.get_alloc_raw(id)?.extra)
804 }
805806/// Return the `mutability` field of the given allocation.
807pub fn get_alloc_mutability<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, Mutability> {
808interp_ok(self.get_alloc_raw(id)?.mutability)
809 }
810811/// Gives raw mutable access to the `Allocation`, without bounds or alignment checks.
812 /// The caller is responsible for calling the access hooks!
813 ///
814 /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the
815 /// allocation.
816 ///
817 /// You almost certainly want to use `get_ptr_alloc`/`get_ptr_alloc_mut` instead.
818pub 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// We have "NLL problem case #3" here, which cannot be worked around without loss of
823 // efficiency even for the common case where the key is in the map.
824 // <https://rust-lang.github.io/rfcs/2094-nll.html#problem-case-3-conditional-control-flow-across-functions>
825 // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`, and that boils down to
826 // Miri's `adjust_alloc_root_pointer` needing to look up the size of the allocation.
827 // It could be avoided with a totally separate codepath in Miri for handling the absolute address
828 // of global allocations, but that's not worth it.)
829if self.memory.alloc_map.get_mut(id).is_none() {
830// Slow path.
831 // Allocation not found locally, go look global.
832let alloc = self.get_global_alloc(id, /*is_write*/ true)?;
833let 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 );
837self.memory.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned()));
838 }
839840let (_kind, alloc) = self.memory.alloc_map.get_mut(id).unwrap();
841if alloc.mutability.is_not() {
842do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(id))throw_ub!(WriteToReadOnly(id))843 }
844interp_ok((alloc, &mut self.machine))
845 }
846847/// Gives raw, mutable access to the `Allocation` address, without bounds or alignment checks.
848 /// The caller is responsible for calling the access hooks!
849pub fn get_alloc_bytes_unchecked_raw_mut(
850&mut self,
851 id: AllocId,
852 ) -> InterpResult<'tcx, *mut u8> {
853let alloc = self.get_alloc_raw_mut(id)?.0;
854interp_ok(alloc.get_bytes_unchecked_raw_mut())
855 }
856857/// Bounds-checked *but not align-checked* allocation access.
858pub 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 {
864let tcx = self.tcx;
865let validation_in_progress = self.memory.validation_in_progress.get();
866867let size_i64 = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes
868let ptr_and_alloc = Self::check_and_deref_ptr(
869self,
870ptr,
871size_i64,
872 CheckInAllocMsg::MemoryAccess,
873 |this, alloc_id, offset, prov| {
874let (alloc, machine) = this.get_alloc_raw_mut(alloc_id)?;
875interp_ok((alloc.size(), alloc.align, (alloc_id, offset, prov, alloc, machine)))
876 },
877 )?;
878879if let Some((alloc_id, offset, prov, alloc, machine)) = ptr_and_alloc {
880let range = alloc_range(offset, size);
881if !validation_in_progress {
882// For writes, it's okay to only call those when there actually is a non-zero
883 // amount of bytes to be written: a zero-sized write doesn't manifest anything.
884M::before_alloc_access(tcx, machine, alloc_id)?;
885 M::before_memory_write(
886tcx,
887machine,
888&mut alloc.extra,
889ptr,
890 (alloc_id, prov),
891range,
892 )?;
893 }
894interp_ok(Some(AllocRefMut { alloc, range, tcx: *tcx, alloc_id }))
895 } else {
896interp_ok(None)
897 }
898 }
899900/// Return the `extra` field of the given allocation.
901pub fn get_alloc_extra_mut<'a>(
902&'a mut self,
903 id: AllocId,
904 ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M)> {
905let (alloc, machine) = self.get_alloc_raw_mut(id)?;
906interp_ok((&mut alloc.extra, machine))
907 }
908909/// Check whether an allocation is live. This is faster than calling
910 /// [`InterpCx::get_alloc_info`] if all you need to check is whether the kind is
911 /// [`AllocKind::Dead`] because it doesn't have to look up the type and layout of statics.
912pub fn is_alloc_live(&self, id: AllocId) -> bool {
913self.memory.alloc_map.contains_key_ref(&id)
914 || self.memory.extra_fn_ptr_map.contains_key(&id)
915// We check `tcx` last as that has to acquire a lock in `many-seeds` mode.
916 // This also matches the order in `get_alloc_info`.
917|| self.tcx.try_get_global_alloc(id).is_some()
918 }
919920/// Obtain the size and alignment of an allocation, even if that allocation has
921 /// been deallocated.
922pub fn get_alloc_info(&self, id: AllocId) -> AllocInfo {
923// # Regular allocations
924 // Don't use `self.get_raw` here as that will
925 // a) cause cycles in case `id` refers to a static
926 // b) duplicate a global's allocation in miri
927if let Some((_, alloc)) = self.memory.alloc_map.get(id) {
928return AllocInfo::new(
929alloc.size(),
930alloc.align,
931 AllocKind::LiveData,
932alloc.mutability,
933 );
934 }
935936// # Function pointers
937 // (both global from `alloc_map` and local from `extra_fn_ptr_map`)
938if let Some(fn_val) = self.get_fn_alloc(id) {
939let align = match fn_val {
940 FnVal::Instance(_instance) => {
941// FIXME: Until we have a clear design for the effects of align(N) functions
942 // on the address of function pointers, we don't consider the align(N)
943 // attribute on functions in the interpreter.
944 // See <https://github.com/rust-lang/rust/issues/144661> for more context.
945Align::ONE946 }
947// Machine-specific extra functions currently do not support alignment restrictions.
948FnVal::Other(_) => Align::ONE,
949 };
950951return AllocInfo::new(Size::ZERO, align, AllocKind::Function, Mutability::Not);
952 }
953954// # Global allocations
955if let Some(global_alloc) = self.tcx.try_get_global_alloc(id) {
956// NOTE: `static` alignment from attributes has already been applied to the allocation.
957let (size, align) = global_alloc.size_and_align(*self.tcx, self.typing_env);
958let mutbl = global_alloc.mutability(*self.tcx, self.typing_env);
959let kind = match global_alloc {
960 GlobalAlloc::Static { .. } | GlobalAlloc::Memory { .. } => AllocKind::LiveData,
961 GlobalAlloc::Function { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("We already checked function pointers above"))bug!("We already checked function pointers above"),
962 GlobalAlloc::VTable { .. } => AllocKind::VTable,
963 GlobalAlloc::TypeId { .. } => AllocKind::TypeId,
964 };
965return AllocInfo::new(size, align, kind, mutbl);
966 }
967968// # Dead pointers
969let (size, align) = *self970 .memory
971 .dead_alloc_map
972 .get(&id)
973 .expect("deallocated pointers should all be recorded in `dead_alloc_map`");
974AllocInfo::new(size, align, AllocKind::Dead, Mutability::Not)
975 }
976977/// Obtain the size and alignment of a *live* allocation.
978fn get_live_alloc_size_and_align(
979&self,
980 id: AllocId,
981 msg: CheckInAllocMsg,
982 ) -> InterpResult<'tcx, (Size, Align)> {
983let info = self.get_alloc_info(id);
984if info.kind == AllocKind::Dead {
985do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::PointerUseAfterFree(id,
msg))throw_ub!(PointerUseAfterFree(id, msg))986 }
987interp_ok((info.size, info.align))
988 }
989990fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
991if let Some(extra) = self.memory.extra_fn_ptr_map.get(&id) {
992Some(FnVal::Other(*extra))
993 } else {
994match self.tcx.try_get_global_alloc(id) {
995Some(GlobalAlloc::Function { instance, .. }) => Some(FnVal::Instance(instance)),
996_ => None,
997 }
998 }
999 }
10001001/// Takes a pointer that is the first chunk of a `TypeId` and return the type that its
1002 /// provenance refers to, as well as the segment of the hash that this pointer covers.
1003pub fn get_ptr_type_id(
1004&self,
1005 ptr: Pointer<Option<M::Provenance>>,
1006 ) -> InterpResult<'tcx, (Ty<'tcx>, u64)> {
1007let (alloc_id, offset, _meta) = self.ptr_get_alloc_id(ptr, 0)?;
1008let Some(GlobalAlloc::TypeId { ty }) = self.tcx.try_get_global_alloc(alloc_id) else {
1009do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `TypeId` value: not all bytes carry type id metadata"))
})))throw_ub_format!("invalid `TypeId` value: not all bytes carry type id metadata")1010 };
1011interp_ok((ty, offset.bytes()))
1012 }
10131014pub fn get_ptr_fn(
1015&self,
1016 ptr: Pointer<Option<M::Provenance>>,
1017 ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
1018{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/memory.rs:1018",
"rustc_const_eval::interpret::memory",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/memory.rs"),
::tracing_core::__macro_support::Option::Some(1018u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("get_ptr_fn({0:?})",
ptr) as &dyn Value))])
});
} else { ; }
};trace!("get_ptr_fn({:?})", ptr);
1019let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?;
1020if offset.bytes() != 0 {
1021do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidFunctionPointer(Pointer::new(alloc_id,
offset)))throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset)))1022 }
1023self.get_fn_alloc(alloc_id)
1024 .ok_or_else(|| ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidFunctionPointer(Pointer::new(alloc_id,
offset)))err_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))))
1025 .into()
1026 }
10271028/// Get the dynamic type of the given vtable pointer.
1029 /// If `expected_trait` is `Some`, it must be a vtable for the given trait.
1030pub 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{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/memory.rs:1035",
"rustc_const_eval::interpret::memory",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/memory.rs"),
::tracing_core::__macro_support::Option::Some(1035u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("get_ptr_vtable({0:?})",
ptr) as &dyn Value))])
});
} else { ; }
};trace!("get_ptr_vtable({:?})", ptr);
1036let (alloc_id, offset, _tag) = self.ptr_get_alloc_id(ptr, 0)?;
1037if offset.bytes() != 0 {
1038do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVTablePointer(Pointer::new(alloc_id,
offset)))throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset)))1039 }
1040let Some(GlobalAlloc::VTable(ty, vtable_dyn_type)) =
1041self.tcx.try_get_global_alloc(alloc_id)
1042else {
1043do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidVTablePointer(Pointer::new(alloc_id,
offset)))throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset)))1044 };
1045if let Some(expected_dyn_type) = expected_trait {
1046self.check_vtable_for_type(vtable_dyn_type, expected_dyn_type)?;
1047 }
1048interp_ok(ty)
1049 }
10501051pub fn alloc_mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {
1052self.get_alloc_raw_mut(id)?.0.mutability = Mutability::Not;
1053interp_ok(())
1054 }
10551056/// Visit all allocations reachable from the given start set, by recursively traversing the
1057 /// provenance information of those allocations.
1058pub fn visit_reachable_allocs(
1059&mut self,
1060 start: Vec<AllocId>,
1061mut visit: impl FnMut(&mut Self, AllocId, &AllocInfo) -> InterpResult<'tcx>,
1062 ) -> InterpResult<'tcx> {
1063let mut done = FxHashSet::default();
1064let mut todo = start;
1065while let Some(id) = todo.pop() {
1066if !done.insert(id) {
1067// We already saw this allocation before, don't process it again.
1068continue;
1069 }
1070let info = self.get_alloc_info(id);
10711072// Recurse, if there is data here.
1073 // Do this *before* invoking the callback, as the callback might mutate the
1074 // allocation and e.g. replace all provenance by wildcards!
1075if info.kind == AllocKind::LiveData {
1076let alloc = self.get_alloc_raw(id)?;
1077for prov in alloc.provenance().provenances() {
1078if let Some(id) = prov.get_alloc_id() {
1079 todo.push(id);
1080 }
1081 }
1082 }
10831084// Call the callback.
1085visit(self, id, &info)?;
1086 }
1087interp_ok(())
1088 }
10891090/// Create a lazy debug printer that prints the given allocation and all allocations it points
1091 /// to, recursively.
1092#[must_use]
1093pub fn dump_alloc<'a>(&'a self, id: AllocId) -> DumpAllocs<'a, 'tcx, M> {
1094self.dump_allocs(<[_]>::into_vec(::alloc::boxed::box_new([id]))vec![id])
1095 }
10961097/// Create a lazy debug printer for a list of allocations and all allocations they point to,
1098 /// recursively.
1099#[must_use]
1100pub fn dump_allocs<'a>(&'a self, mut allocs: Vec<AllocId>) -> DumpAllocs<'a, 'tcx, M> {
1101allocs.sort();
1102allocs.dedup();
1103DumpAllocs { ecx: self, allocs }
1104 }
11051106/// Print the allocation's bytes, without any nested allocations.
1107pub fn print_alloc_bytes_for_diagnostics(&self, id: AllocId) -> String {
1108// Using the "raw" access to avoid the `before_alloc_read` hook, we specifically
1109 // want to be able to read all memory for diagnostics, even if that is cyclic.
1110let alloc = self.get_alloc_raw(id).unwrap();
1111let mut bytes = String::new();
1112if alloc.size() != Size::ZERO {
1113bytes = "\n".into();
1114// FIXME(translation) there might be pieces that are translatable.
1115rustc_middle::mir::pretty::write_allocation_bytes(*self.tcx, alloc, &mut bytes, " ")
1116 .unwrap();
1117 }
1118bytes1119 }
11201121/// Find leaked allocations, remove them from memory and return them. Allocations reachable from
1122 /// `static_roots` or a `Global` allocation are not considered leaked, as well as leaks whose
1123 /// kind's `may_leak()` returns true.
1124 ///
1125 /// This is highly destructive, no more execution can happen after this!
1126pub 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// Collect the set of allocations that are *reachable* from `Global` allocations.
1132let reachable = {
1133let mut reachable = FxHashSet::default();
1134let global_kind = M::GLOBAL_KIND.map(MemoryKind::Machine);
1135let mut todo: Vec<_> =
1136self.memory.alloc_map.filter_map_collect(move |&id, &(kind, _)| {
1137if Some(kind) == global_kind { Some(id) } else { None }
1138 });
1139todo.extend(static_roots(self));
1140while let Some(id) = todo.pop() {
1141if reachable.insert(id) {
1142// This is a new allocation, add the allocations it points to `todo`.
1143 // We only need to care about `alloc_map` memory here, as entirely unchanged
1144 // global memory cannot point to memory relevant for the leak check.
1145if 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 }
1152reachable1153 };
11541155// All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking.
1156let leaked: Vec<_> = self.memory.alloc_map.filter_map_collect(|&id, &(kind, _)| {
1157if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) }
1158 });
1159let mut result = Vec::new();
1160for &id in leaked.iter() {
1161let (kind, alloc) = self.memory.alloc_map.remove(&id).unwrap();
1162 result.push((id, kind, alloc));
1163 }
1164result1165 }
11661167/// Runs the closure in "validation" mode, which means the machine's memory read hooks will be
1168 /// suppressed. Needless to say, this must only be set with great care! Cannot be nested.
1169 ///
1170 /// We do this so Miri's allocation access tracking does not show the validation
1171 /// reads as spurious accesses.
1172pub fn run_for_validation_mut<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
1173// This deliberately uses `==` on `bool` to follow the pattern
1174 // `assert!(val.replace(new) == old)`.
1175if !(self.memory.validation_in_progress.replace(true) == false) {
{
::core::panicking::panic_fmt(format_args!("`validation_in_progress` was already set"));
}
};assert!(
1176self.memory.validation_in_progress.replace(true) == false,
1177"`validation_in_progress` was already set"
1178);
1179let res = f(self);
1180if !(self.memory.validation_in_progress.replace(false) == true) {
{
::core::panicking::panic_fmt(format_args!("`validation_in_progress` was unset by someone else"));
}
};assert!(
1181self.memory.validation_in_progress.replace(false) == true,
1182"`validation_in_progress` was unset by someone else"
1183);
1184res1185 }
11861187/// Runs the closure in "validation" mode, which means the machine's memory read hooks will be
1188 /// suppressed. Needless to say, this must only be set with great care! Cannot be nested.
1189 ///
1190 /// We do this so Miri's allocation access tracking does not show the validation
1191 /// reads as spurious accesses.
1192pub fn run_for_validation_ref<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
1193// This deliberately uses `==` on `bool` to follow the pattern
1194 // `assert!(val.replace(new) == old)`.
1195if !(self.memory.validation_in_progress.replace(true) == false) {
{
::core::panicking::panic_fmt(format_args!("`validation_in_progress` was already set"));
}
};assert!(
1196self.memory.validation_in_progress.replace(true) == false,
1197"`validation_in_progress` was already set"
1198);
1199let res = f(self);
1200if !(self.memory.validation_in_progress.replace(false) == true) {
{
::core::panicking::panic_fmt(format_args!("`validation_in_progress` was unset by someone else"));
}
};assert!(
1201self.memory.validation_in_progress.replace(false) == true,
1202"`validation_in_progress` was unset by someone else"
1203);
1204res1205 }
12061207pub(super) fn validation_in_progress(&self) -> bool {
1208self.memory.validation_in_progress.get()
1209 }
1210}
12111212#[doc(hidden)]
1213/// There's no way to use this directly, it's just a helper struct for the `dump_alloc(s)` methods.
1214pub struct DumpAllocs<'a, 'tcx, M: Machine<'tcx>> {
1215 ecx: &'a InterpCx<'tcx, M>,
1216 allocs: Vec<AllocId>,
1217}
12181219impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debugfor DumpAllocs<'a, 'tcx, M> {
1220fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1221// Cannot be a closure because it is generic in `Prov`, `Extra`.
1222fn 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 {
1228for alloc_id in alloc.provenance().provenances().filter_map(|prov| prov.get_alloc_id())
1229 {
1230 allocs_to_print.push_back(alloc_id);
1231 }
1232fmt.write_fmt(format_args!("{0}", display_allocation(tcx, alloc)))write!(fmt, "{}", display_allocation(tcx, alloc))1233 }
12341235let mut allocs_to_print: VecDeque<_> = self.allocs.iter().copied().collect();
1236// `allocs_printed` contains all allocations that we have already printed.
1237let mut allocs_printed = FxHashSet::default();
12381239while let Some(id) = allocs_to_print.pop_front() {
1240if !allocs_printed.insert(id) {
1241// Already printed, so skip this.
1242continue;
1243 }
12441245fmt.write_fmt(format_args!("{0:?}", id))write!(fmt, "{id:?}")?;
1246match self.ecx.memory.alloc_map.get(id) {
1247Some((kind, alloc)) => {
1248// normal alloc
1249fmt.write_fmt(format_args!(" ({0}, ", kind))write!(fmt, " ({kind}, ")?;
1250 write_allocation_track_relocs(
1251&mut *fmt,
1252*self.ecx.tcx,
1253&mut allocs_to_print,
1254 alloc,
1255 )?;
1256 }
1257None => {
1258// global alloc
1259match self.ecx.tcx.try_get_global_alloc(id) {
1260Some(GlobalAlloc::Memory(alloc)) => {
1261fmt.write_fmt(format_args!(" (unchanged global, "))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 }
1269Some(GlobalAlloc::Function { instance, .. }) => {
1270fmt.write_fmt(format_args!(" (fn: {0})", instance))write!(fmt, " (fn: {instance})")?;
1271 }
1272Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1273fmt.write_fmt(format_args!(" (vtable: impl {0} for {1})", dyn_ty, ty))write!(fmt, " (vtable: impl {dyn_ty} for {ty})")?;
1274 }
1275Some(GlobalAlloc::TypeId { ty }) => {
1276fmt.write_fmt(format_args!(" (typeid for {0})", ty))write!(fmt, " (typeid for {ty})")?;
1277 }
1278Some(GlobalAlloc::Static(did)) => {
1279fmt.write_fmt(format_args!(" (static: {0})", self.ecx.tcx.def_path_str(did)))write!(fmt, " (static: {})", self.ecx.tcx.def_path_str(did))?;
1280 }
1281None => {
1282fmt.write_fmt(format_args!(" (deallocated)"))write!(fmt, " (deallocated)")?;
1283 }
1284 }
1285 }
1286 }
1287fmt.write_fmt(format_args!("\n"))writeln!(fmt)?;
1288 }
1289Ok(())
1290 }
1291}
12921293/// Reading and writing.
1294impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>
1295AllocRefMut<'a, 'tcx, Prov, Extra, Bytes>
1296{
1297pub fn as_ref<'b>(&'b self) -> AllocRef<'b, 'tcx, Prov, Extra, Bytes> {
1298AllocRef { alloc: self.alloc, range: self.range, tcx: self.tcx, alloc_id: self.alloc_id }
1299 }
13001301/// `range` is relative to this allocation reference, not the base of the allocation.
1302pub fn write_scalar(&mut self, range: AllocRange, val: Scalar<Prov>) -> InterpResult<'tcx> {
1303let range = self.range.subrange(range);
1304{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/memory.rs:1304",
"rustc_const_eval::interpret::memory",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/memory.rs"),
::tracing_core::__macro_support::Option::Some(1304u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::memory"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("write_scalar at {0:?}{1:?}: {2:?}",
self.alloc_id, range, val) as &dyn Value))])
});
} else { ; }
};debug!("write_scalar at {:?}{range:?}: {val:?}", self.alloc_id);
13051306self.alloc
1307 .write_scalar(&self.tcx, range, val)
1308 .map_err(|e| e.to_interp_error(self.alloc_id))
1309 .into()
1310 }
13111312/// `offset` is relative to this allocation reference, not the base of the allocation.
1313pub fn write_ptr_sized(&mut self, offset: Size, val: Scalar<Prov>) -> InterpResult<'tcx> {
1314self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size()), val)
1315 }
13161317/// Mark the given sub-range (relative to this allocation reference) as uninitialized.
1318pub fn write_uninit(&mut self, range: AllocRange) {
1319let range = self.range.subrange(range);
13201321self.alloc.write_uninit(&self.tcx, range);
1322 }
13231324/// Mark the entire referenced range as uninitialized
1325pub fn write_uninit_full(&mut self) {
1326self.alloc.write_uninit(&self.tcx, self.range);
1327 }
13281329/// Remove all provenance in the reference range.
1330pub fn clear_provenance(&mut self) {
1331self.alloc.clear_provenance(&self.tcx, self.range);
1332 }
1333}
13341335impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
1336/// `range` is relative to this allocation reference, not the base of the allocation.
1337pub fn read_scalar(
1338&self,
1339 range: AllocRange,
1340 read_provenance: bool,
1341 ) -> InterpResult<'tcx, Scalar<Prov>> {
1342let range = self.range.subrange(range);
1343self.alloc
1344 .read_scalar(&self.tcx, range, read_provenance)
1345 .map_err(|e| e.to_interp_error(self.alloc_id))
1346 .into()
1347 }
13481349/// `range` is relative to this allocation reference, not the base of the allocation.
1350pub fn read_integer(&self, range: AllocRange) -> InterpResult<'tcx, Scalar<Prov>> {
1351self.read_scalar(range, /*read_provenance*/ false)
1352 }
13531354/// `offset` is relative to this allocation reference, not the base of the allocation.
1355pub fn read_pointer(&self, offset: Size) -> InterpResult<'tcx, Scalar<Prov>> {
1356self.read_scalar(
1357alloc_range(offset, self.tcx.data_layout().pointer_size()),
1358/*read_provenance*/ true,
1359 )
1360 }
13611362/// `range` is relative to this allocation reference, not the base of the allocation.
1363pub fn get_bytes_strip_provenance<'b>(&'b self) -> InterpResult<'tcx, &'a [u8]> {
1364self.alloc
1365 .get_bytes_strip_provenance(&self.tcx, self.range)
1366 .map_err(|e| e.to_interp_error(self.alloc_id))
1367 .into()
1368 }
13691370/// Returns whether the allocation has provenance anywhere in the range of the `AllocRef`.
1371pub fn has_provenance(&self) -> bool {
1372 !self.alloc.provenance().range_empty(self.range, &self.tcx)
1373 }
1374}
13751376impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1377/// Reads the given number of bytes from memory, and strips their provenance if possible.
1378 /// Returns them as a slice.
1379 ///
1380 /// Performs appropriate bounds checks.
1381pub fn read_bytes_ptr_strip_provenance(
1382&self,
1383 ptr: Pointer<Option<M::Provenance>>,
1384 size: Size,
1385 ) -> InterpResult<'tcx, &[u8]> {
1386let Some(alloc_ref) = self.get_ptr_alloc(ptr, size)? else {
1387// zero-sized access
1388return interp_ok(&[]);
1389 };
1390// Side-step AllocRef and directly access the underlying bytes more efficiently.
1391 // (We are staying inside the bounds here so all is good.)
1392interp_ok(
1393alloc_ref1394 .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 }
13991400/// Writes the given stream of bytes into memory.
1401 ///
1402 /// Performs appropriate bounds checks.
1403pub fn write_bytes_ptr(
1404&mut self,
1405 ptr: Pointer<Option<M::Provenance>>,
1406 src: impl IntoIterator<Item = u8>,
1407 ) -> InterpResult<'tcx> {
1408let mut src = src.into_iter();
1409let (lower, upper) = src.size_hint();
1410let len = upper.expect("can only write bounded iterators");
1411match (&lower, &len) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::Some(format_args!("can only write iterators with a precise length")));
}
}
};assert_eq!(lower, len, "can only write iterators with a precise length");
14121413let size = Size::from_bytes(len);
1414let Some(alloc_ref) = self.get_ptr_alloc_mut(ptr, size)? else {
1415// zero-sized access
1416match src.next() {
None => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val, "None",
::core::option::Option::Some(format_args!("iterator said it was empty but returned an element")));
}
};assert_matches!(src.next(), None, "iterator said it was empty but returned an element");
1417return interp_ok(());
1418 };
14191420// Side-step AllocRef and directly access the underlying bytes more efficiently.
1421 // (We are staying inside the bounds here and all bytes do get overwritten so all is good.)
1422let bytes =
1423alloc_ref.alloc.get_bytes_unchecked_for_overwrite(&alloc_ref.tcx, alloc_ref.range);
1424// `zip` would stop when the first iterator ends; we want to definitely
1425 // cover all of `bytes`.
1426for dest in bytes {
1427*dest = src.next().expect("iterator was shorter than it said it would be");
1428 }
1429match src.next() {
None => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val, "None",
::core::option::Option::Some(format_args!("iterator was longer than it said it would be")));
}
};assert_matches!(src.next(), None, "iterator was longer than it said it would be");
1430interp_ok(())
1431 }
14321433pub 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> {
1440self.mem_copy_repeatedly(src, dest, size, 1, nonoverlapping)
1441 }
14421443/// Performs `num_copies` many copies of `size` many bytes from `src` to `dest + i*size` (where
1444 /// `i` is the index of the copy).
1445 ///
1446 /// Either `nonoverlapping` must be true or `num_copies` must be 1; doing repeated copies that
1447 /// may overlap is not supported.
1448pub 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> {
1456let tcx = self.tcx;
1457// We need to do our own bounds-checks.
1458let src_parts = self.get_ptr_access(src, size)?;
1459let dest_parts = self.get_ptr_access(dest, size * num_copies)?; // `Size` multiplication
14601461 // Similar to `get_ptr_alloc`, we need to call `before_alloc_access` even for zero-sized
1462 // reads. However, just like in `get_ptr_alloc_mut`, the write part is okay to skip for
1463 // zero-sized writes.
1464if 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 }
14681469// FIXME: we look up both allocations twice here, once before for the `check_ptr_access`
1470 // and once below to get the underlying `&[mut] Allocation`.
14711472 // Source alloc preparations and access hooks.
1473let Some((src_alloc_id, src_offset, src_prov)) = src_partselse {
1474// Zero-sized *source*, that means dest is also zero-sized and we have nothing to do.
1475return interp_ok(());
1476 };
1477let src_alloc = self.get_alloc_raw(src_alloc_id)?;
1478let src_range = alloc_range(src_offset, size);
1479if !!self.memory.validation_in_progress.get() {
{
::core::panicking::panic_fmt(format_args!("we can\'t be copying during validation"));
}
};assert!(!self.memory.validation_in_progress.get(), "we can't be copying during validation");
14801481// Trigger read hook.
1482 // For the overlapping case, it is crucial that we trigger the read hook
1483 // before the write hook -- the aliasing model cares about the order.
1484M::before_memory_read(
1485tcx,
1486&self.machine,
1487&src_alloc.extra,
1488src,
1489 (src_alloc_id, src_prov),
1490src_range,
1491 )?;
1492// We need the `dest` ptr for the next operation, so we get it now.
1493 // We already did the source checks and called the hooks so we are good to return early.
1494let Some((dest_alloc_id, dest_offset, dest_prov)) = dest_partselse {
1495// Zero-sized *destination*.
1496return interp_ok(());
1497 };
14981499// Prepare getting source provenance.
1500let src_bytes = src_alloc.get_bytes_unchecked(src_range).as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation
1501 // First copy the provenance to a temporary buffer, because
1502 // `get_bytes_unchecked_for_overwrite_ptr` will clear the provenance (in preparation for
1503 // inserting the new provenance), and that can overlap with the source range.
1504let provenance = src_alloc.provenance_prepare_copy(src_range, self);
1505// Prepare a copy of the initialization mask.
1506let init = src_alloc.init_mask().prepare_copy(src_range);
15071508// Destination alloc preparations...
1509let (dest_alloc, machine) = self.get_alloc_raw_mut(dest_alloc_id)?;
1510let dest_range = alloc_range(dest_offset, size * num_copies);
1511// ...and access hooks.
1512M::before_alloc_access(tcx, machine, dest_alloc_id)?;
1513 M::before_memory_write(
1514tcx,
1515machine,
1516&mut dest_alloc.extra,
1517dest,
1518 (dest_alloc_id, dest_prov),
1519dest_range,
1520 )?;
1521// Yes we do overwrite all bytes in `dest_bytes`.
1522let dest_bytes =
1523dest_alloc.get_bytes_unchecked_for_overwrite_ptr(&tcx, dest_range).as_mut_ptr();
15241525if init.no_bytes_init() {
1526// Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
1527 // is marked as uninitialized but we otherwise omit changing the byte representation which may
1528 // be arbitrary for uninitialized bytes.
1529 // This also avoids writing to the target bytes so that the backing allocation is never
1530 // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
1531 // operating system this can avoid physically allocating the page.
1532dest_alloc.write_uninit(&tcx, dest_range);
1533// `write_uninit` also resets the provenance, so we are done.
1534return interp_ok(());
1535 }
15361537// SAFE: The above indexing would have panicked if there weren't at least `size` bytes
1538 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
1539 // `dest` could possibly overlap.
1540 // The pointers above remain valid even if the `HashMap` table is moved around because they
1541 // point into the `Vec` storing the bytes.
1542unsafe {
1543if src_alloc_id == dest_alloc_id {
1544if nonoverlapping {
1545// `Size` additions
1546if (src_offset <= dest_offset && src_offset + size > dest_offset)
1547 || (dest_offset <= src_offset && dest_offset + size > src_offset)
1548 {
1549do yeet {
::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Custom(::rustc_middle::error::CustomSubdiagnostic {
msg: || fluent::const_eval_copy_nonoverlapping_overlapping,
add_args: Box::new(move |mut set_arg| {}),
}))
};throw_ub_custom!(fluent::const_eval_copy_nonoverlapping_overlapping);
1550 }
1551 }
1552 }
1553if num_copies > 1 {
1554if !nonoverlapping {
{
::core::panicking::panic_fmt(format_args!("multi-copy only supported in non-overlapping mode"));
}
};assert!(nonoverlapping, "multi-copy only supported in non-overlapping mode");
1555 }
15561557let size_in_bytes = size.bytes_usize();
1558// For particularly large arrays (where this is perf-sensitive) it's common that
1559 // we're writing a single byte repeatedly. So, optimize that case to a memset.
1560if size_in_bytes == 1 {
1561if true {
if !(num_copies >= 1) {
::core::panicking::panic("assertion failed: num_copies >= 1")
};
};debug_assert!(num_copies >= 1); // we already handled the zero-sized cases above.
1562 // SAFETY: `src_bytes` would be read from anyway by `copy` below (num_copies >= 1).
1563let value = *src_bytes;
1564dest_bytes.write_bytes(value, (size * num_copies).bytes_usize());
1565 } else if src_alloc_id == dest_alloc_id {
1566let mut dest_ptr = dest_bytes;
1567for _ in 0..num_copies {
1568// Here we rely on `src` and `dest` being non-overlapping if there is more than
1569 // one copy.
1570ptr::copy(src_bytes, dest_ptr, size_in_bytes);
1571 dest_ptr = dest_ptr.add(size_in_bytes);
1572 }
1573 } else {
1574let mut dest_ptr = dest_bytes;
1575for _ in 0..num_copies {
1576 ptr::copy_nonoverlapping(src_bytes, dest_ptr, size_in_bytes);
1577 dest_ptr = dest_ptr.add(size_in_bytes);
1578 }
1579 }
1580 }
15811582// now fill in all the "init" data
1583dest_alloc.init_mask_apply_copy(
1584init,
1585alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`)
1586num_copies,
1587 );
1588// copy the provenance to the destination
1589dest_alloc.provenance_apply_copy(provenance, alloc_range(dest_offset, size), num_copies);
15901591interp_ok(())
1592 }
1593}
15941595/// Machine pointer introspection.
1596impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
1597/// Test if this value might be null.
1598 /// If the machine does not support ptr-to-int casts, this is conservative.
1599pub fn scalar_may_be_null(&self, scalar: Scalar<M::Provenance>) -> InterpResult<'tcx, bool> {
1600match scalar.try_to_scalar_int() {
1601Ok(int) => interp_ok(int.is_null()),
1602Err(_) => {
1603// We can't cast this pointer to an integer. Can only happen during CTFE.
1604let ptr = scalar.to_pointer(self)?;
1605match self.ptr_try_get_alloc_id(ptr, 0) {
1606Ok((alloc_id, offset, _)) => {
1607let info = self.get_alloc_info(alloc_id);
1608if info.kind == AllocKind::TypeId {
1609// We *could* actually precisely answer this question since here,
1610 // the offset *is* the integer value. But the entire point of making
1611 // this a pointer is not to leak the integer value, so we say everything
1612 // might be null.
1613return interp_ok(true);
1614 }
1615// If the pointer is in-bounds (including "at the end"), it is definitely not null.
1616if offset <= info.size {
1617return interp_ok(false);
1618 }
1619// If the allocation is N-aligned, and the offset is not divisible by N,
1620 // then `base + offset` has a non-zero remainder after division by `N`,
1621 // which means `base + offset` cannot be null.
1622if !offset.bytes().is_multiple_of(info.align.bytes()) {
1623return interp_ok(false);
1624 }
1625// We don't know enough, this might be null.
1626interp_ok(true)
1627 }
1628Err(_offset) => ::rustc_middle::util::bug::bug_fmt(format_args!("a non-int scalar is always a pointer"))bug!("a non-int scalar is always a pointer"),
1629 }
1630 }
1631 }
1632 }
16331634/// Turning a "maybe pointer" into a proper pointer (and some information
1635 /// about where it points), or an absolute address.
1636 ///
1637 /// `size` says how many bytes of memory are expected at that pointer. This is largely only used
1638 /// for error messages; however, the *sign* of `size` can be used to disambiguate situations
1639 /// where a wildcard pointer sits right in between two allocations.
1640 /// It is almost always okay to just set the size to 0; this will be treated like a positive size
1641 /// for handling wildcard pointers.
1642 ///
1643 /// The result must be used immediately; it is not allowed to convert
1644 /// the returned data back into a `Pointer` and store that in machine state.
1645 /// (In fact that's not even possible since `M::ProvenanceExtra` is generic and
1646 /// we don't have an operation to turn it back into `M::Provenance`.)
1647pub fn ptr_try_get_alloc_id(
1648&self,
1649 ptr: Pointer<Option<M::Provenance>>,
1650 size: i64,
1651 ) -> Result<(AllocId, Size, M::ProvenanceExtra), u64> {
1652match ptr.into_pointer_or_addr() {
1653Ok(ptr) => match M::ptr_get_alloc(self, ptr, size) {
1654Some((alloc_id, offset, extra)) => Ok((alloc_id, offset, extra)),
1655None => {
1656if !M::Provenance::OFFSET_IS_ADDR {
::core::panicking::panic("assertion failed: M::Provenance::OFFSET_IS_ADDR")
};assert!(M::Provenance::OFFSET_IS_ADDR);
1657// Offset is absolute, as we just asserted.
1658let (_, addr) = ptr.into_raw_parts();
1659Err(addr.bytes())
1660 }
1661 },
1662Err(addr) => Err(addr.bytes()),
1663 }
1664 }
16651666/// Turning a "maybe pointer" into a proper pointer (and some information about where it points).
1667 ///
1668 /// `size` says how many bytes of memory are expected at that pointer. This is largely only used
1669 /// for error messages; however, the *sign* of `size` can be used to disambiguate situations
1670 /// where a wildcard pointer sits right in between two allocations.
1671 /// It is almost always okay to just set the size to 0; this will be treated like a positive size
1672 /// for handling wildcard pointers.
1673 ///
1674 /// The result must be used immediately; it is not allowed to convert
1675 /// the returned data back into a `Pointer` and store that in machine state.
1676 /// (In fact that's not even possible since `M::ProvenanceExtra` is generic and
1677 /// we don't have an operation to turn it back into `M::Provenance`.)
1678#[inline(always)]
1679pub fn ptr_get_alloc_id(
1680&self,
1681 ptr: Pointer<Option<M::Provenance>>,
1682 size: i64,
1683 ) -> InterpResult<'tcx, (AllocId, Size, M::ProvenanceExtra)> {
1684self.ptr_try_get_alloc_id(ptr, size)
1685 .map_err(|offset| {
1686::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::DanglingIntPointer {
addr: offset,
inbounds_size: size,
msg: CheckInAllocMsg::Dereferenceable,
})err_ub!(DanglingIntPointer {
1687 addr: offset,
1688 inbounds_size: size,
1689 msg: CheckInAllocMsg::Dereferenceable
1690 })1691 })
1692 .into()
1693 }
1694}