use super::builds::Build;
use super::tables::*;
#[derive(Debug, Clone, Copy)]
pub struct Chunk {
pub user: u32,
pub len: u32,
}
pub(super) fn read_u32(mem: &[u8], a: u32) -> Option<u32> {
Some(u32::from_le_bytes(
mem.get(a as usize..a as usize + 4)?.try_into().ok()?,
))
}
pub fn heap_chunks(mem: &[u8], build: Build) -> Result<Vec<Chunk>, String> {
Ok(heap_all(mem, build)?
.into_iter()
.filter(|c| c.2)
.map(|c| Chunk {
user: c.0 + 8,
len: c.1 - 4,
})
.collect())
}
pub fn heap_all(mem: &[u8], build: Build) -> Result<Vec<(u32, u32, bool)>, String> {
let gm = GM[build.index()];
let (Some(least), Some(top)) = (read_u32(mem, gm + 16), read_u32(mem, gm + 24)) else {
return Err("memory too short for the allocator state".into());
};
let mut out = Vec::new();
let mut c = least;
while c < top {
let head = read_u32(mem, c + 4).ok_or("chunk past the end of memory")?;
let size = head & !7;
if size < 16 || c + size > top {
return Err(format!("corrupt chunk at {c:#x} (size {size})"));
}
let next = c + size;
let next_head = read_u32(mem, next + 4).ok_or("chunk past the end of memory")?;
out.push((c, size, next_head & 1 != 0));
c = next;
}
if c != top {
return Err(format!(
"heap walk ended at {c:#x}, not at its top {top:#x}"
));
}
Ok(out)
}