use std::collections::{HashSet, VecDeque};
use std::fs::File;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
#[derive(Debug, thiserror::Error)]
pub enum ElfError {
#[error("cannot read {path}: {source}")]
Io {
path: PathBuf,
source: std::io::Error,
},
#[error("{0} is a script; cants must currently be native ELF executables")]
Script(PathBuf),
#[error("{path} is not a usable ELF executable: {reason}")]
Malformed {
path: PathBuf,
reason: &'static str,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Resolved {
pub interpreter: Option<PathBuf>,
pub libs: Vec<PathBuf>,
pub missing: Vec<String>,
pub interpreter_literal: Option<PathBuf>,
pub found: Vec<(PathBuf, PathBuf)>,
}
const PT_LOAD: u32 = 1;
const PT_DYNAMIC: u32 = 2;
const PT_INTERP: u32 = 3;
const DT_NULL: u64 = 0;
const DT_NEEDED: u64 = 1;
const DT_STRTAB: u64 = 5;
const DT_STRSZ: u64 = 10;
const DT_RPATH: u64 = 15;
const DT_RUNPATH: u64 = 29;
const MAX_PHNUM: u64 = 4096;
const MAX_DYNAMIC: u64 = 1 << 20;
const MAX_STRTAB: u64 = 16 << 20;
const MAX_INTERP: u64 = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Kind {
is_64: bool,
little: bool,
machine: u16,
}
#[derive(Debug, Default)]
struct DynInfo {
kind: Option<Kind>,
interp: Option<String>,
needed: Vec<String>,
rpath: Vec<String>,
runpath: Vec<String>,
}
struct Reader<'a> {
file: &'a File,
path: &'a Path,
}
impl Reader<'_> {
fn bad(&self, reason: &'static str) -> ElfError {
ElfError::Malformed {
path: self.path.to_path_buf(),
reason,
}
}
fn read(&self, offset: u64, len: u64) -> Result<Vec<u8>, ElfError> {
let len = usize::try_from(len).map_err(|_| self.bad("size overflow"))?;
let mut buf = vec![0u8; len];
self.file
.read_exact_at(&mut buf, offset)
.map_err(|e| match e.kind() {
std::io::ErrorKind::UnexpectedEof => self.bad("truncated file"),
_ => ElfError::Io {
path: self.path.to_path_buf(),
source: e,
},
})?;
Ok(buf)
}
}
fn uint(bytes: &[u8], little: bool) -> u64 {
let mut v: u64 = 0;
if little {
for &b in bytes.iter().rev() {
v = (v << 8) | u64::from(b);
}
} else {
for &b in bytes {
v = (v << 8) | u64::from(b);
}
}
v
}
fn field(buf: &[u8], off: usize, len: usize, little: bool) -> u64 {
buf.get(off..off + len).map_or(0, |b| uint(b, little))
}
struct Segment {
kind: u32,
offset: u64,
vaddr: u64,
filesz: u64,
}
fn read_dyn_info(path: &Path) -> Result<DynInfo, ElfError> {
let file = File::open(path).map_err(|source| ElfError::Io {
path: path.to_path_buf(),
source,
})?;
let r = Reader { file: &file, path };
let mut ident = [0u8; 64];
let n = read_prefix(&file, &mut ident).map_err(|source| ElfError::Io {
path: path.to_path_buf(),
source,
})?;
if ident.starts_with(b"#!") {
return Err(ElfError::Script(path.to_path_buf()));
}
if n < 52 || &ident[..4] != b"\x7fELF" {
return Err(r.bad("not an ELF file"));
}
let is_64 = match ident[4] {
1 => false,
2 => true,
_ => return Err(r.bad("unknown ELF class")),
};
let little = match ident[5] {
1 => true,
2 => false,
_ => return Err(r.bad("unknown byte order")),
};
if is_64 && n < 64 {
return Err(r.bad("truncated header"));
}
let machine = field(&ident, 18, 2, little) as u16;
let (phoff, phentsize, phnum) = if is_64 {
(
field(&ident, 32, 8, little),
field(&ident, 54, 2, little),
field(&ident, 56, 2, little),
)
} else {
(
field(&ident, 28, 4, little),
field(&ident, 42, 2, little),
field(&ident, 44, 2, little),
)
};
let min_phent = if is_64 { 56 } else { 32 };
if phnum > MAX_PHNUM || (phnum > 0 && phentsize < min_phent) {
return Err(r.bad("bad program header table"));
}
let table = r.read(phoff, phentsize * phnum)?;
let mut segments = Vec::with_capacity(phnum as usize);
for i in 0..phnum as usize {
let ph = &table[i * phentsize as usize..];
let seg = if is_64 {
Segment {
kind: field(ph, 0, 4, little) as u32,
offset: field(ph, 8, 8, little),
vaddr: field(ph, 16, 8, little),
filesz: field(ph, 32, 8, little),
}
} else {
Segment {
kind: field(ph, 0, 4, little) as u32,
offset: field(ph, 4, 4, little),
vaddr: field(ph, 8, 4, little),
filesz: field(ph, 16, 4, little),
}
};
segments.push(seg);
}
let mut info = DynInfo {
kind: Some(Kind {
is_64,
little,
machine,
}),
..DynInfo::default()
};
if let Some(seg) = segments.iter().find(|s| s.kind == PT_INTERP) {
if seg.filesz == 0 || seg.filesz > MAX_INTERP {
return Err(r.bad("bad PT_INTERP"));
}
let raw = r.read(seg.offset, seg.filesz)?;
let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
info.interp = Some(String::from_utf8_lossy(&raw[..end]).into_owned());
}
let Some(dynamic) = segments.iter().find(|s| s.kind == PT_DYNAMIC) else {
return Ok(info); };
if dynamic.filesz > MAX_DYNAMIC {
return Err(r.bad("PT_DYNAMIC too large"));
}
let entries = r.read(dynamic.offset, dynamic.filesz)?;
let entsize = if is_64 { 16 } else { 8 };
let word = entsize / 2;
let mut strtab_vaddr = None;
let mut strsz = None;
let mut wanted: Vec<(u64, u64)> = Vec::new();
for entry in entries.chunks_exact(entsize) {
let tag = field(entry, 0, word, little);
let val = field(entry, word, word, little);
match tag {
DT_NULL => break,
DT_STRTAB => strtab_vaddr = Some(val),
DT_STRSZ => strsz = Some(val),
DT_NEEDED | DT_RPATH | DT_RUNPATH => wanted.push((tag, val)),
_ => {}
}
}
if wanted.is_empty() {
return Ok(info);
}
let (Some(strtab_vaddr), Some(strsz)) = (strtab_vaddr, strsz) else {
return Err(r.bad("dynamic section without string table"));
};
if strsz > MAX_STRTAB {
return Err(r.bad("string table too large"));
}
let load = segments
.iter()
.find(|s| s.kind == PT_LOAD && strtab_vaddr >= s.vaddr && strtab_vaddr - s.vaddr < s.filesz)
.ok_or_else(|| r.bad("string table outside loaded segments"))?;
let strtab_offset = load
.offset
.checked_add(strtab_vaddr - load.vaddr)
.ok_or_else(|| r.bad("string table offset overflow"))?;
let strtab = r.read(strtab_offset, strsz)?;
let string_at = |off: u64| -> Result<String, ElfError> {
let start = usize::try_from(off).map_err(|_| r.bad("bad string offset"))?;
let rest = strtab
.get(start..)
.ok_or_else(|| r.bad("bad string offset"))?;
let end = rest
.iter()
.position(|&b| b == 0)
.ok_or_else(|| r.bad("unterminated string"))?;
Ok(String::from_utf8_lossy(&rest[..end]).into_owned())
};
for (tag, val) in wanted {
let s = string_at(val)?;
match tag {
DT_NEEDED => info.needed.push(s),
DT_RPATH => info.rpath.extend(s.split(':').map(str::to_owned)),
DT_RUNPATH => info.runpath.extend(s.split(':').map(str::to_owned)),
_ => {}
}
}
Ok(info)
}
fn read_prefix(file: &File, buf: &mut [u8]) -> std::io::Result<usize> {
let mut filled = 0;
while filled < buf.len() {
match file.read_at(&mut buf[filled..], filled as u64) {
Ok(0) => break,
Ok(n) => filled += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(filled)
}
fn kind_of(path: &Path) -> Option<Kind> {
let file = File::open(path).ok()?;
let mut ident = [0u8; 20];
let n = read_prefix(&file, &mut ident).ok()?;
if n < 20 || &ident[..4] != b"\x7fELF" {
return None;
}
let little = ident[5] == 1;
Some(Kind {
is_64: ident[4] == 2,
little,
machine: uint(&ident[18..20], little) as u16,
})
}
fn system_dirs() -> &'static [PathBuf] {
static DIRS: OnceLock<Vec<PathBuf>> = OnceLock::new();
DIRS.get_or_init(|| {
let mut dirs = Vec::new();
parse_ld_so_conf(Path::new("/etc/ld.so.conf"), &mut dirs, 0);
let triplet = if cfg!(target_arch = "x86_64") {
"x86_64-linux-gnu"
} else if cfg!(target_arch = "aarch64") {
"aarch64-linux-gnu"
} else {
"unknown"
};
for d in [
format!("/lib/{triplet}"),
format!("/usr/lib/{triplet}"),
"/lib64".into(),
"/usr/lib64".into(),
"/lib".into(),
"/usr/lib".into(),
] {
let d = PathBuf::from(d);
if !dirs.contains(&d) {
dirs.push(d);
}
}
dirs
})
}
fn parse_ld_so_conf(path: &Path, out: &mut Vec<PathBuf>, depth: u32) {
if depth > 8 {
return;
}
let Ok(text) = std::fs::read_to_string(path) else {
return;
};
for line in text.lines() {
let line = line.split('#').next().unwrap_or("").trim();
if line.is_empty() || line.starts_with("hwcap ") {
continue;
}
if let Some(pattern) = line.strip_prefix("include") {
let pattern = pattern.trim();
let pattern = if pattern.starts_with('/') {
PathBuf::from(pattern)
} else {
path.parent().unwrap_or(Path::new("/")).join(pattern)
};
for file in glob_last_component(&pattern) {
parse_ld_so_conf(&file, out, depth + 1);
}
} else {
let dir = PathBuf::from(line);
if dir.is_absolute() && !out.contains(&dir) {
out.push(dir);
}
}
}
}
fn glob_last_component(pattern: &Path) -> Vec<PathBuf> {
let (Some(dir), Some(name)) = (
pattern.parent(),
pattern.file_name().and_then(|n| n.to_str()),
) else {
return Vec::new();
};
let Some((prefix, suffix)) = name.split_once('*') else {
return vec![pattern.to_path_buf()];
};
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut out: Vec<PathBuf> = entries
.filter_map(|e| e.ok())
.filter_map(|e| {
let n = e.file_name();
let n = n.to_str()?;
(n.len() >= prefix.len() + suffix.len() && n.starts_with(prefix) && n.ends_with(suffix))
.then(|| e.path())
})
.collect();
out.sort();
out
}
fn expand_origin(entry: &str, origin: &Path) -> Option<PathBuf> {
let origin = origin.to_str()?;
let expanded = entry
.replace("${ORIGIN}", origin)
.replace("$ORIGIN", origin);
if expanded.contains('$') || !expanded.starts_with('/') {
return None;
}
Some(PathBuf::from(expanded))
}
enum Search<'a> {
Host,
Root(&'a Path),
}
pub fn in_merged_usr(root: &Path, path: &str) -> PathBuf {
let rel = path.trim_start_matches('/');
for top in ["lib/", "lib64/", "lib32/", "bin/", "sbin/"] {
if rel.starts_with(top) {
return root.join("usr").join(rel);
}
}
root.join(rel)
}
fn triplet(machine: u16) -> &'static str {
match machine {
62 => "x86_64-linux-gnu",
183 => "aarch64-linux-gnu",
243 => "riscv64-linux-gnu",
_ => "unknown",
}
}
impl Search<'_> {
fn dirs(&self, kind: Option<Kind>) -> Vec<PathBuf> {
match self {
Search::Host => system_dirs().to_vec(),
Search::Root(root) => {
let t = triplet(kind.map_or(0, |k| k.machine));
[format!("usr/lib/{t}"), "usr/lib64".into(), "usr/lib".into()]
.iter()
.map(|d| root.join(d))
.collect()
}
}
}
fn place(&self, path: &str) -> PathBuf {
match self {
Search::Host => PathBuf::from(path),
Search::Root(root) => in_merged_usr(root, path),
}
}
fn canonical(&self, p: &Path) -> Option<PathBuf> {
let c = std::fs::canonicalize(p).ok()?;
match self {
Search::Host => Some(c),
Search::Root(root) => c.starts_with(root).then_some(c),
}
}
}
pub fn resolve(binary: &Path) -> Result<Resolved, ElfError> {
resolve_with(binary, &Search::Host)
}
pub fn resolve_in(binary: &Path, root: &Path) -> Result<Resolved, ElfError> {
let root = std::fs::canonicalize(root).map_err(|source| ElfError::Io {
path: root.to_path_buf(),
source,
})?;
resolve_with(binary, &Search::Root(&root))
}
fn resolve_with(binary: &Path, search: &Search<'_>) -> Result<Resolved, ElfError> {
let main = read_dyn_info(binary)?;
let kind = main.kind;
let mut out = Resolved::default();
if let Some(interp) = &main.interp {
let placed = search.place(interp);
out.interpreter = match search {
Search::Host => Some(std::fs::canonicalize(&placed).unwrap_or(placed)),
Search::Root(_) => search.canonical(&placed),
};
out.interpreter_literal = Some(PathBuf::from(interp));
}
let exe_rpath: Vec<String> = if main.runpath.is_empty() {
main.rpath.clone()
} else {
Vec::new()
};
let mut seen_names: HashSet<String> = HashSet::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
let mut queue: VecDeque<(PathBuf, DynInfo)> = VecDeque::new();
queue.push_back((binary.to_path_buf(), main));
while let Some((obj_path, info)) = queue.pop_front() {
let origin = obj_path.parent().unwrap_or(Path::new("/")).to_path_buf();
let mut dirs: Vec<PathBuf> = Vec::new();
if info.runpath.is_empty() {
for e in info.rpath.iter().chain(exe_rpath.iter()) {
dirs.extend(expand_origin(e, &origin));
}
}
for e in &info.runpath {
dirs.extend(expand_origin(e, &origin));
}
if let Search::Root(root) = search {
dirs = dirs
.into_iter()
.map(|d| {
if d.starts_with(root) {
d
} else {
search.place(&d.to_string_lossy())
}
})
.collect();
}
dirs.extend(search.dirs(kind));
for name in &info.needed {
if !seen_names.insert(name.clone()) {
continue;
}
let found = if name.contains('/') {
Some(search.place(name)).filter(|p| p.is_file())
} else {
dirs.iter()
.map(|d| d.join(name))
.find(|p| p.is_file() && kind_of(p) == kind)
};
let Some(found) = found else {
out.missing.push(name.clone());
continue;
};
if let Some(dir) = found.parent() {
for variant in glob_last_component(&dir.join("glibc-hwcaps").join("*")) {
let candidate = variant.join(name);
if candidate.is_file() {
if let Some(c) = search.canonical(&candidate) {
if seen_paths.insert(c.clone()) {
out.libs.push(c);
}
}
}
}
}
let canonical = match search {
Search::Host => std::fs::canonicalize(&found).unwrap_or_else(|_| found.clone()),
Search::Root(_) => match search.canonical(&found) {
Some(c) => c,
None => {
out.missing.push(name.clone());
continue;
}
},
};
out.found.push((found, canonical.clone()));
if seen_paths.insert(canonical.clone()) {
out.libs.push(canonical.clone());
if let Ok(child) = read_dyn_info(&canonical) {
queue.push_back((canonical, child));
}
}
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolves_inside_a_sysroot_only() {
let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
let host = resolve(&cat).expect("resolve");
let (Some(literal), Some(interp)) = (&host.interpreter_literal, &host.interpreter) else {
return; };
let kind = read_dyn_info(&cat).expect("elf").kind;
let dir = std::env::temp_dir().join(format!("cant-sysroot-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let root = dir.join("root");
std::fs::create_dir_all(&root).expect("mkdir");
let empty = resolve_in(&cat, &root).expect("resolve_in");
assert!(empty.interpreter.is_none(), "{empty:?}");
assert!(
!empty.missing.is_empty() && empty.libs.is_empty(),
"{empty:?}"
);
let lib_dir = root
.join("usr/lib")
.join(triplet(kind.expect("kind").machine));
std::fs::create_dir_all(&lib_dir).expect("mkdir");
let placed = in_merged_usr(&root, &literal.to_string_lossy());
std::fs::create_dir_all(placed.parent().expect("parent")).expect("mkdir");
std::fs::copy(interp, &placed).expect("copy loader");
for (found, canonical) in &host.found {
let name = found.file_name().expect("name");
std::fs::copy(canonical, lib_dir.join(name)).expect("copy lib");
}
let r = resolve_in(&cat, &root).expect("resolve_in");
assert!(r.missing.is_empty(), "{r:?}");
let canonical_root = std::fs::canonicalize(&root).expect("canonical");
assert!(
r.libs.iter().all(|l| l.starts_with(&canonical_root)),
"{r:?}"
);
assert_eq!(
r.interpreter.as_deref(),
std::fs::canonicalize(&placed).ok().as_deref()
);
assert_eq!(r.interpreter_literal.as_ref(), Some(literal));
let (first, _) = &host.found[0];
let name = first.file_name().expect("name");
std::fs::remove_file(lib_dir.join(name)).expect("rm");
std::os::unix::fs::symlink(first, lib_dir.join(name)).expect("symlink");
let r = resolve_in(&cat, &root).expect("resolve_in");
assert!(
r.missing.contains(&name.to_string_lossy().into_owned()),
"{r:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn merged_usr_paths() {
let r = Path::new("/r");
assert_eq!(
in_merged_usr(r, "/lib/ld-linux-aarch64.so.1"),
Path::new("/r/usr/lib/ld-linux-aarch64.so.1")
);
assert_eq!(
in_merged_usr(r, "/lib64/ld-linux-x86-64.so.2"),
Path::new("/r/usr/lib64/ld-linux-x86-64.so.2")
);
assert_eq!(
in_merged_usr(r, "/usr/lib/x/libc.so.6"),
Path::new("/r/usr/lib/x/libc.so.6")
);
assert_eq!(in_merged_usr(r, "/opt/x"), Path::new("/r/opt/x"));
assert_eq!(
in_merged_usr(r, "/library"),
Path::new("/r/library"),
"only whole components"
);
assert_eq!(triplet(62), "x86_64-linux-gnu");
assert_eq!(triplet(183), "aarch64-linux-gnu");
assert_eq!(triplet(1), "unknown");
}
#[test]
fn resolves_cat_like_ldd() {
let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
let r = resolve(&cat).expect("resolve");
let libc = r.libs.iter().any(|p| {
p.file_name()
.is_some_and(|n| n.to_string_lossy().starts_with("libc.so"))
});
assert!(libc, "libc not found in {r:?}");
assert!(r.interpreter.is_some(), "cat should be dynamically linked");
assert!(r.missing.is_empty(), "{r:?}");
if let Ok(out) = std::process::Command::new("ldd").arg(&cat).output() {
let text = String::from_utf8_lossy(&out.stdout);
for line in text.lines() {
if let Some((_, rest)) = line.split_once("=> ") {
if let Some(path) = rest.split_whitespace().next() {
let p = std::fs::canonicalize(path).expect("ldd path exists");
assert!(r.libs.contains(&p), "ldd found {p:?}, we did not: {r:?}");
}
}
}
}
}
#[test]
fn rejects_non_elf_and_scripts() {
let dir = tempfile::tempdir().expect("tempdir");
let script = dir.path().join("s");
std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write");
assert!(matches!(resolve(&script), Err(ElfError::Script(_))));
let junk = dir.path().join("j");
std::fs::write(&junk, vec![0u8; 100]).expect("write");
assert!(matches!(resolve(&junk), Err(ElfError::Malformed { .. })));
let truncated = dir.path().join("t");
let mut bytes = std::fs::read("/bin/cat").expect("read cat");
bytes.truncate(200);
std::fs::write(&truncated, bytes).expect("write");
assert!(resolve(&truncated).is_err());
}
#[test]
fn origin_expansion() {
let o = Path::new("/opt/app/bin");
assert_eq!(
expand_origin("$ORIGIN/../lib", o),
Some(PathBuf::from("/opt/app/bin/../lib"))
);
assert_eq!(
expand_origin("${ORIGIN}/lib", o),
Some(PathBuf::from("/opt/app/bin/lib"))
);
assert_eq!(expand_origin("$LIB/x", o), None);
assert_eq!(expand_origin("lib", o), None);
}
const HOST: u16 = if cfg!(target_arch = "x86_64") {
62
} else if cfg!(target_arch = "aarch64") {
183
} else {
243
};
#[derive(Default)]
struct Synth {
is_32: bool,
big: bool,
interp: Option<&'static str>,
needed: Vec<&'static str>,
rpath: Option<&'static str>,
runpath: Option<&'static str>,
}
type Edit<'a> = &'a dyn Fn(&mut Built);
struct Built {
bytes: Vec<u8>,
dynamic: usize,
}
fn put(buf: &mut Vec<u8>, off: usize, len: usize, v: u64, little: bool) {
if buf.len() < off + len {
buf.resize(off + len, 0);
}
for i in 0..len {
let shift = 8 * if little { i } else { len - 1 - i };
buf[off + i] = (v >> shift) as u8;
}
}
impl Synth {
fn build(&self) -> Built {
let (is_64, little) = (!self.is_32, !self.big);
let (hdr, phent, word) = if is_64 { (64, 56, 8) } else { (52, 32, 4) };
let mut strtab = vec![0u8];
let mut entries: Vec<(u64, u64)> = Vec::new();
let strings = self
.needed
.iter()
.map(|n| (DT_NEEDED, *n))
.chain(self.rpath.map(|r| (DT_RPATH, r)))
.chain(self.runpath.map(|r| (DT_RUNPATH, r)));
for (tag, s) in strings {
entries.push((tag, strtab.len() as u64));
strtab.extend_from_slice(s.as_bytes());
strtab.push(0);
}
let has_dynamic = !entries.is_empty();
let nseg = 1 + usize::from(self.interp.is_some()) + usize::from(has_dynamic);
let interp: Vec<u8> = self
.interp
.map(|i| [i.as_bytes(), b"\0"].concat())
.unwrap_or_default();
let interp_at = hdr + phent * nseg;
let strtab_at = interp_at + interp.len();
let dynamic = (strtab_at + strtab.len()).next_multiple_of(8);
entries.push((DT_STRTAB, strtab_at as u64));
entries.push((DT_STRSZ, strtab.len() as u64));
entries.push((DT_NULL, 0));
let dyn_size = entries.len() * 2 * word;
let end = dynamic + if has_dynamic { dyn_size } else { 0 };
let mut b = vec![0u8; end];
b[..4].copy_from_slice(b"\x7fELF");
b[4] = if is_64 { 2 } else { 1 };
b[5] = if little { 1 } else { 2 };
b[6] = 1;
put(&mut b, 16, 2, 3, little); put(&mut b, 18, 2, u64::from(HOST), little);
let (phoff, phentsize, phnum) = if is_64 { (32, 54, 56) } else { (28, 42, 44) };
put(&mut b, phoff, word, hdr as u64, little);
put(&mut b, phentsize, 2, phent as u64, little);
put(&mut b, phnum, 2, nseg as u64, little);
let mut segs = vec![(PT_LOAD, 0, end)];
if self.interp.is_some() {
segs.push((PT_INTERP, interp_at, interp.len()));
}
if has_dynamic {
segs.push((PT_DYNAMIC, dynamic, dyn_size));
}
let (o, v, f) = if is_64 { (8, 16, 32) } else { (4, 8, 16) };
for (i, (kind, off, size)) in segs.into_iter().enumerate() {
let ph = hdr + i * phent;
put(&mut b, ph, 4, u64::from(kind), little);
put(&mut b, ph + o, word, off as u64, little);
put(&mut b, ph + v, word, off as u64, little);
put(&mut b, ph + f, word, size as u64, little);
}
b[interp_at..strtab_at].copy_from_slice(&interp);
b[strtab_at..strtab_at + strtab.len()].copy_from_slice(&strtab);
if has_dynamic {
for (i, (t, val)) in entries.iter().enumerate() {
let at = dynamic + i * 2 * word;
put(&mut b, at, word, *t, little);
put(&mut b, at + word, word, *val, little);
}
}
Built { bytes: b, dynamic }
}
}
fn set_dyn(b: &mut Built, tag: u64, new_tag: u64, val: u64) {
let mut at = b.dynamic;
loop {
let t = uint(&b.bytes[at..at + 8], true);
assert_ne!(t, DT_NULL, "no dynamic entry {tag}");
if t == tag {
put(&mut b.bytes, at, 8, new_tag, true);
put(&mut b.bytes, at + 8, 8, val, true);
return;
}
at += 16;
}
}
fn info(bytes: &[u8]) -> Result<DynInfo, ElfError> {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("elf");
std::fs::write(&path, bytes).expect("write");
read_dyn_info(&path)
}
fn reason(bytes: &[u8]) -> &'static str {
match info(bytes) {
Err(ElfError::Malformed { reason, .. }) => reason,
other => panic!("not refused as malformed: {other:?}"),
}
}
#[test]
fn every_class_and_byte_order_reads_the_same() {
for (is_32, big) in [(false, false), (false, true), (true, false), (true, true)] {
let bytes = Synth {
is_32,
big,
interp: Some("/lib/ld-test.so.1"),
needed: vec!["liba.so.1", "libb.so.2"],
rpath: Some("/r1:/r2"),
runpath: Some("$ORIGIN/lib"),
}
.build()
.bytes;
let i = info(&bytes).expect("reads");
let kind = Kind {
is_64: !is_32,
little: !big,
machine: HOST,
};
assert_eq!(i.kind, Some(kind));
assert_eq!(i.interp.as_deref(), Some("/lib/ld-test.so.1"));
assert_eq!(i.needed, ["liba.so.1", "libb.so.2"]);
assert_eq!(i.rpath, ["/r1", "/r2"]);
assert_eq!(i.runpath, ["$ORIGIN/lib"]);
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("e"), &bytes).expect("write");
assert_eq!(kind_of(&dir.path().join("e")), Some(kind));
}
let i = info(&Synth::default().build().bytes).expect("static");
assert!(i.interp.is_none() && i.needed.is_empty(), "{i:?}");
}
#[test]
fn malformed_files_are_refused_with_a_reason() {
let good = || {
Synth {
interp: Some("/lib/ld.so"),
needed: vec!["liba.so"],
..Synth::default()
}
.build()
};
let edit = |f: &dyn Fn(&mut Built)| {
let mut b = good();
f(&mut b);
reason(&b.bytes)
};
let ph = |i: usize, field: usize| 64 + 56 * i + field;
let cases: [(Edit<'_>, &str); 16] = [
(&|b| b.bytes[4] = 3, "unknown ELF class"),
(&|b| b.bytes[5] = 3, "unknown byte order"),
(&|b| b.bytes.truncate(60), "truncated header"),
(&|b| b.bytes.truncate(40), "not an ELF file"),
(
&|b| put(&mut b.bytes, 56, 2, MAX_PHNUM + 1, true),
"bad program header table",
),
(
&|b| put(&mut b.bytes, 54, 2, 8, true),
"bad program header table",
),
(
&|b| put(&mut b.bytes, 32, 8, 1 << 20, true),
"truncated file",
),
(
&|b| put(&mut b.bytes, ph(1, 32), 8, 0, true),
"bad PT_INTERP",
),
(
&|b| put(&mut b.bytes, ph(1, 32), 8, MAX_INTERP + 1, true),
"bad PT_INTERP",
),
(
&|b| put(&mut b.bytes, ph(2, 32), 8, MAX_DYNAMIC + 1, true),
"PT_DYNAMIC too large",
),
(
&|b| set_dyn(b, DT_STRTAB, 0x6fff_0000, 0),
"dynamic section without string table",
),
(
&|b| set_dyn(b, DT_STRSZ, DT_STRSZ, MAX_STRTAB + 1),
"string table too large",
),
(
&|b| set_dyn(b, DT_STRTAB, DT_STRTAB, 1 << 40),
"string table outside loaded segments",
),
(
&|b| put(&mut b.bytes, ph(0, 8), 8, u64::MAX, true),
"string table offset overflow",
),
(
&|b| set_dyn(b, DT_NEEDED, DT_NEEDED, 1 << 20),
"bad string offset",
),
(
&|b| set_dyn(b, DT_STRSZ, DT_STRSZ, 2),
"unterminated string",
),
];
for (f, want) in cases {
assert_eq!(edit(f), want);
}
let mut b = good();
set_dyn(&mut b, DT_NEEDED, 0x6fff_0000, 0);
assert!(info(&b.bytes).expect("reads").needed.is_empty());
let dir = tempfile::tempdir().expect("tempdir");
assert!(matches!(
read_dyn_info(&dir.path().join("missing")),
Err(ElfError::Io { .. })
));
assert!(matches!(
read_dyn_info(dir.path()),
Err(ElfError::Io { .. })
));
assert_eq!(kind_of(&dir.path().join("missing")), None);
}
#[test]
fn a_sysroot_is_searched_like_the_loader_does() {
let dir = tempfile::tempdir().expect("tempdir");
let root = std::fs::canonicalize(dir.path())
.expect("canonical")
.join("root");
let t = triplet(HOST);
let write = |rel: &str, s: Synth| {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().expect("parent")).expect("mkdir");
std::fs::write(&p, s.build().bytes).expect("write");
p
};
let lib = |needed: Vec<&'static str>| Synth {
needed,
..Synth::default()
};
let prog = write(
"usr/bin/prog",
Synth {
interp: Some("/lib/ld-test.so"),
needed: vec![
"libfoo.so.1",
"/lib/libabs.so",
"libgone.so",
"libout.so",
"libpriv.so",
"libbar.so",
],
runpath: Some("$ORIGIN/../lib/private:/opt/vendor/lib"),
..Synth::default()
},
);
write("usr/lib/ld-test.so", Synth::default());
write(&format!("usr/lib/{t}/libfoo.so.1"), lib(vec!["libdeep.so"]));
write(
&format!("usr/lib/{t}/glibc-hwcaps/v3/libfoo.so.1"),
Synth::default(),
);
write("usr/lib64/libdeep.so", lib(vec!["libfoo.so.1"]));
write("usr/lib/libabs.so", Synth::default());
write("usr/lib/private/libpriv.so", Synth::default());
write("opt/vendor/lib/libbar.so", Synth::default());
write(
"usr/lib/private/libbar.so",
Synth {
is_32: true,
..Synth::default()
},
);
let outside = dir.path().join("libout.so");
std::fs::write(&outside, Synth::default().build().bytes).expect("write");
std::os::unix::fs::symlink(&outside, root.join(format!("usr/lib/{t}/libout.so")))
.expect("symlink");
let r = resolve_in(&prog, &root).expect("resolve_in");
assert_eq!(r.missing, ["libgone.so", "libout.so"], "{r:?}");
assert_eq!(
r.interpreter.as_deref(),
Some(root.join("usr/lib/ld-test.so").as_path())
);
assert_eq!(
r.interpreter_literal.as_deref(),
Some(Path::new("/lib/ld-test.so"))
);
let expected = [
format!("usr/lib/{t}/glibc-hwcaps/v3/libfoo.so.1"),
format!("usr/lib/{t}/libfoo.so.1"),
"usr/lib/libabs.so".into(),
"usr/lib/private/libpriv.so".into(),
"opt/vendor/lib/libbar.so".into(),
"usr/lib64/libdeep.so".into(),
];
let expected: Vec<PathBuf> = expected.iter().map(|p| root.join(p)).collect();
assert_eq!(r.libs, expected);
assert_eq!(r.found.len(), 5, "{r:?}"); }
#[test]
fn ld_so_conf_includes_and_skips_like_glibc() {
let dir = tempfile::tempdir().expect("tempdir");
let d = dir.path();
std::fs::create_dir(d.join("conf.d")).expect("mkdir");
std::fs::write(
d.join("ld.so.conf"),
"# a comment\n\nhwcap 0 nosegneg\ninclude conf.d/*.conf\n\
include /nonexistent/*.conf\nrelative/dir\n/abs/one # trailing\n/abs/one\n",
)
.expect("write");
std::fs::write(d.join("conf.d/b.conf"), "/abs/b\n").expect("write");
std::fs::write(d.join("conf.d/a.conf"), "/abs/a\n").expect("write");
std::fs::write(d.join("conf.d/skip.txt"), "/abs/skipped\n").expect("write");
let looped = d.join("conf.d/z.conf");
std::fs::write(&looped, format!("include {}\n", looped.display())).expect("write");
let mut out = Vec::new();
parse_ld_so_conf(&d.join("ld.so.conf"), &mut out, 0);
let want: Vec<PathBuf> = ["/abs/a", "/abs/b", "/abs/one"]
.iter()
.map(PathBuf::from)
.collect();
assert_eq!(out, want);
parse_ld_so_conf(&d.join("nope"), &mut out, 0);
assert_eq!(out, want);
assert_eq!(
glob_last_component(Path::new("/a/b")),
[PathBuf::from("/a/b")]
);
assert!(glob_last_component(Path::new("/")).is_empty());
assert!(!system_dirs().is_empty());
}
}