use crate::{elf::Shdr64, util::align_up};
pub fn is_debug_section(name: &[u8]) -> bool {
name.starts_with(DEBUG_PREFIX)
}
pub const DEBUG_PREFIX: &[u8] = b".debug";
pub const ZDEBUG_PREFIX: &[u8] = b".zdebug";
#[derive(Copy, Clone, Debug)]
pub struct DebugMember {
pub file: usize,
pub section: u16,
pub size: u64,
pub out_offset: u64,
}
#[derive(Debug)]
pub struct DebugSection {
pub name: Vec<u8>,
pub sh_type: u32,
pub sh_flags: u64,
pub entsize: u64,
pub align: u64,
pub size: u64,
pub members: Vec<DebugMember>,
}
#[derive(Default, Debug)]
pub struct DebugSections {
pub sections: Vec<DebugSection>,
}
impl DebugSections {
pub fn new() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.sections.is_empty()
}
pub fn add(
&mut self,
file: usize,
section: u16,
shdr: &Shdr64,
name: &[u8],
) {
let align = shdr.sh_addralign.get().max(1);
let idx = if let Some(i) =
self.sections.iter().position(|s| s.name == name)
{
i
} else {
self.sections.push(DebugSection {
name: name.to_vec(),
sh_type: shdr.sh_type.get(),
sh_flags: shdr.sh_flags.get(),
entsize: shdr.sh_entsize.get(),
align: 1,
size: 0,
members: Vec::new(),
});
self.sections.len() - 1
};
let out = &mut self.sections[idx];
let cursor = align_up(out.size, align);
out.members.push(DebugMember {
file,
section,
size: shdr.sh_size.get(),
out_offset: cursor,
});
out.size = cursor.saturating_add(shdr.sh_size.get());
if align > out.align {
out.align = align;
}
}
pub fn relayout(&mut self, size_of: impl Fn(usize, u16) -> Option<u64>) {
for out in &mut self.sections {
let mut cursor = 0u64;
for m in &mut out.members {
if let Some(size) = size_of(m.file, m.section) {
m.size = size;
}
m.out_offset = cursor;
cursor = cursor.saturating_add(m.size);
}
out.size = cursor;
}
}
}