use rustc_hash::FxHashMap;
use crate::{
error::Result,
macho::{
MachOFile,
constants::N_EXT,
layout::is_linkable,
reloc::{MachoTarget, scan_needs},
},
};
pub struct GotPlan<'d> {
keys: Vec<GotKey<'d>>,
index: FxHashMap<GotKey<'d>, u32>,
}
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum GotKey<'d> {
Global(&'d [u8]),
Local { file: usize, sym: u32 },
}
impl<'d> GotPlan<'d> {
pub fn scan(
inputs: &'d [MachOFile<'d>],
target: MachoTarget,
) -> Result<Self> {
let mut keys: Vec<GotKey<'d>> = Vec::new();
let mut index: FxHashMap<GotKey<'d>, u32> = FxHashMap::default();
for (file, input) in inputs.iter().enumerate() {
let sym_keys: Vec<GotKey<'d>> = input
.symbols()
.iter()
.enumerate()
.map(|(i, s)| key_of(file, i, s.name, s.n_type & N_EXT != 0))
.collect();
for section in input.sections() {
if !is_linkable(§ion) {
continue;
}
for reloc in §ion.relocations {
if !reloc.r_extern {
continue;
}
let needs = scan_needs(target, u32::from(reloc.r_type))?;
if !needs.got {
continue;
}
let Some(&key) = sym_keys.get(reloc.r_symbolnum as usize)
else {
continue;
};
if matches!(key, GotKey::Global(n) if n.is_empty())
|| index.contains_key(&key)
{
continue;
}
let slot = u32::try_from(keys.len()).unwrap_or(u32::MAX);
index.insert(key, slot);
keys.push(key);
}
}
}
Ok(Self { keys, index })
}
pub fn count(&self) -> u32 {
u32::try_from(self.keys.len()).unwrap_or(u32::MAX)
}
pub fn ensure_global(&mut self, name: &'d [u8]) -> u32 {
let key = GotKey::Global(name);
if let Some(&slot) = self.index.get(&key) {
return slot;
}
let slot = u32::try_from(self.keys.len()).unwrap_or(u32::MAX);
self.index.insert(key, slot);
self.keys.push(key);
slot
}
pub fn global_slot(&self, name: &[u8]) -> Option<u32> {
self.index.get(&GotKey::Global(name)).copied()
}
pub fn slot(
&self,
file: usize,
sym: usize,
name: &'d [u8],
external: bool,
) -> Option<u32> {
self.index.get(&key_of(file, sym, name, external)).copied()
}
pub fn iter(&self) -> impl Iterator<Item = (u32, GotKey<'d>)> {
self.keys
.iter()
.enumerate()
.map(|(i, &k)| (u32::try_from(i).unwrap_or(u32::MAX), k))
}
}
fn key_of(file: usize, sym: usize, name: &[u8], external: bool) -> GotKey<'_> {
if external {
GotKey::Global(name)
} else {
GotKey::Local {
file,
sym: u32::try_from(sym).unwrap_or(u32::MAX),
}
}
}