Skip to content

Commit 3dd9d4f

Browse files
committed
temp
1 parent c683873 commit 3dd9d4f

File tree

18 files changed

+98
-196
lines changed

18 files changed

+98
-196
lines changed

compiler/rustc_const_eval/src/const_eval/dummy_machine.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,9 @@ impl<'tcx> interpret::Machine<'tcx> for DummyMachine {
197197
) -> &'a mut Vec<interpret::Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
198198
unimplemented!()
199199
}
200+
201+
fn get_default_byte_mdata(
202+
&self,
203+
) -> <Self::Bytes as rustc_middle::mir::interpret::AllocBytes>::ByteMetadata {
204+
}
200205
}

compiler/rustc_const_eval/src/const_eval/machine.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,8 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
735735
Cow::Owned(compute_range())
736736
}
737737
}
738+
739+
fn get_default_byte_mdata(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::ByteMetadata {}
738740
}
739741

740742
// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups

compiler/rustc_const_eval/src/interpret/intrinsics.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::fluent_generated as fluent;
2626
/// Directly returns an `Allocation` containing an absolute path representation of the given type.
2727
pub(crate) fn alloc_type_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ConstAllocation<'tcx> {
2828
let path = crate::util::type_name(tcx, ty);
29-
let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes());
29+
let alloc = Allocation::from_bytes_byte_aligned_immutable(path.into_bytes(), ());
3030
tcx.mk_const_alloc(alloc)
3131
}
3232

compiler/rustc_const_eval/src/interpret/machine.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,8 @@ pub trait Machine<'tcx>: Sized {
628628
// Default to no caching.
629629
Cow::Owned(compute_range())
630630
}
631+
632+
fn get_default_byte_mdata(&self) -> <Self::Bytes as AllocBytes>::ByteMetadata;
631633
}
632634

633635
/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines

compiler/rustc_const_eval/src/interpret/memory.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,10 +233,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
233233
kind: MemoryKind<M::MemoryKind>,
234234
init: AllocInit,
235235
) -> InterpResult<'tcx, Pointer<M::Provenance>> {
236+
let dsc = self.machine.get_default_byte_mdata();
236237
let alloc = if M::PANIC_ON_ALLOC_FAIL {
237-
Allocation::new(size, align, init)
238+
Allocation::new(size, align, init, dsc)
238239
} else {
239-
Allocation::try_new(size, align, init)?
240+
Allocation::try_new(size, align, init, dsc)?
240241
};
241242
self.insert_allocation(alloc, kind)
242243
}
@@ -248,7 +249,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
248249
kind: MemoryKind<M::MemoryKind>,
249250
mutability: Mutability,
250251
) -> InterpResult<'tcx, Pointer<M::Provenance>> {
251-
let alloc = Allocation::from_bytes(bytes, align, mutability);
252+
let dsc = self.machine.get_default_byte_mdata();
253+
let alloc = Allocation::from_bytes(bytes, align, mutability, dsc);
252254
self.insert_allocation(alloc, kind)
253255
}
254256

compiler/rustc_const_eval/src/interpret/util.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ pub(crate) fn create_static_alloc<'tcx>(
3838
static_def_id: LocalDefId,
3939
layout: TyAndLayout<'tcx>,
4040
) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
41-
let alloc = Allocation::try_new(layout.size, layout.align.abi, AllocInit::Uninit)?;
41+
let alloc = Allocation::try_new(layout.size, layout.align.abi, AllocInit::Uninit, ())?;
4242
let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id.into());
4343
assert_eq!(ecx.machine.static_root_ids, None);
4444
ecx.machine.static_root_ids = Some((alloc_id, static_def_id));

compiler/rustc_middle/src/mir/interpret/allocation.rs

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use crate::ty;
2929
pub trait AllocBytes: Clone + fmt::Debug + Deref<Target = [u8]> + DerefMut<Target = [u8]> {
3030
/// Used for giving extra metadata on creation. Miri uses this to allow
3131
/// machine memory to be allocated separately from other allocations.
32-
type ByteMetadata: Default + Clone + fmt::Debug;
32+
type ByteMetadata: Clone + fmt::Debug;
3333

3434
/// Create an `AllocBytes` from a slice of `u8`.
3535
fn from_bytes<'a>(
@@ -55,6 +55,9 @@ pub trait AllocBytes: Clone + fmt::Debug + Deref<Target = [u8]> + DerefMut<Targe
5555
/// - other pointers returned by this method, and
5656
/// - references returned from `deref()`, as long as there was no write.
5757
fn as_ptr(&self) -> *const u8;
58+
59+
/// Gets the allocation metadata.
60+
fn get_mdata(&self) -> Self::ByteMetadata;
5861
}
5962

6063
/// Default `bytes` for `Allocation` is a `Box<u8>`.
@@ -79,6 +82,8 @@ impl AllocBytes for Box<[u8]> {
7982
fn as_ptr(&self) -> *const u8 {
8083
Box::as_ptr(self).cast()
8184
}
85+
86+
fn get_mdata(&self) -> () {}
8287
}
8388

8489
/// This type represents an Allocation in the Miri/CTFE core engine.
@@ -185,6 +190,7 @@ fn all_zero(buf: &[u8]) -> bool {
185190
impl<Prov: Provenance, Extra, Bytes, E: Encoder> Encodable<E> for Allocation<Prov, Extra, Bytes>
186191
where
187192
Bytes: AllocBytes,
193+
Bytes::ByteMetadata: Encodable<E>,
188194
ProvenanceMap<Prov>: Encodable<E>,
189195
Extra: Encodable<E>,
190196
{
@@ -196,6 +202,7 @@ where
196202
if !all_zero {
197203
encoder.emit_raw_bytes(&self.bytes);
198204
}
205+
self.bytes.get_mdata().encode(encoder);
199206
self.provenance.encode(encoder);
200207
self.init_mask.encode(encoder);
201208
self.extra.encode(encoder);
@@ -205,6 +212,7 @@ where
205212
impl<Prov: Provenance, Extra, Bytes, D: Decoder> Decodable<D> for Allocation<Prov, Extra, Bytes>
206213
where
207214
Bytes: AllocBytes,
215+
Bytes::ByteMetadata: Decodable<D>,
208216
ProvenanceMap<Prov>: Decodable<D>,
209217
Extra: Decodable<D>,
210218
{
@@ -213,7 +221,9 @@ where
213221

214222
let len = decoder.read_usize();
215223
let bytes = if all_zero { vec![0u8; len] } else { decoder.read_raw_bytes(len).to_vec() };
216-
let bytes = Bytes::from_bytes(bytes, align, Bytes::ByteMetadata::default());
224+
225+
let mdata = Decodable::decode(decoder);
226+
let bytes = Bytes::from_bytes(bytes, align, mdata);
217227

218228
let provenance = Decodable::decode(decoder);
219229
let init_mask = Decodable::decode(decoder);
@@ -405,8 +415,9 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
405415
slice: impl Into<Cow<'a, [u8]>>,
406416
align: Align,
407417
mutability: Mutability,
418+
dsc: <Bytes as AllocBytes>::ByteMetadata,
408419
) -> Self {
409-
let bytes = Bytes::from_bytes(slice, align, Bytes::ByteMetadata::default());
420+
let bytes = Bytes::from_bytes(slice, align, dsc);
410421
let size = Size::from_bytes(bytes.len());
411422
Self {
412423
bytes,
@@ -418,14 +429,18 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
418429
}
419430
}
420431

421-
pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into<Cow<'a, [u8]>>) -> Self {
422-
Allocation::from_bytes(slice, Align::ONE, Mutability::Not)
432+
pub fn from_bytes_byte_aligned_immutable<'a>(
433+
slice: impl Into<Cow<'a, [u8]>>,
434+
dsc: <Bytes as AllocBytes>::ByteMetadata,
435+
) -> Self {
436+
Allocation::from_bytes(slice, Align::ONE, Mutability::Not, dsc)
423437
}
424438

425439
fn new_inner<R>(
426440
size: Size,
427441
align: Align,
428442
init: AllocInit,
443+
dsc: <Bytes as AllocBytes>::ByteMetadata,
429444
fail: impl FnOnce() -> R,
430445
) -> Result<Self, R> {
431446
// We raise an error if we cannot create the allocation on the host.
@@ -434,7 +449,7 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
434449
// deterministic. However, we can be non-deterministic here because all uses of const
435450
// evaluation (including ConstProp!) will make compilation fail (via hard error
436451
// or ICE) upon encountering a `MemoryExhausted` error.
437-
let bytes = Bytes::zeroed(size, align, Bytes::ByteMetadata::default()).ok_or_else(fail)?;
452+
let bytes = Bytes::zeroed(size, align, dsc).ok_or_else(fail)?;
438453

439454
Ok(Allocation {
440455
bytes,
@@ -454,8 +469,13 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
454469

455470
/// Try to create an Allocation of `size` bytes, failing if there is not enough memory
456471
/// available to the compiler to do so.
457-
pub fn try_new<'tcx>(size: Size, align: Align, init: AllocInit) -> InterpResult<'tcx, Self> {
458-
Self::new_inner(size, align, init, || {
472+
pub fn try_new<'tcx>(
473+
size: Size,
474+
align: Align,
475+
init: AllocInit,
476+
dsc: <Bytes as AllocBytes>::ByteMetadata,
477+
) -> InterpResult<'tcx, Self> {
478+
Self::new_inner(size, align, init, dsc, || {
459479
ty::tls::with(|tcx| tcx.dcx().delayed_bug("exhausted memory during interpretation"));
460480
InterpErrorKind::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted)
461481
})
@@ -467,8 +487,13 @@ impl<Prov: Provenance, Bytes: AllocBytes> Allocation<Prov, (), Bytes> {
467487
///
468488
/// Example use case: To obtain an Allocation filled with specific data,
469489
/// first call this function and then call write_scalar to fill in the right data.
470-
pub fn new(size: Size, align: Align, init: AllocInit) -> Self {
471-
match Self::new_inner(size, align, init, || {
490+
pub fn new(
491+
size: Size,
492+
align: Align,
493+
init: AllocInit,
494+
dsc: <Bytes as AllocBytes>::ByteMetadata,
495+
) -> Self {
496+
match Self::new_inner(size, align, init, dsc, || {
472497
panic!(
473498
"interpreter ran out of memory: cannot create allocation of {} bytes",
474499
size.bytes()

compiler/rustc_middle/src/ty/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1579,7 +1579,7 @@ impl<'tcx> TyCtxt<'tcx> {
15791579
/// Returns the same `AllocId` if called again with the same bytes.
15801580
pub fn allocate_bytes_dedup(self, bytes: &[u8], salt: usize) -> interpret::AllocId {
15811581
// Create an allocation that just contains these bytes.
1582-
let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes);
1582+
let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes, ());
15831583
let alloc = self.mk_const_alloc(alloc);
15841584
self.reserve_and_set_memory_dedup(alloc, salt)
15851585
}

compiler/rustc_middle/src/ty/vtable.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ pub(super) fn vtable_allocation_provider<'tcx>(
110110
let ptr_align = tcx.data_layout.pointer_align.abi;
111111

112112
let vtable_size = ptr_size * u64::try_from(vtable_entries.len()).unwrap();
113-
let mut vtable = Allocation::new(vtable_size, ptr_align, AllocInit::Uninit);
113+
let mut vtable = Allocation::new(vtable_size, ptr_align, AllocInit::Uninit, ());
114114

115115
// No need to do any alignment checks on the memory accesses below, because we know the
116116
// allocation is correctly aligned as we created it above. Also we're only offsetting by

compiler/rustc_mir_build/src/builder/expr/as_constant.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,14 +121,14 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>
121121
let value = match (lit, lit_ty.kind()) {
122122
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
123123
let s = s.as_str();
124-
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
124+
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes(), ());
125125
let allocation = tcx.mk_const_alloc(allocation);
126126
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
127127
}
128128
(ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _))
129129
if matches!(inner_ty.kind(), ty::Slice(_)) =>
130130
{
131-
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
131+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8], ());
132132
let allocation = tcx.mk_const_alloc(allocation);
133133
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
134134
}
@@ -138,7 +138,7 @@ fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>
138138
}
139139
(ast::LitKind::CStr(data, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) =>
140140
{
141-
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
141+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8], ());
142142
let allocation = tcx.mk_const_alloc(allocation);
143143
ConstValue::Slice { data: allocation, meta: allocation.inner().size().bytes() }
144144
}

compiler/rustc_mir_transform/src/large_enums.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ impl EnumSizeOpt {
241241
data,
242242
tcx.data_layout.ptr_sized_integer().align(&tcx.data_layout).abi,
243243
Mutability::Not,
244+
(),
244245
);
245246
let alloc = tcx.reserve_and_set_memory_alloc(tcx.mk_const_alloc(alloc));
246247
Some((*adt_def, num_discrs, *alloc_cache.entry(ty).or_insert(alloc)))

compiler/rustc_smir/src/rustc_smir/alloc.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ pub(crate) fn try_new_allocation<'tcx>(
4848
size,
4949
layout.align.abi,
5050
AllocInit::Uninit,
51+
(),
5152
);
5253
allocation
5354
.write_scalar(&tables.tcx, alloc_range(Size::ZERO, size), scalar)
@@ -65,6 +66,7 @@ pub(crate) fn try_new_allocation<'tcx>(
6566
layout.size,
6667
layout.align.abi,
6768
AllocInit::Uninit,
69+
(),
6870
);
6971
allocation
7072
.write_scalar(

src/tools/miri/src/alloc/alloc_bytes.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,8 @@ use rustc_middle::mir::interpret::AllocBytes;
99
use crate::alloc::discrete_alloc::MachineAlloc;
1010
use crate::helpers::ToU64 as _;
1111

12-
#[derive(Clone, Copy, Debug, Default)]
12+
#[derive(Clone, Copy, Debug)]
1313
pub enum MiriByteMdata {
14-
#[default]
1514
Global,
1615
Isolated,
1716
}
@@ -163,4 +162,8 @@ impl AllocBytes for MiriAllocBytes {
163162
fn as_ptr(&self) -> *const u8 {
164163
self.ptr
165164
}
165+
166+
fn get_mdata(&self) -> MiriByteMdata {
167+
self.dsc
168+
}
166169
}

src/tools/miri/src/alloc/discrete_alloc.rs

Lines changed: 17 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -25,38 +25,21 @@ pub struct MachineAlloc {
2525
allocated: Vec<Box<[u8]>>,
2626
/// The host (not emulated) page size.
2727
page_size: usize,
28-
/// If false, calls to `alloc()` and `alloc_zeroed()` just wrap the corresponding
29-
/// function in the global allocator. Otherwise, uses the pages tracked
30-
/// internally.
31-
enabled: bool,
3228
}
3329

3430
// SAFETY: We only point to heap-allocated data
3531
unsafe impl Send for MachineAlloc {}
3632

3733
impl MachineAlloc {
38-
/// Initializes the allocator. `page_size` is set to 4k as a placeholder to
39-
/// allow this function to be `const`; it is updated to its real value when
40-
/// `enable()` is called.
34+
/// Initializes the allocator. `page_size` is set to 0 as a placeholder to
35+
/// allow this function to be `const`; it is updated to its real value on
36+
/// the first call to `alloc()` or `alloc_zeroed()`.
4137
const fn empty() -> Self {
4238
Self {
4339
pages: Vec::new(),
4440
huge_allocs: Vec::new(),
4541
allocated: Vec::new(),
46-
page_size: 4096,
47-
enabled: true,
48-
}
49-
}
50-
51-
/// Enables the allocator. From this point onwards, calls to `alloc()` and
52-
/// `alloc_zeroed()` will return `(ptr, false)`.
53-
pub fn enable() {
54-
let mut alloc = ALLOCATOR.lock().unwrap();
55-
alloc.enabled = true;
56-
// This needs to specifically be the system pagesize!
57-
alloc.page_size = unsafe {
58-
// If sysconf errors, better to just panic
59-
libc::sysconf(libc::_SC_PAGE_SIZE).try_into().unwrap()
42+
page_size: 0,
6043
}
6144
}
6245

@@ -79,13 +62,9 @@ impl MachineAlloc {
7962
(size, align)
8063
}
8164

82-
/// Allocates memory as described in `Layout`. If `MachineAlloc::enable()`
83-
/// has *not* been called yet, this is just a wrapper for `(alloc::alloc(),
84-
/// true)`. Otherwise, it will allocate from its own memory pool and
85-
/// return `(ptr, false)`. The latter field is meant to correspond with the
86-
/// field `alloc_is_global` for `MiriAllocBytes`.
65+
/// Allocates memory as described in `Layout`.
8766
///
88-
/// SAFETY: See alloc::alloc()
67+
/// SAFETY: `See alloc::alloc()`
8968
#[inline]
9069
pub unsafe fn alloc(layout: Layout) -> *mut u8 {
9170
let mut alloc = ALLOCATOR.lock().unwrap();
@@ -94,21 +73,24 @@ impl MachineAlloc {
9473
}
9574
}
9675

97-
/// Same as `alloc()`, but zeroes out data before allocating. Instead
98-
/// wraps `alloc::alloc_zeroed()` if `MachineAlloc::enable()` has not been
99-
/// called yet.
76+
/// Same as `alloc()`, but zeroes out data before allocating.
10077
///
101-
/// SAFETY: See alloc::alloc_zeroed()
78+
/// SAFETY: See `alloc::alloc_zeroed()`
10279
pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
10380
let mut alloc = ALLOCATOR.lock().unwrap();
10481
unsafe { alloc.alloc_inner(layout, true) }
10582
}
10683

107-
/// SAFETY: The allocator must have been `enable()`d already and
108-
/// the `layout` must be valid.
84+
/// SAFETY: See `alloc::alloc()`
10985
unsafe fn alloc_inner(&mut self, layout: Layout, zeroed: bool) -> *mut u8 {
11086
let (size, align) = MachineAlloc::normalized_layout(layout);
11187

88+
if self.page_size == 0 {
89+
unsafe {
90+
self.page_size = libc::sysconf(libc::_SC_PAGESIZE).try_into().unwrap();
91+
}
92+
}
93+
11294
if align > self.page_size || size > self.page_size {
11395
unsafe { self.alloc_multi_page(layout, zeroed) }
11496
} else {
@@ -151,13 +133,10 @@ impl MachineAlloc {
151133
ret
152134
}
153135

154-
/// Deallocates a pointer from the machine allocator. While not unsound,
155-
/// attempting to deallocate a pointer if `MachineAlloc` has not been enabled
156-
/// will likely result in a panic.
136+
/// Deallocates a pointer from the isolated allocator.
157137
///
158138
/// SAFETY: This pointer must have been allocated with `MachineAlloc::alloc()`
159-
/// (or `alloc_zeroed()`) which must have returned `(ptr, false)` specifically!
160-
/// If it returned `(ptr, true)`, then deallocate it with `alloc::dealloc()` instead.
139+
/// (or `alloc_zeroed()`) with the same layout as the one passed.
161140
pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
162141
let mut alloc_guard = ALLOCATOR.lock().unwrap();
163142
// Doing it this way lets us grab 2 mutable references to different fields at once

0 commit comments

Comments
 (0)