use rustc_hash::FxHashSet;
use crate::{
error::Result, gc::reloc_target, linker::Context, output::OutKind,
};
pub fn sections_with_lsda(
ctx: &Context<'_>,
) -> Result<FxHashSet<(usize, u16)>> {
let mut out = FxHashSet::default();
let Some(eh) = ctx.outputs.section(OutKind::EhFrame) else {
return Ok(out);
};
let mut pieces = Vec::new();
let mut fde = Vec::new();
for m in &eh.members {
scan_member(ctx, m.file, m.section, &mut pieces, &mut fde, &mut out)?;
}
Ok(out)
}
fn scan_member(
ctx: &Context<'_>,
file: usize,
section: u16,
pieces: &mut Vec<super::Piece>,
fde: &mut Vec<bool>,
out: &mut FxHashSet<(usize, u16)>,
) -> Result<()> {
let Some(input) = ctx.files.get(file) else {
return Ok(());
};
let obj = input.object()?;
let Some(shdr) = obj.sections().get(usize::from(section)) else {
return Ok(());
};
let data = obj.section_data(shdr)?;
super::records(data, pieces, fde);
let Some(symtab) = input.symbol_table()? else {
return Ok(());
};
let Some(entries) = input.relocations(section)? else {
return Ok(());
};
let with_lsda = cies_with_lsda(data, pieces)?;
if with_lsda.is_empty() {
return Ok(());
}
let first = super::first_reloc_syms(pieces, entries);
for (i, piece) in pieces.iter().enumerate() {
let Some(cie) = super::cie_offset_of(data, *piece) else {
continue;
};
if !with_lsda.contains(&cie) {
continue;
}
let Some(Some(sym_idx)) = first.get(i).copied() else {
continue;
};
if let Some(target) = reloc_target(ctx, &symtab, file, sym_idx) {
out.insert(target);
}
}
Ok(())
}
fn cies_with_lsda(
data: &[u8],
pieces: &[super::Piece],
) -> Result<FxHashSet<u64>> {
let mut out = FxHashSet::default();
for piece in pieces {
if piece.fde {
continue;
}
let Ok(start) = usize::try_from(piece.in_off) else {
continue;
};
let end = start
.saturating_add(usize::try_from(piece.len).unwrap_or(usize::MAX));
if super::cie_augmentation(data, start, end.min(data.len()))?.has_lsda {
out.insert(piece.in_off);
}
}
Ok(out)
}