use rayon::prelude::*;
use crate::{
elf::{
Shdr64, Sym64,
constants::{
SHF_ALLOC, SHF_MERGE, SHN_ABS, SHN_LORESERVE, SHN_UNDEF, STB_LOCAL,
STT_SECTION, STT_TLS,
},
},
error::Result,
input::InputFile,
layout::Layout,
linker::Context,
};
pub(super) struct LocalSym<'a> {
pub(super) name: &'a [u8],
pub(super) value: u64,
pub(super) size: u64,
pub(super) info: u8,
pub(super) other: u8,
pub(super) shndx: u16,
}
pub(super) fn collect<'a>(
ctx: &'a Context<'_>,
layout: &Layout,
) -> Result<Vec<LocalSym<'a>>> {
let per_file: Vec<Vec<LocalSym<'a>>> = ctx
.files
.par_iter()
.enumerate()
.map(|(file, input)| collect_file(ctx, layout, file, input))
.collect::<Result<Vec<_>>>()?;
Ok(per_file.into_iter().flatten().collect())
}
fn collect_file<'a>(
ctx: &'a Context<'_>,
layout: &Layout,
file: usize,
input: &'a InputFile<'_>,
) -> Result<Vec<LocalSym<'a>>> {
let Some(symtab) = input.symbol_table()? else {
return Ok(Vec::new());
};
let sections = input.object()?.sections();
let tls_base = layout.tls_block().map_or(0, |b| b.vaddr);
let mut out = Vec::new();
for sym in symtab.syms {
if sym.bind() != STB_LOCAL || sym.type_() == STT_SECTION {
continue;
}
let name = symtab.name(sym);
let Some((value, shndx)) =
place(ctx, layout, file, sections, sym, name, tls_base)
else {
continue;
};
out.push(LocalSym {
name,
value,
size: sym.st_size.get(),
info: sym.st_info,
other: sym.st_other,
shndx,
});
}
Ok(out)
}
fn place(
ctx: &Context<'_>,
layout: &Layout,
file: usize,
sections: &[Shdr64],
sym: &Sym64,
name: &[u8],
tls_base: u64,
) -> Option<(u64, u16)> {
let shndx = sym.st_shndx.get();
if shndx == SHN_ABS {
return Some((sym.st_value.get(), SHN_ABS));
}
if shndx == SHN_UNDEF || shndx >= SHN_LORESERVE {
return None;
}
let flags = sections.get(usize::from(shndx))?.sh_flags.get();
if flags & SHF_ALLOC == 0 {
return None;
}
let out_shndx = layout.section_shndx(file, shndx)?;
let base = layout.section_vaddr(file, shndx)?;
if flags & SHF_MERGE != 0 && name.starts_with(b".L") {
return None;
}
let offset = sym.st_value.get();
let moved = ctx.merge.remap(file, shndx, offset).unwrap_or(offset);
let addr = base.wrapping_add(moved);
let value = if sym.type_() == STT_TLS {
addr.wrapping_sub(tls_base)
} else {
addr
};
Some((value, out_shndx))
}