summaryrefslogtreecommitdiffstats
path: root/rsnix/src/memory.rs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--rsnix/src/memory.rs142
1 files changed, 142 insertions, 0 deletions
diff --git a/rsnix/src/memory.rs b/rsnix/src/memory.rs
index 35f3464..3362d94 100644
--- a/rsnix/src/memory.rs
+++ b/rsnix/src/memory.rs
@@ -1,5 +1,6 @@
1use crate::uefi::*; 1use crate::uefi::*;
2use core::alloc::{GlobalAlloc, Layout}; 2use core::alloc::{GlobalAlloc, Layout};
3use core::fmt;
3use core::mem; 4use core::mem;
4use core::ptr; 5use core::ptr;
5 6
@@ -304,6 +305,22 @@ unsafe impl GlobalAlloc for Allocator {
304 return; 305 return;
305 } 306 }
306 unsafe { 307 unsafe {
308 // Real-hardware corruption guard: the back-pointer at [ptr-8]
309 // must point at a sane block header inside the heap. A
310 // garbage back-pointer (heap/stack corruption clobbered the
311 // block header, or the caller passed a bogus pointer) used to
312 // turn into a #GP on the store below — now it turns into a
313 // readable report + halt instead.
314 let p = ptr as usize;
315 if !back_pointer_ok(p) {
316 let rsp: usize;
317 core::arch::asm!(
318 "mov {}, rsp",
319 out(reg) rsp,
320 options(nostack, preserves_flags)
321 );
322 heap_guard_report(p, rsp);
323 }
307 let block = *((ptr as *const usize).sub(1)) as *mut Header; 324 let block = *((ptr as *const usize).sub(1)) as *mut Header;
308 debug_assert!( 325 debug_assert!(
309 (*block).free == 0, 326 (*block).free == 0,
@@ -320,6 +337,131 @@ unsafe impl GlobalAlloc for Allocator {
320#[global_allocator] 337#[global_allocator]
321static ALLOCATOR: Allocator = Allocator; 338static ALLOCATOR: Allocator = Allocator;
322 339
340/// Current kernel-heap extent, if the heap has been initialised.
341pub(crate) fn heap_range() -> Option<(usize, usize)> {
342 unsafe {
343 if HEAP_END > HEAP_START {
344 Some((HEAP_START, HEAP_END))
345 } else {
346 None
347 }
348 }
349}
350
351/// True when `[ptr-8]` holds a plausible back-pointer: the *value* there
352/// must be a block address inside the heap whose header size is sane and
353/// whose free flag says the block is still allocated (a block being freed
354/// must be in-use).
355unsafe fn back_pointer_ok(ptr: usize) -> bool {
356 unsafe {
357 let Some((hs, he)) = heap_range() else {
358 return true; // heap not initialised yet — trust the pointer
359 };
360 let slot = ptr.wrapping_sub(8);
361 if slot < hs || slot >= he {
362 // The slot itself is outside the heap — can't even read it
363 // safely (a garbage ptr reads random memory).
364 return false;
365 }
366 let block = *(slot as *const usize);
367 if block < hs || block >= he {
368 return false; // back-pointer points outside the heap
369 }
370 let size = *(block as *const usize);
371 let free = *((block + 8) as *const usize);
372 size >= MIN_BLOCK && block + size <= he && free == 0
373 }
374}
375
376/// Heap-corruption report, called from `dealloc` when the back-pointer
377/// check fails. Heap-free by construction (we ARE the allocator): raw
378/// serial, the crash band, crash.log, then halt.
379fn heap_guard_report(ptr: usize, rsp: usize) -> ! {
380 let (hs, he) = heap_range().unwrap_or((0, 0));
381 let block = if ptr >= hs + 8 && ptr <= he { unsafe { *(ptr.wrapping_sub(8) as *const usize) } } else { 0 };
382
383 let mut b1 = [0u8; 96];
384 let n1 = {
385 let mut w = crate::strbuf::FmtBuf::new(&mut b1);
386 let _ = fmt::write(&mut w, core::format_args!("!!! heap corruption in dealloc"));
387 w.len()
388 };
389 let mut b2 = [0u8; 96];
390 let n2 = {
391 let mut w = crate::strbuf::FmtBuf::new(&mut b2);
392 let _ = fmt::write(&mut w, core::format_args!("ptr={:#x} block={:#x}", ptr, block));
393 w.len()
394 };
395 let mut b3 = [0u8; 96];
396 let n3 = {
397 let mut w = crate::strbuf::FmtBuf::new(&mut b3);
398 let _ = fmt::write(
399 &mut w,
400 core::format_args!("heap={:#x}..{:#x} rsp={:#x}", hs, he, rsp),
401 );
402 w.len()
403 };
404
405 // Words around the block header — the corruption lives in the
406 // header's size/free slots or the payload. Only when the addresses
407 // are inside the mapped heap (reading a garbage pointer would fault
408 // mid-report).
409 let mut b4 = [0u8; 216];
410 let n4 = {
411 let mut w = crate::strbuf::FmtBuf::new(&mut b4);
412 let focus = if block >= hs && block < he { block } else { ptr };
413 if focus >= hs + 8 && focus < he {
414 let lo = (focus - 16).max(hs);
415 let hi = (focus + 40).min(he - 8);
416 let _ = fmt::write(&mut w, core::format_args!("mem:"));
417 let mut a = lo & !7;
418 while a <= hi {
419 let _ = fmt::write(
420 &mut w,
421 core::format_args!(" {:x}={:#x}", a, unsafe { *(a as *const usize) }),
422 );
423 a += 8;
424 }
425 } else {
426 let _ = fmt::write(&mut w, core::format_args!("mem: out of heap — no dump"));
427 }
428 w.len()
429 };
430
431 // Live return-address chain on the stack above our rsp (dealloc ←
432 // drop glue ← shell::run); raw stack words, resolves against the PDB.
433 let mut b5 = [0u8; 216];
434 let n5 = {
435 let mut w = crate::strbuf::FmtBuf::new(&mut b5);
436 let _ = fmt::write(&mut w, core::format_args!("stk:"));
437 let mut a = rsp.wrapping_add(8);
438 for _ in 0..12 {
439 let v = unsafe { *(a as *const usize) };
440 let _ = fmt::write(&mut w, core::format_args!(" {:x}={:#x}", a, v));
441 a += 8;
442 }
443 w.len()
444 };
445
446 let l1 = core::str::from_utf8(&b1[..n1]).unwrap_or("!!!");
447 let l2 = core::str::from_utf8(&b2[..n2]).unwrap_or("");
448 let l3 = core::str::from_utf8(&b3[..n3]).unwrap_or("");
449 let l4 = core::str::from_utf8(&b4[..n4]).unwrap_or("");
450 let l5 = core::str::from_utf8(&b5[..n5]).unwrap_or("");
451 crate::serial::write_raw(l2);
452 crate::serial::write_raw("\r\n");
453 crate::serial::write_raw(l3);
454 crate::serial::write_raw("\r\n");
455 crate::serial::write_raw(l4);
456 crate::serial::write_raw("\r\n");
457 crate::serial::write_raw(l5);
458 crate::serial::write_raw("\r\n");
459 let lines = [l1, l2, l3, l4, l5];
460 crate::gop::dump_lines(&lines);
461 crate::fs::write_crash_log(&lines);
462 crate::interrupts::halt()
463}
464
323/// Capture the UEFI memory map into the static buffer. Uses a pre-allocated 465/// Capture the UEFI memory map into the static buffer. Uses a pre-allocated
324/// .bss working buffer so no pool allocation (and thus no memory-map change) 466/// .bss working buffer so no pool allocation (and thus no memory-map change)
325/// occurs between GetMemoryMap and ExitBootServices. 467/// occurs between GetMemoryMap and ExitBootServices.