Skip to content

Commit 39e20f1

Browse files
committed
Auto merge of #86255 - Smittyvb:mir-alloc-oom, r=RalfJung,oli-obk
Support allocation failures when interpreting MIR This closes #79601 by handling the case where memory allocation fails during MIR interpretation, and translates that failure into an `InterpError`. The error message is "tried to allocate more memory than available to compiler" to make it clear that the memory shortage is happening at compile-time by the compiler itself, and that it is not a runtime issue. Now that memory allocation can fail, it would be neat if Miri could simulate low-memory devices to make it easy to see how much memory a Rust program needs. Note that this breaks Miri because it assumes that allocation can never fail.
2 parents 64ae15d + d83c46f commit 39e20f1

File tree

15 files changed

+96
-21
lines changed

15 files changed

+96
-21
lines changed

Diff for: compiler/rustc_middle/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
#![feature(associated_type_defaults)]
4949
#![feature(iter_zip)]
5050
#![feature(thread_local_const_init)]
51+
#![feature(try_reserve)]
5152
#![recursion_limit = "512"]
5253

5354
#[macro_use]

Diff for: compiler/rustc_middle/src/mir/interpret/allocation.rs

+27-6
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@ use std::ptr;
88

99
use rustc_ast::Mutability;
1010
use rustc_data_structures::sorted_map::SortedMap;
11+
use rustc_span::DUMMY_SP;
1112
use rustc_target::abi::{Align, HasDataLayout, Size};
1213

1314
use super::{
14-
read_target_uint, write_target_uint, AllocId, InterpError, Pointer, Scalar, ScalarMaybeUninit,
15-
UndefinedBehaviorInfo, UninitBytesAccess, UnsupportedOpInfo,
15+
read_target_uint, write_target_uint, AllocId, InterpError, InterpResult, Pointer,
16+
ResourceExhaustionInfo, Scalar, ScalarMaybeUninit, UndefinedBehaviorInfo, UninitBytesAccess,
17+
UnsupportedOpInfo,
1618
};
19+
use crate::ty;
1720

1821
/// This type represents an Allocation in the Miri/CTFE core engine.
1922
///
@@ -121,15 +124,33 @@ impl<Tag> Allocation<Tag> {
121124
Allocation::from_bytes(slice, Align::ONE, Mutability::Not)
122125
}
123126

124-
pub fn uninit(size: Size, align: Align) -> Self {
125-
Allocation {
126-
bytes: vec![0; size.bytes_usize()],
127+
/// Try to create an Allocation of `size` bytes, failing if there is not enough memory
128+
/// available to the compiler to do so.
129+
pub fn uninit(size: Size, align: Align, panic_on_fail: bool) -> InterpResult<'static, Self> {
130+
let mut bytes = Vec::new();
131+
bytes.try_reserve(size.bytes_usize()).map_err(|_| {
132+
// This results in an error that can happen non-deterministically, since the memory
133+
// available to the compiler can change between runs. Normally queries are always
134+
// deterministic. However, we can be non-determinstic here because all uses of const
135+
// evaluation (including ConstProp!) will make compilation fail (via hard error
136+
// or ICE) upon encountering a `MemoryExhausted` error.
137+
if panic_on_fail {
138+
panic!("Allocation::uninit called with panic_on_fail had allocation failure")
139+
}
140+
ty::tls::with(|tcx| {
141+
tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpreation")
142+
});
143+
InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted)
144+
})?;
145+
bytes.resize(size.bytes_usize(), 0);
146+
Ok(Allocation {
147+
bytes,
127148
relocations: Relocations::new(),
128149
init_mask: InitMask::new(size, false),
129150
align,
130151
mutability: Mutability::Mut,
131152
extra: (),
132-
}
153+
})
133154
}
134155
}
135156

Diff for: compiler/rustc_middle/src/mir/interpret/error.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,8 @@ pub enum ResourceExhaustionInfo {
423423
///
424424
/// The exact limit is set by the `const_eval_limit` attribute.
425425
StepLimitReached,
426+
/// There is not enough memory to perform an allocation.
427+
MemoryExhausted,
426428
}
427429

428430
impl fmt::Display for ResourceExhaustionInfo {
@@ -435,6 +437,9 @@ impl fmt::Display for ResourceExhaustionInfo {
435437
StepLimitReached => {
436438
write!(f, "exceeded interpreter step limit (see `#[const_eval_limit]`)")
437439
}
440+
MemoryExhausted => {
441+
write!(f, "tried to allocate more memory than available to compiler")
442+
}
438443
}
439444
}
440445
}
@@ -525,7 +530,8 @@ impl InterpError<'_> {
525530
use InterpError::*;
526531
match *self {
527532
MachineStop(ref err) => err.is_hard_err(),
528-
InterpError::UndefinedBehavior(_) => true,
533+
UndefinedBehavior(_) => true,
534+
ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) => true,
529535
_ => false,
530536
}
531537
}

Diff for: compiler/rustc_middle/src/ty/vtable.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ impl<'tcx> TyCtxt<'tcx> {
6060
let ptr_align = tcx.data_layout.pointer_align.abi;
6161

6262
let vtable_size = ptr_size * u64::try_from(vtable_entries.len()).unwrap();
63-
let mut vtable = Allocation::uninit(vtable_size, ptr_align);
63+
let mut vtable =
64+
Allocation::uninit(vtable_size, ptr_align, /* panic_on_fail */ true).unwrap();
6465

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

Diff for: compiler/rustc_mir/src/const_eval/eval_queries.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(
4848
);
4949
let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
5050
assert!(!layout.is_unsized());
51-
let ret = ecx.allocate(layout, MemoryKind::Stack);
51+
let ret = ecx.allocate(layout, MemoryKind::Stack)?;
5252

5353
let name =
5454
with_no_trimmed_paths(|| ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id())));

Diff for: compiler/rustc_mir/src/const_eval/machine.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
201201

202202
type MemoryExtra = MemoryExtra;
203203

204+
const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
205+
204206
fn load_mir(
205207
ecx: &InterpCx<'mir, 'tcx, Self>,
206208
instance: ty::InstanceDef<'tcx>,
@@ -306,7 +308,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
306308
Size::from_bytes(size as u64),
307309
align,
308310
interpret::MemoryKind::Machine(MemoryKind::Heap),
309-
);
311+
)?;
310312
ecx.write_scalar(Scalar::Ptr(ptr), dest)?;
311313
}
312314
_ => {

Diff for: compiler/rustc_mir/src/interpret/intern.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ impl<'mir, 'tcx: 'mir, M: super::intern::CompileTimeMachine<'mir, 'tcx, !>>
428428
&MPlaceTy<'tcx, M::PointerTag>,
429429
) -> InterpResult<'tcx, ()>,
430430
) -> InterpResult<'tcx, &'tcx Allocation> {
431-
let dest = self.allocate(layout, MemoryKind::Stack);
431+
let dest = self.allocate(layout, MemoryKind::Stack)?;
432432
f(self, &dest)?;
433433
let ptr = dest.ptr.assert_ptr();
434434
assert_eq!(ptr.offset, Size::ZERO);

Diff for: compiler/rustc_mir/src/interpret/intrinsics/caller_location.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
9191
.type_of(self.tcx.require_lang_item(LangItem::PanicLocation, None))
9292
.subst(*self.tcx, self.tcx.mk_substs([self.tcx.lifetimes.re_erased.into()].iter()));
9393
let loc_layout = self.layout_of(loc_ty).unwrap();
94-
let location = self.allocate(loc_layout, MemoryKind::CallerLocation);
94+
// This can fail if rustc runs out of memory right here. Trying to emit an error would be
95+
// pointless, since that would require allocating more memory than a Location.
96+
let location = self.allocate(loc_layout, MemoryKind::CallerLocation).unwrap();
9597

9698
// Initialize fields.
9799
self.write_immediate(file.to_ref(), &self.mplace_field(&location, 0).unwrap().into())

Diff for: compiler/rustc_mir/src/interpret/machine.rs

+3
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ pub trait Machine<'mir, 'tcx>: Sized {
122122
/// that is added to the memory so that the work is not done twice.
123123
const GLOBAL_KIND: Option<Self::MemoryKind>;
124124

125+
/// Should the machine panic on allocation failures?
126+
const PANIC_ON_ALLOC_FAIL: bool;
127+
125128
/// Whether memory accesses should be alignment-checked.
126129
fn enforce_alignment(memory_extra: &Self::MemoryExtra) -> bool;
127130

Diff for: compiler/rustc_mir/src/interpret/memory.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,9 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
207207
size: Size,
208208
align: Align,
209209
kind: MemoryKind<M::MemoryKind>,
210-
) -> Pointer<M::PointerTag> {
211-
let alloc = Allocation::uninit(size, align);
212-
self.allocate_with(alloc, kind)
210+
) -> InterpResult<'static, Pointer<M::PointerTag>> {
211+
let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?;
212+
Ok(self.allocate_with(alloc, kind))
213213
}
214214

215215
pub fn allocate_bytes(
@@ -257,7 +257,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
257257

258258
// For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
259259
// This happens so rarely, the perf advantage is outweighed by the maintenance cost.
260-
let new_ptr = self.allocate(new_size, new_align, kind);
260+
let new_ptr = self.allocate(new_size, new_align, kind)?;
261261
let old_size = match old_size_and_align {
262262
Some((size, _align)) => size,
263263
None => self.get_raw(ptr.alloc_id)?.size(),

Diff for: compiler/rustc_mir/src/interpret/place.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -982,7 +982,7 @@ where
982982
let (size, align) = self
983983
.size_and_align_of(&meta, &local_layout)?
984984
.expect("Cannot allocate for non-dyn-sized type");
985-
let ptr = self.memory.allocate(size, align, MemoryKind::Stack);
985+
let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?;
986986
let mplace = MemPlace { ptr: ptr.into(), align, meta };
987987
if let LocalValue::Live(Operand::Immediate(value)) = local_val {
988988
// Preserve old value.
@@ -1018,9 +1018,9 @@ where
10181018
&mut self,
10191019
layout: TyAndLayout<'tcx>,
10201020
kind: MemoryKind<M::MemoryKind>,
1021-
) -> MPlaceTy<'tcx, M::PointerTag> {
1022-
let ptr = self.memory.allocate(layout.size, layout.align.abi, kind);
1023-
MPlaceTy::from_aligned_ptr(ptr, layout)
1021+
) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> {
1022+
let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?;
1023+
Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
10241024
}
10251025

10261026
/// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation.

Diff for: compiler/rustc_mir/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Rust MIR: a lowered representation of Rust.
2929
#![feature(option_get_or_insert_default)]
3030
#![feature(once_cell)]
3131
#![feature(control_flow_enum)]
32+
#![feature(try_reserve)]
3233
#![recursion_limit = "256"]
3334

3435
#[macro_use]

Diff for: compiler/rustc_mir/src/transform/const_prop.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
181181

182182
impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
183183
compile_time_machine!(<'mir, 'tcx>);
184+
const PANIC_ON_ALLOC_FAIL: bool = true; // all allocations are small (see `MAX_ALLOC_LIMIT`)
184185

185186
type MemoryKind = !;
186187

@@ -393,7 +394,11 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
393394
.filter(|ret_layout| {
394395
!ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
395396
})
396-
.map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack).into());
397+
.map(|ret_layout| {
398+
ecx.allocate(ret_layout, MemoryKind::Stack)
399+
.expect("couldn't perform small allocation")
400+
.into()
401+
});
397402

398403
ecx.push_stack_frame(
399404
Instance::new(def_id, substs),

Diff for: src/test/ui/consts/large_const_alloc.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// only-64bit
2+
// on 32bit and 16bit platforms it is plausible that the maximum allocation size will succeed
3+
4+
const FOO: () = {
5+
// 128 TiB, unlikely anyone has that much RAM
6+
let x = [0_u8; (1 << 47) - 1];
7+
//~^ ERROR evaluation of constant value failed
8+
};
9+
10+
static FOO2: () = {
11+
let x = [0_u8; (1 << 47) - 1];
12+
//~^ ERROR could not evaluate static initializer
13+
};
14+
15+
fn main() {
16+
let _ = FOO;
17+
let _ = FOO2;
18+
}

Diff for: src/test/ui/consts/large_const_alloc.stderr

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error[E0080]: evaluation of constant value failed
2+
--> $DIR/large_const_alloc.rs:6:13
3+
|
4+
LL | let x = [0_u8; (1 << 47) - 1];
5+
| ^^^^^^^^^^^^^^^^^^^^^ tried to allocate more memory than available to compiler
6+
7+
error[E0080]: could not evaluate static initializer
8+
--> $DIR/large_const_alloc.rs:11:13
9+
|
10+
LL | let x = [0_u8; (1 << 47) - 1];
11+
| ^^^^^^^^^^^^^^^^^^^^^ tried to allocate more memory than available to compiler
12+
13+
error: aborting due to 2 previous errors
14+
15+
For more information about this error, try `rustc --explain E0080`.

0 commit comments

Comments
 (0)