use rustc_hash::FxHashMap;
use crate::{
elf::{Rela64, SymbolTable, constants::STB_LOCAL},
linker::Context,
symbol::SymbolId,
};
#[derive(Clone, Copy, Debug)]
pub struct CieRef {
pub file: usize,
pub section: u16,
pub out_off: u64,
}
#[derive(PartialEq, Eq, Hash)]
struct CieReloc {
at: u64,
kind: u32,
addend: i64,
target: CieTarget,
}
#[derive(PartialEq, Eq, Hash)]
enum CieTarget {
Global(SymbolId),
Local(usize, u32),
}
#[derive(PartialEq, Eq, Hash)]
pub struct CieKey {
bytes: Vec<u8>,
relocs: Vec<CieReloc>,
}
impl CieKey {
pub fn new(
ctx: &Context<'_>,
symtab: &SymbolTable<'_>,
file: usize,
bytes: &[u8],
covering: &[(usize, u64, Rela64)],
) -> Option<Self> {
let mut relocs = Vec::with_capacity(covering.len());
for (_, at, r) in covering {
relocs.push(CieReloc {
at: *at,
kind: r.r_type(),
addend: r.r_addend.get(),
target: target_of(ctx, symtab, file, r.sym())?,
});
}
Some(Self {
bytes: bytes.to_vec(),
relocs,
})
}
}
fn target_of(
ctx: &Context<'_>,
symtab: &SymbolTable<'_>,
file: usize,
sym_idx: u32,
) -> Option<CieTarget> {
let sym = symtab.syms.get(sym_idx as usize)?;
if sym.bind() == STB_LOCAL {
return Some(CieTarget::Local(file, sym_idx));
}
let name = crate::symbol::version_stem(symtab.name(sym));
ctx.symbols.find(name).map(CieTarget::Global)
}
pub enum Claim {
Kept(usize),
Shared(CieRef),
}
#[derive(Default)]
pub struct CiePool {
seen: FxHashMap<CieKey, usize>,
refs: Vec<CieRef>,
}
impl CiePool {
pub fn claim(&mut self, key: CieKey, at: CieRef) -> Claim {
if let Some(found) =
self.seen.get(&key).and_then(|&slot| self.refs.get(slot))
{
return Claim::Shared(*found);
}
let slot = self.refs.len();
self.refs.push(at);
self.seen.insert(key, slot);
Claim::Kept(slot)
}
pub fn place(&mut self, slot: usize, out_off: u64) {
if let Some(found) = self.refs.get_mut(slot) {
found.out_off = out_off;
}
}
}