report apu heap allocations that fail (#1720)

This commit is contained in:
prism authored and GitHub committed 2026-11-25 22:51:12 +01:00 Unverified
1 parent cc7ec2a531
commit deb05ab989
2 files changed
+112 -20

No files matched your search

+53 -10
View File
@@ -100,21 +100,55 @@ impl Heap {
}
}
/// Why the APU heap could not give a block.
#[derive(Debug)]
enum HeapRefusal {
/// No free device-address range fits the request.
NoDeviceRange { size: usize, align: usize },
/// The host allocator returned null for the block.
HostAllocator { len_bytes: usize },
}
impl HeapRefusal {
/// Reports the refusal. Called with no lock held: a host refusal is
/// written to `crashes.log`, so its cause is on record if the title fails
/// after it.
fn report(&self) {
match *self {
Self::NoDeviceRange { size, align } => tracing::warn!(
size,
align,
"no free APU device-address range fits the request"
),
Self::HostAllocator { len_bytes } => super::xmem::report_allocator_refusal(len_bytes),
}
}
}
/// Zeroed host memory and its device address.
fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> {
let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?;
fn heap_alloc(size: usize, align: usize) -> Result<(*mut u8, u32), HeapRefusal> {
let mut heap = lock(&HEAP);
let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?;
let fit = Layout::from_size_align(size.max(1), align.max(16))
.ok()
.and_then(|layout| {
let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?;
Some((layout, apu))
});
let Some((layout, apu)) = fit else {
return Err(HeapRefusal::NoDeviceRange { size, align });
};
// SAFETY: non-zero size.
let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
if ptr.is_null() {
heap.give_back(apu, apu + layout.size() as u32);
return None;
return Err(HeapRefusal::HostAllocator {
len_bytes: layout.size(),
});
}
heap.blocks
.insert(ptr as usize, Block { size, apu, layout });
heap.by_apu.insert(apu, ptr as usize);
Some((ptr, apu))
Ok((ptr, apu))
}
fn heap_free(ptr: *mut u8) {
@@ -195,8 +229,12 @@ pub extern "system" fn ApuAlloc(
if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() {
return E_INVALIDARG;
}
let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else {
return E_OUTOFMEMORY;
let (ptr, address) = match heap_alloc(size as usize, align as usize) {
Ok(block) => block,
Err(refusal) => {
refusal.report();
return E_OUTOFMEMORY;
}
};
// SAFETY: checked non-null; optional out parameter checked below.
unsafe {
@@ -254,9 +292,14 @@ pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts)
if counts[i] == 0 {
continue;
}
let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else {
arrays.iter().for_each(|&p| heap_free(p.cast()));
return E_OUTOFMEMORY;
let (ptr, apu) = match heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) {
Ok(block) => block,
Err(refusal) => {
arrays.iter().for_each(|&p| heap_free(p.cast()));
drop(allocated);
refusal.report();
return E_OUTOFMEMORY;
}
};
(arrays[i], addresses[i]) = (ptr.cast(), apu);
}
+59 -10
View File
@@ -866,32 +866,64 @@ fn commit(base: usize, len: usize) -> bool {
/// gets; otherwise as a warning.
fn commit_refused(len: usize, what: &str, error: std::io::Error) {
if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) {
let mut info = PERFORMANCE_INFORMATION {
cb: size_of::<PERFORMANCE_INFORMATION>() as u32,
..Default::default()
};
// SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION.
let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0;
victory_loader::log_crash(&commit_limit_message(
len,
what,
&error,
queried.then_some(&info),
system_commit().as_ref(),
));
} else {
tracing::warn!(len, %error, "committing {what} failed");
}
}
/// Reports to `crashes.log` that the host allocator refused `len_bytes` of
/// APU heap memory. There is no Windows error code to give: `std::alloc`
/// allocates with `HeapAlloc`, which does not set one when it fails.
pub(crate) fn report_allocator_refusal(len_bytes: usize) {
victory_loader::log_crash(&allocator_refusal_message(
len_bytes,
system_commit().as_ref(),
));
}
/// The system commit, if Windows reports it.
fn system_commit() -> Option<PERFORMANCE_INFORMATION> {
let mut info = PERFORMANCE_INFORMATION {
cb: size_of::<PERFORMANCE_INFORMATION>() as u32,
..Default::default()
};
// SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION.
(unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0).then_some(info)
}
fn commit_limit_message(
len: usize,
what: &str,
error: &std::io::Error,
info: Option<&PERFORMANCE_INFORMATION>,
) -> String {
let mut message = format!(
"VIctory: Windows commit limit reached while committing {len} bytes of {what}: {error}.\n"
);
refusal_message(
format_args!(
"Windows commit limit reached while committing {len} bytes of {what}: {error}"
),
info,
)
}
fn allocator_refusal_message(len_bytes: usize, info: Option<&PERFORMANCE_INFORMATION>) -> String {
refusal_message(
format_args!("the host allocator refused {len_bytes} bytes of APU heap memory"),
info,
)
}
/// What the host refused, then the system commit and what the user can do.
fn refusal_message(
refusal: std::fmt::Arguments<'_>,
info: Option<&PERFORMANCE_INFORMATION>,
) -> String {
let mut message = format!("VIctory: {refusal}.\n");
if let Some(info) = info {
use std::fmt::Write;
@@ -1173,6 +1205,23 @@ mod tests {
assert!(!fallback.contains("System commit:"));
}
#[test]
fn allocator_refusal_report_names_apu_heap_and_system_commit() {
let info = PERFORMANCE_INFORMATION {
CommitTotal: 512,
CommitLimit: 768,
PageSize: 4096,
..Default::default()
};
let report = allocator_refusal_message(4 * MIB, Some(&info));
assert!(report.contains("host allocator refused 4194304 bytes of APU heap memory"));
assert!(report.contains("System commit: 2 MiB of 3 MiB in use"));
assert!(report.contains("Windows paging file size"));
let fallback = allocator_refusal_message(4 * MIB, None);
assert!(fallback.contains("4194304 bytes of APU heap memory"));
assert!(!fallback.contains("System commit:"));
}
#[test]
fn physical_pages_map_alias_and_unmap() {
let mut pages = [0usize; 3];