use super::addresses::to_canonical_global;
use super::builds::Build;
use super::heap::{Chunk, heap_all, heap_chunks, read_u32};
pub(super) enum PointsTo {
Null,
Heap(usize, u32),
Global(u32),
Unresolved,
}
pub(super) struct Image<'a> {
pub(super) build: Build,
pub(super) mem: &'a [u8],
pub(super) chunks: Vec<Chunk>,
pub(super) all: Vec<(u32, u32, bool)>,
}
impl<'a> Image<'a> {
pub(super) fn new(mem: &'a [u8], build: Build) -> Result<Self, String> {
let all = heap_all(mem, build)?;
let chunks = heap_chunks(mem, build)?;
Ok(Image {
build,
mem,
chunks,
all,
})
}
pub(super) fn read(&self, a: u32) -> Option<u32> {
read_u32(self.mem, a)
}
pub(super) fn chunk_of(&self, v: u32) -> Option<usize> {
let i = self.chunks.partition_point(|c| c.user <= v);
let c = self.chunks.get(i.checked_sub(1)?)?;
(v - c.user < c.len).then_some(i - 1)
}
pub(super) fn classify(&self, v: u32) -> PointsTo {
if v == 0 {
return PointsTo::Null;
}
if let Some(ci) = self.chunk_of(v) {
return PointsTo::Heap(ci, v - self.chunks[ci].user);
}
match to_canonical_global(self.build, v) {
Some(g) => PointsTo::Global(g),
None => PointsTo::Unresolved,
}
}
pub(super) fn free_chunk_of(&self, v: u32) -> Option<(u32, u32)> {
let i = self.all.partition_point(|c| c.0 <= v);
let &(c, size, in_use) = self.all.get(i.checked_sub(1)?)?;
(!in_use && v >= c + 8 && v < c + size).then_some((c, size))
}
}