use std::path::{Path, PathBuf};
use crate::{
elf::{
Group, ObjectFile, Rela64, Relocs, Shdr64,
constants::{
SHN_ABS, SHN_COMMON, SHN_LORESERVE, SHN_UNDEF, SHN_XINDEX,
STB_LOCAL,
},
},
endian::U64,
error::{Error, Result},
mmap_file::{MappedFile, OpenedFile},
};
#[derive(Clone, Copy)]
pub enum Input<'data> {
Path(&'data Path),
Library(&'data Path),
AsNeeded { path: &'data Path, from_l: bool },
Memory {
name: &'data Path,
bytes: &'data [u8],
},
}
impl<'data> Input<'data> {
pub fn from_paths(paths: &'data [PathBuf]) -> Vec<Self> {
paths.iter().map(|p| Self::Path(p)).collect()
}
pub const fn name(&self) -> &'data Path {
match *self {
Self::Path(path)
| Self::Library(path)
| Self::AsNeeded { path, .. } => path,
Self::Memory { name, .. } => name,
}
}
pub const fn is_library_search(&self) -> bool {
matches!(
*self,
Self::Library(_) | Self::AsNeeded { from_l: true, .. }
)
}
pub const fn is_as_needed(&self) -> bool {
matches!(*self, Self::AsNeeded { .. })
}
pub fn open(&self) -> Result<InputBytes<'data>> {
self.open_with(self.open_file()?)
}
pub fn open_file(&self) -> Result<Option<OpenedFile>> {
match *self {
Self::Path(path)
| Self::Library(path)
| Self::AsNeeded { path, .. } => {
MappedFile::open_file(path).map(Some)
}
Self::Memory { .. } => Ok(None),
}
}
pub fn open_with(
&self,
file: Option<OpenedFile>,
) -> Result<InputBytes<'data>> {
match (*self, file) {
(
Self::Path(path)
| Self::Library(path)
| Self::AsNeeded { path, .. },
Some(file),
) => Ok(InputBytes::Mapped(MappedFile::map(path, &file)?)),
(Self::Memory { bytes, .. }, _) if is_parse_aligned(bytes) => {
Ok(InputBytes::Borrowed(bytes))
}
(Self::Memory { bytes, .. }, _) => {
Ok(InputBytes::Owned(AlignedBytes::new(bytes)))
}
(_, None) => Err(Error::Format("input opened without its file")),
}
}
}
pub enum InputBytes<'data> {
Mapped(MappedFile),
Borrowed(&'data [u8]),
Owned(AlignedBytes),
}
impl InputBytes<'_> {
pub fn bytes(&self) -> &[u8] {
match self {
Self::Mapped(map) => map.bytes(),
Self::Borrowed(bytes) => bytes,
Self::Owned(owned) => owned.bytes(),
}
}
}
pub struct AlignedBytes {
words: Vec<u64>,
len: usize,
}
impl AlignedBytes {
pub fn new(bytes: &[u8]) -> Self {
let mut words = vec![0u64; bytes.len().div_ceil(WORD)];
let raw: &mut [u8] = bytemuck::cast_slice_mut(&mut words);
if let Some(slot) = raw.get_mut(..bytes.len()) {
slot.copy_from_slice(bytes);
}
Self {
words,
len: bytes.len(),
}
}
pub fn bytes(&self) -> &[u8] {
let raw: &[u8] = bytemuck::cast_slice(&self.words);
raw.get(..self.len).unwrap_or(&[])
}
}
const WORD: usize = core::mem::size_of::<u64>();
const PARSE_ALIGN: usize = core::mem::align_of::<U64>();
fn is_parse_aligned(bytes: &[u8]) -> bool {
bytes.as_ptr().addr().is_multiple_of(PARSE_ALIGN)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Format {
Elf,
MachO,
Coff,
Pe,
}
impl Format {
pub fn detect(bytes: &[u8]) -> Option<Self> {
if bytes.starts_with(MZ.as_slice()) {
return Some(Self::Pe);
}
let magic: [u8; 4] = bytes.get(..4)?.try_into().ok()?;
match magic {
ELFMAGIC => Some(Self::Elf),
MH_MAGIC_BE_64 | MH_MAGIC_LE_64 | MH_MAGIC_BE_32
| MH_MAGIC_LE_32 | FAT_MAGIC_BE | FAT_MAGIC_BE_64 => {
Some(Self::MachO)
}
_ if is_coff_machine(bytes) => Some(Self::Coff),
_ => None,
}
}
}
const ELFMAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F'];
const MH_MAGIC_BE_64: [u8; 4] = [0xfe, 0xed, 0xfa, 0xcf];
const MH_MAGIC_LE_64: [u8; 4] = [0xcf, 0xfa, 0xed, 0xfe];
const MH_MAGIC_BE_32: [u8; 4] = [0xfe, 0xed, 0xfa, 0xce];
const MH_MAGIC_LE_32: [u8; 4] = [0xce, 0xfa, 0xed, 0xfe];
const FAT_MAGIC_BE: [u8; 4] = [0xca, 0xfe, 0xba, 0xbe];
const FAT_MAGIC_BE_64: [u8; 4] = [0xca, 0xfe, 0xba, 0xbf];
const MZ: [u8; 2] = *b"MZ";
fn is_coff_machine(bytes: &[u8]) -> bool {
let Some(head) = bytes.get(..2) else {
return false;
};
let machine = u16::from_le_bytes([head[0], head[1]]);
matches!(
machine,
crate::coff::constants::IMAGE_FILE_MACHINE_AMD64
| crate::coff::constants::IMAGE_FILE_MACHINE_I386
| crate::coff::constants::IMAGE_FILE_MACHINE_ARM64
| crate::coff::constants::IMAGE_FILE_MACHINE_ARMNT
)
}
pub enum InputFile<'data> {
Borrowed(BorrowedFile<'data>),
Owned(OwnedFile),
}
pub struct BorrowedFile<'data> {
path: PathBuf,
obj: ObjectFile<'data>,
reloc_by_target: Vec<Relocs<'data>>,
}
pub struct OwnedFile {
path: PathBuf,
bytes: AlignedBytes,
reloc_by_target: Vec<RelocSpan>,
}
#[derive(Clone, Copy)]
enum RelocSpan {
None,
Rel,
Rela { off: usize, len: usize },
}
impl<'data> InputFile<'data> {
pub fn open(path: &Path, bytes: &'data [u8]) -> Result<Self> {
let obj = ObjectFile::parse(bytes)?;
let reloc_by_target = obj.reloc_index()?;
Ok(Self::Borrowed(BorrowedFile {
path: path.to_path_buf(),
obj,
reloc_by_target,
}))
}
pub fn open_with_symbols(
path: &Path,
bytes: &'data [u8],
) -> Result<(Self, Vec<InputSymbol<'data>>, Vec<Group<'data>>)> {
let obj = ObjectFile::parse(bytes)?;
if !obj.is_relocatable() {
return Err(Error::Format(
"not a relocatable object: only ET_REL inputs can be linked \
into an image",
));
}
let symbols = extract_globals(&obj)?;
let mut groups = Vec::new();
obj.groups(&mut groups)?;
let reloc_by_target = obj.reloc_index()?;
Ok((
Self::Borrowed(BorrowedFile {
path: path.to_path_buf(),
obj,
reloc_by_target,
}),
symbols,
groups,
))
}
pub fn from_member(path: &Path, bytes: &[u8]) -> Result<Self> {
let owned = AlignedBytes::new(bytes);
let reloc_by_target = reloc_spans(owned.bytes())?;
Ok(Self::Owned(OwnedFile {
path: path.to_path_buf(),
bytes: owned,
reloc_by_target,
}))
}
pub fn path(&self) -> &Path {
match self {
Self::Borrowed(b) => &b.path,
Self::Owned(o) => &o.path,
}
}
pub fn basename(&self) -> &str {
self.path()
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("?")
}
pub fn object(&self) -> Result<ObjectFile<'_>> {
match self {
Self::Borrowed(b) => Ok(b.obj),
Self::Owned(o) => ObjectFile::parse(o.bytes.bytes()),
}
}
pub fn relocations(&self, target_shndx: u16) -> Result<Option<&[Rela64]>> {
match self {
Self::Borrowed(b) => b
.reloc_by_target
.get(usize::from(target_shndx))
.copied()
.unwrap_or(Relocs::None)
.entries(),
Self::Owned(o) => o.relocations(target_shndx),
}
}
pub fn section_bytes(&self, shdr: &Shdr64) -> Result<&[u8]> {
match self {
Self::Borrowed(b) => b.obj.section_data(shdr),
Self::Owned(o) => {
ObjectFile::parse(o.bytes.bytes())?.section_data(shdr)
}
}
}
pub fn symbol_table(&self) -> Result<Option<crate::elf::SymbolTable<'_>>> {
self.object()?.symbol_table()
}
pub fn global_symbols(&self) -> Result<Vec<InputSymbol<'_>>> {
let obj = self.object()?;
extract_globals(&obj)
}
pub fn global_symbols_direct(&self) -> Result<Vec<InputSymbol<'data>>> {
match self {
Self::Borrowed(file) => extract_globals(&file.obj),
Self::Owned(_) => Err(Error::Format(
"archive member reached the direct-input symbol fold",
)),
}
}
}
impl OwnedFile {
fn relocations(&self, target_shndx: u16) -> Result<Option<&[Rela64]>> {
let span = self
.reloc_by_target
.get(usize::from(target_shndx))
.copied()
.unwrap_or(RelocSpan::None);
let RelocSpan::Rela { off, len } = span else {
return match span {
RelocSpan::Rel => Err(Error::Format(
"SHT_REL relocations (only SHT_RELA is supported)",
)),
_ => Ok(None),
};
};
let bytes = self
.bytes
.bytes()
.get(off..off.saturating_add(len))
.ok_or(Error::OutOfRange("member relocation span"))?;
bytemuck::try_cast_slice(bytes)
.map(Some)
.map_err(|_| Error::Format("misaligned member relocations"))
}
}
fn reloc_spans(bytes: &[u8]) -> Result<Vec<RelocSpan>> {
use crate::elf::constants::{SHT_REL, SHT_RELA};
let obj = ObjectFile::parse(bytes)?;
let sections = obj.sections();
let mut out = vec![RelocSpan::None; sections.len()];
for shdr in sections {
let kind = shdr.sh_type.get();
if kind != SHT_RELA && kind != SHT_REL {
continue;
}
let Ok(target) = usize::try_from(shdr.sh_info.get()) else {
continue;
};
let Some(slot) = out.get_mut(target) else {
continue;
};
if !matches!(slot, RelocSpan::None) {
continue;
}
*slot = if kind == SHT_REL {
RelocSpan::Rel
} else {
RelocSpan::Rela {
off: usize::try_from(shdr.sh_offset.get()).unwrap_or(0),
len: usize::try_from(shdr.sh_size.get()).unwrap_or(0),
}
};
}
Ok(out)
}
fn extract_globals<'d>(obj: &ObjectFile<'d>) -> Result<Vec<InputSymbol<'d>>> {
let Some(symtab) = obj.symbol_table()? else {
return Ok(Vec::new());
};
let mut out = Vec::with_capacity(symtab.syms.len());
for (idx, sym) in symtab.iter().enumerate() {
check_shndx(sym.st_shndx.get())?;
if sym.bind() == STB_LOCAL {
continue;
}
let name = symtab.name(sym);
let name = crate::symbol::version_stem(name);
if name.is_empty() {
continue;
}
let sym_idx = u32::try_from(idx)
.map_err(|_| Error::OutOfRange("symbol index"))?;
if sym.st_shndx.get() == SHN_COMMON {
crate::util::check_align(
sym.st_value.get(),
"common symbol alignment is not a usable power of two",
)?;
}
out.push(InputSymbol {
name,
name_hash: crate::symbol::name_hash(name),
binding: sym.bind(),
type_: sym.type_(),
visibility: sym.visibility(),
shndx: sym.st_shndx.get(),
value: sym.st_value.get(),
size: sym.st_size.get(),
sym_idx,
});
}
Ok(out)
}
fn check_shndx(shndx: u16) -> Result<()> {
if shndx < SHN_LORESERVE
|| matches!(shndx, SHN_UNDEF | SHN_ABS | SHN_COMMON)
{
return Ok(());
}
if shndx == SHN_XINDEX {
return Err(Error::Format(
"symbol uses SHN_XINDEX: SHT_SYMTAB_SHNDX is not implemented",
));
}
Err(Error::Format(
"symbol has a reserved st_shndx this linker \
does not implement",
))
}
#[derive(Clone, Copy)]
pub struct InputSymbol<'a> {
pub name: &'a [u8],
pub binding: u8,
pub type_: u8,
pub visibility: u8,
pub shndx: u16,
pub value: u64,
pub size: u64,
pub sym_idx: u32,
pub name_hash: u64,
}
impl InputSymbol<'_> {
pub const fn is_undefined(&self) -> bool {
self.shndx == SHN_UNDEF
}
pub const fn is_common(&self) -> bool {
self.shndx == SHN_COMMON
}
pub const fn is_absolute(&self) -> bool {
self.shndx == SHN_ABS
}
}