Skip to main content

cant_launch/linux/
elf.rs

1//! Shared-library resolution, in the style of `ldd`, without running anything.
2//!
3//! We read only what the dynamic loader reads to find dependencies: the ELF header, the
4//! program headers, `PT_INTERP`, and from `PT_DYNAMIC` the `DT_NEEDED`, `DT_RPATH` and
5//! `DT_RUNPATH` strings. Each is a small positioned read, so large binaries cost no more than
6//! small ones. Search order follows glibc: `DT_RPATH` (only without `DT_RUNPATH`),
7//! `DT_RUNPATH`, the directories in `/etc/ld.so.conf`, then the system defaults.
8//! `LD_LIBRARY_PATH` is ignored because `cant` never passes `LD_*` variables into a cant.
9//!
10//! This is an approximation of the loader (no `ld.so.cache`, no `$LIB`/`$PLATFORM`).
11//! Libraries it misses are reported, and the loader's own error appears if one is needed.
12
13use std::collections::{HashSet, VecDeque};
14use std::fs::File;
15use std::os::unix::fs::FileExt;
16use std::path::{Path, PathBuf};
17use std::sync::OnceLock;
18
19/// Errors reading an executable.
20#[derive(Debug, thiserror::Error)]
21pub enum ElfError {
22    /// I/O error.
23    #[error("cannot read {path}: {source}")]
24    Io {
25        /// File.
26        path: PathBuf,
27        /// Cause.
28        source: std::io::Error,
29    },
30    /// The file starts with `#!`.
31    #[error("{0} is a script; cants must currently be native ELF executables")]
32    Script(PathBuf),
33    /// Not an ELF file, or a malformed one.
34    #[error("{path} is not a usable ELF executable: {reason}")]
35    Malformed {
36        /// File.
37        path: PathBuf,
38        /// What is wrong.
39        reason: &'static str,
40    },
41}
42
43/// What an executable needs from the filesystem to start.
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct Resolved {
46    /// `PT_INTERP`, canonicalized (absent for static binaries).
47    pub interpreter: Option<PathBuf>,
48    /// Shared libraries (canonical paths), in discovery order.
49    pub libs: Vec<PathBuf>,
50    /// `DT_NEEDED` names that could not be found.
51    pub missing: Vec<String>,
52    /// `PT_INTERP` exactly as written in the file (what the kernel will open).
53    pub interpreter_literal: Option<PathBuf>,
54    /// Each library as found: the path where its `DT_NEEDED` name was found (so its file name
55    /// is the name the loader looks for), and the canonical file. Used by `cant pack`.
56    pub found: Vec<(PathBuf, PathBuf)>,
57}
58
59const PT_LOAD: u32 = 1;
60const PT_DYNAMIC: u32 = 2;
61const PT_INTERP: u32 = 3;
62const DT_NULL: u64 = 0;
63const DT_NEEDED: u64 = 1;
64const DT_STRTAB: u64 = 5;
65const DT_STRSZ: u64 = 10;
66const DT_RPATH: u64 = 15;
67const DT_RUNPATH: u64 = 29;
68
69/// Sanity limits so a hostile file cannot make us allocate without bound.
70const MAX_PHNUM: u64 = 4096;
71const MAX_DYNAMIC: u64 = 1 << 20;
72const MAX_STRTAB: u64 = 16 << 20;
73const MAX_INTERP: u64 = 4096;
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76struct Kind {
77    is_64: bool,
78    little: bool,
79    machine: u16,
80}
81
82#[derive(Debug, Default)]
83struct DynInfo {
84    kind: Option<Kind>,
85    interp: Option<String>,
86    needed: Vec<String>,
87    rpath: Vec<String>,
88    runpath: Vec<String>,
89}
90
91struct Reader<'a> {
92    file: &'a File,
93    path: &'a Path,
94}
95
96impl Reader<'_> {
97    fn bad(&self, reason: &'static str) -> ElfError {
98        ElfError::Malformed {
99            path: self.path.to_path_buf(),
100            reason,
101        }
102    }
103
104    fn read(&self, offset: u64, len: u64) -> Result<Vec<u8>, ElfError> {
105        let len = usize::try_from(len).map_err(|_| self.bad("size overflow"))?;
106        let mut buf = vec![0u8; len];
107        self.file
108            .read_exact_at(&mut buf, offset)
109            .map_err(|e| match e.kind() {
110                std::io::ErrorKind::UnexpectedEof => self.bad("truncated file"),
111                _ => ElfError::Io {
112                    path: self.path.to_path_buf(),
113                    source: e,
114                },
115            })?;
116        Ok(buf)
117    }
118}
119
120fn uint(bytes: &[u8], little: bool) -> u64 {
121    let mut v: u64 = 0;
122    if little {
123        for &b in bytes.iter().rev() {
124            v = (v << 8) | u64::from(b);
125        }
126    } else {
127        for &b in bytes {
128            v = (v << 8) | u64::from(b);
129        }
130    }
131    v
132}
133
134fn field(buf: &[u8], off: usize, len: usize, little: bool) -> u64 {
135    // Callers only pass offsets inside fixed-size structures they already read.
136    buf.get(off..off + len).map_or(0, |b| uint(b, little))
137}
138
139struct Segment {
140    kind: u32,
141    offset: u64,
142    vaddr: u64,
143    filesz: u64,
144}
145
146fn read_dyn_info(path: &Path) -> Result<DynInfo, ElfError> {
147    let file = File::open(path).map_err(|source| ElfError::Io {
148        path: path.to_path_buf(),
149        source,
150    })?;
151    let r = Reader { file: &file, path };
152    let mut ident = [0u8; 64];
153    let n = read_prefix(&file, &mut ident).map_err(|source| ElfError::Io {
154        path: path.to_path_buf(),
155        source,
156    })?;
157    if ident.starts_with(b"#!") {
158        return Err(ElfError::Script(path.to_path_buf()));
159    }
160    if n < 52 || &ident[..4] != b"\x7fELF" {
161        return Err(r.bad("not an ELF file"));
162    }
163    let is_64 = match ident[4] {
164        1 => false,
165        2 => true,
166        _ => return Err(r.bad("unknown ELF class")),
167    };
168    let little = match ident[5] {
169        1 => true,
170        2 => false,
171        _ => return Err(r.bad("unknown byte order")),
172    };
173    if is_64 && n < 64 {
174        return Err(r.bad("truncated header"));
175    }
176    let machine = field(&ident, 18, 2, little) as u16;
177    let (phoff, phentsize, phnum) = if is_64 {
178        (
179            field(&ident, 32, 8, little),
180            field(&ident, 54, 2, little),
181            field(&ident, 56, 2, little),
182        )
183    } else {
184        (
185            field(&ident, 28, 4, little),
186            field(&ident, 42, 2, little),
187            field(&ident, 44, 2, little),
188        )
189    };
190    let min_phent = if is_64 { 56 } else { 32 };
191    if phnum > MAX_PHNUM || (phnum > 0 && phentsize < min_phent) {
192        return Err(r.bad("bad program header table"));
193    }
194    let table = r.read(phoff, phentsize * phnum)?;
195    let mut segments = Vec::with_capacity(phnum as usize);
196    for i in 0..phnum as usize {
197        let ph = &table[i * phentsize as usize..];
198        let seg = if is_64 {
199            Segment {
200                kind: field(ph, 0, 4, little) as u32,
201                offset: field(ph, 8, 8, little),
202                vaddr: field(ph, 16, 8, little),
203                filesz: field(ph, 32, 8, little),
204            }
205        } else {
206            Segment {
207                kind: field(ph, 0, 4, little) as u32,
208                offset: field(ph, 4, 4, little),
209                vaddr: field(ph, 8, 4, little),
210                filesz: field(ph, 16, 4, little),
211            }
212        };
213        segments.push(seg);
214    }
215
216    let mut info = DynInfo {
217        kind: Some(Kind {
218            is_64,
219            little,
220            machine,
221        }),
222        ..DynInfo::default()
223    };
224
225    if let Some(seg) = segments.iter().find(|s| s.kind == PT_INTERP) {
226        if seg.filesz == 0 || seg.filesz > MAX_INTERP {
227            return Err(r.bad("bad PT_INTERP"));
228        }
229        let raw = r.read(seg.offset, seg.filesz)?;
230        let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
231        info.interp = Some(String::from_utf8_lossy(&raw[..end]).into_owned());
232    }
233
234    let Some(dynamic) = segments.iter().find(|s| s.kind == PT_DYNAMIC) else {
235        return Ok(info); // statically linked
236    };
237    if dynamic.filesz > MAX_DYNAMIC {
238        return Err(r.bad("PT_DYNAMIC too large"));
239    }
240    let entries = r.read(dynamic.offset, dynamic.filesz)?;
241    let entsize = if is_64 { 16 } else { 8 };
242    let word = entsize / 2;
243    let mut strtab_vaddr = None;
244    let mut strsz = None;
245    let mut wanted: Vec<(u64, u64)> = Vec::new();
246    for entry in entries.chunks_exact(entsize) {
247        let tag = field(entry, 0, word, little);
248        let val = field(entry, word, word, little);
249        match tag {
250            DT_NULL => break,
251            DT_STRTAB => strtab_vaddr = Some(val),
252            DT_STRSZ => strsz = Some(val),
253            DT_NEEDED | DT_RPATH | DT_RUNPATH => wanted.push((tag, val)),
254            _ => {}
255        }
256    }
257    if wanted.is_empty() {
258        return Ok(info);
259    }
260    let (Some(strtab_vaddr), Some(strsz)) = (strtab_vaddr, strsz) else {
261        return Err(r.bad("dynamic section without string table"));
262    };
263    if strsz > MAX_STRTAB {
264        return Err(r.bad("string table too large"));
265    }
266    let load = segments
267        .iter()
268        .find(|s| s.kind == PT_LOAD && strtab_vaddr >= s.vaddr && strtab_vaddr - s.vaddr < s.filesz)
269        .ok_or_else(|| r.bad("string table outside loaded segments"))?;
270    let strtab_offset = load
271        .offset
272        .checked_add(strtab_vaddr - load.vaddr)
273        .ok_or_else(|| r.bad("string table offset overflow"))?;
274    let strtab = r.read(strtab_offset, strsz)?;
275    let string_at = |off: u64| -> Result<String, ElfError> {
276        let start = usize::try_from(off).map_err(|_| r.bad("bad string offset"))?;
277        let rest = strtab
278            .get(start..)
279            .ok_or_else(|| r.bad("bad string offset"))?;
280        let end = rest
281            .iter()
282            .position(|&b| b == 0)
283            .ok_or_else(|| r.bad("unterminated string"))?;
284        Ok(String::from_utf8_lossy(&rest[..end]).into_owned())
285    };
286    for (tag, val) in wanted {
287        let s = string_at(val)?;
288        match tag {
289            DT_NEEDED => info.needed.push(s),
290            DT_RPATH => info.rpath.extend(s.split(':').map(str::to_owned)),
291            DT_RUNPATH => info.runpath.extend(s.split(':').map(str::to_owned)),
292            _ => {}
293        }
294    }
295    Ok(info)
296}
297
298fn read_prefix(file: &File, buf: &mut [u8]) -> std::io::Result<usize> {
299    let mut filled = 0;
300    while filled < buf.len() {
301        match file.read_at(&mut buf[filled..], filled as u64) {
302            Ok(0) => break,
303            Ok(n) => filled += n,
304            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
305            Err(e) => return Err(e),
306        }
307    }
308    Ok(filled)
309}
310
311fn kind_of(path: &Path) -> Option<Kind> {
312    let file = File::open(path).ok()?;
313    let mut ident = [0u8; 20];
314    let n = read_prefix(&file, &mut ident).ok()?;
315    if n < 20 || &ident[..4] != b"\x7fELF" {
316        return None;
317    }
318    let little = ident[5] == 1;
319    Some(Kind {
320        is_64: ident[4] == 2,
321        little,
322        machine: uint(&ident[18..20], little) as u16,
323    })
324}
325
326/// Directories from `/etc/ld.so.conf` (with `include`s) followed by the system defaults.
327fn system_dirs() -> &'static [PathBuf] {
328    static DIRS: OnceLock<Vec<PathBuf>> = OnceLock::new();
329    DIRS.get_or_init(|| {
330        let mut dirs = Vec::new();
331        parse_ld_so_conf(Path::new("/etc/ld.so.conf"), &mut dirs, 0);
332        let triplet = if cfg!(target_arch = "x86_64") {
333            "x86_64-linux-gnu"
334        } else if cfg!(target_arch = "aarch64") {
335            "aarch64-linux-gnu"
336        } else {
337            "unknown"
338        };
339        for d in [
340            format!("/lib/{triplet}"),
341            format!("/usr/lib/{triplet}"),
342            "/lib64".into(),
343            "/usr/lib64".into(),
344            "/lib".into(),
345            "/usr/lib".into(),
346        ] {
347            let d = PathBuf::from(d);
348            if !dirs.contains(&d) {
349                dirs.push(d);
350            }
351        }
352        dirs
353    })
354}
355
356fn parse_ld_so_conf(path: &Path, out: &mut Vec<PathBuf>, depth: u32) {
357    if depth > 8 {
358        return;
359    }
360    let Ok(text) = std::fs::read_to_string(path) else {
361        return;
362    };
363    for line in text.lines() {
364        let line = line.split('#').next().unwrap_or("").trim();
365        if line.is_empty() || line.starts_with("hwcap ") {
366            continue;
367        }
368        if let Some(pattern) = line.strip_prefix("include") {
369            let pattern = pattern.trim();
370            let pattern = if pattern.starts_with('/') {
371                PathBuf::from(pattern)
372            } else {
373                path.parent().unwrap_or(Path::new("/")).join(pattern)
374            };
375            for file in glob_last_component(&pattern) {
376                parse_ld_so_conf(&file, out, depth + 1);
377            }
378        } else {
379            let dir = PathBuf::from(line);
380            if dir.is_absolute() && !out.contains(&dir) {
381                out.push(dir);
382            }
383        }
384    }
385}
386
387/// Expands a single `*` in the last path component (all `ld.so.conf` needs).
388fn glob_last_component(pattern: &Path) -> Vec<PathBuf> {
389    let (Some(dir), Some(name)) = (
390        pattern.parent(),
391        pattern.file_name().and_then(|n| n.to_str()),
392    ) else {
393        return Vec::new();
394    };
395    let Some((prefix, suffix)) = name.split_once('*') else {
396        return vec![pattern.to_path_buf()];
397    };
398    let Ok(entries) = std::fs::read_dir(dir) else {
399        return Vec::new();
400    };
401    let mut out: Vec<PathBuf> = entries
402        .filter_map(|e| e.ok())
403        .filter_map(|e| {
404            let n = e.file_name();
405            let n = n.to_str()?;
406            (n.len() >= prefix.len() + suffix.len() && n.starts_with(prefix) && n.ends_with(suffix))
407                .then(|| e.path())
408        })
409        .collect();
410    out.sort();
411    out
412}
413
414fn expand_origin(entry: &str, origin: &Path) -> Option<PathBuf> {
415    let origin = origin.to_str()?;
416    let expanded = entry
417        .replace("${ORIGIN}", origin)
418        .replace("$ORIGIN", origin);
419    if expanded.contains('$') || !expanded.starts_with('/') {
420        // $LIB, $PLATFORM and relative entries are not supported.
421        return None;
422    }
423    Some(PathBuf::from(expanded))
424}
425
426/// Where [`resolve_with`] looks for things.
427enum Search<'a> {
428    /// This machine: `/etc/ld.so.conf` and the system directories.
429    Host,
430    /// Only inside this directory (canonical), laid out like Debian's merged `/usr`.
431    Root(&'a Path),
432}
433
434/// The path under a merged-`/usr` root of an absolute path as a program names it:
435/// `/lib/ld-linux-aarch64.so.1` is `<root>/usr/lib/ld-linux-aarch64.so.1`.
436pub fn in_merged_usr(root: &Path, path: &str) -> PathBuf {
437    let rel = path.trim_start_matches('/');
438    for top in ["lib/", "lib64/", "lib32/", "bin/", "sbin/"] {
439        if rel.starts_with(top) {
440            return root.join("usr").join(rel);
441        }
442    }
443    root.join(rel)
444}
445
446/// The Debian multiarch triplet of an ELF machine.
447fn triplet(machine: u16) -> &'static str {
448    match machine {
449        62 => "x86_64-linux-gnu",
450        183 => "aarch64-linux-gnu",
451        243 => "riscv64-linux-gnu",
452        _ => "unknown",
453    }
454}
455
456impl Search<'_> {
457    fn dirs(&self, kind: Option<Kind>) -> Vec<PathBuf> {
458        match self {
459            Search::Host => system_dirs().to_vec(),
460            Search::Root(root) => {
461                let t = triplet(kind.map_or(0, |k| k.machine));
462                [format!("usr/lib/{t}"), "usr/lib64".into(), "usr/lib".into()]
463                    .iter()
464                    .map(|d| root.join(d))
465                    .collect()
466            }
467        }
468    }
469
470    /// An absolute path as written in a program (interpreter, `DT_NEEDED` with a `/`, an
471    /// `RPATH` entry), where to look for it.
472    fn place(&self, path: &str) -> PathBuf {
473        match self {
474            Search::Host => PathBuf::from(path),
475            Search::Root(root) => in_merged_usr(root, path),
476        }
477    }
478
479    /// The canonical file, if it stays inside the root.
480    fn canonical(&self, p: &Path) -> Option<PathBuf> {
481        let c = std::fs::canonicalize(p).ok()?;
482        match self {
483            Search::Host => Some(c),
484            Search::Root(root) => c.starts_with(root).then_some(c),
485        }
486    }
487}
488
489/// Resolves the interpreter and all shared libraries of `binary`.
490pub fn resolve(binary: &Path) -> Result<Resolved, ElfError> {
491    resolve_with(binary, &Search::Host)
492}
493
494/// Like [`resolve`], but only inside `root`, a sysroot laid out like Debian's merged `/usr`
495/// (`cant build` unpacks pinned packages there): nothing is looked up on this machine. The
496/// interpreter is found at `<root>/usr/lib/…` for a `/lib/…` `PT_INTERP`, and
497/// `interpreter_literal` stays as written in the program. Files that resolve outside `root`
498/// (a symlink pointing out) count as missing.
499pub fn resolve_in(binary: &Path, root: &Path) -> Result<Resolved, ElfError> {
500    let root = std::fs::canonicalize(root).map_err(|source| ElfError::Io {
501        path: root.to_path_buf(),
502        source,
503    })?;
504    resolve_with(binary, &Search::Root(&root))
505}
506
507fn resolve_with(binary: &Path, search: &Search<'_>) -> Result<Resolved, ElfError> {
508    let main = read_dyn_info(binary)?;
509    let kind = main.kind;
510    let mut out = Resolved::default();
511    if let Some(interp) = &main.interp {
512        let placed = search.place(interp);
513        out.interpreter = match search {
514            Search::Host => Some(std::fs::canonicalize(&placed).unwrap_or(placed)),
515            Search::Root(_) => search.canonical(&placed),
516        };
517        out.interpreter_literal = Some(PathBuf::from(interp));
518    }
519    // glibc: DT_RPATH of the executable applies to all its dependencies unless DT_RUNPATH exists.
520    let exe_rpath: Vec<String> = if main.runpath.is_empty() {
521        main.rpath.clone()
522    } else {
523        Vec::new()
524    };
525
526    let mut seen_names: HashSet<String> = HashSet::new();
527    let mut seen_paths: HashSet<PathBuf> = HashSet::new();
528    let mut queue: VecDeque<(PathBuf, DynInfo)> = VecDeque::new();
529    queue.push_back((binary.to_path_buf(), main));
530
531    while let Some((obj_path, info)) = queue.pop_front() {
532        let origin = obj_path.parent().unwrap_or(Path::new("/")).to_path_buf();
533        let mut dirs: Vec<PathBuf> = Vec::new();
534        if info.runpath.is_empty() {
535            for e in info.rpath.iter().chain(exe_rpath.iter()) {
536                dirs.extend(expand_origin(e, &origin));
537            }
538        }
539        for e in &info.runpath {
540            dirs.extend(expand_origin(e, &origin));
541        }
542        if let Search::Root(root) = search {
543            // `$ORIGIN` entries are already inside the root; other absolute entries name
544            // directories of the target system.
545            dirs = dirs
546                .into_iter()
547                .map(|d| {
548                    if d.starts_with(root) {
549                        d
550                    } else {
551                        search.place(&d.to_string_lossy())
552                    }
553                })
554                .collect();
555        }
556        dirs.extend(search.dirs(kind));
557
558        for name in &info.needed {
559            if !seen_names.insert(name.clone()) {
560                continue;
561            }
562            let found = if name.contains('/') {
563                Some(search.place(name)).filter(|p| p.is_file())
564            } else {
565                dirs.iter()
566                    .map(|d| d.join(name))
567                    .find(|p| p.is_file() && kind_of(p) == kind)
568            };
569            let Some(found) = found else {
570                out.missing.push(name.clone());
571                continue;
572            };
573            // Optimized variants the loader may prefer (glibc-hwcaps).
574            if let Some(dir) = found.parent() {
575                for variant in glob_last_component(&dir.join("glibc-hwcaps").join("*")) {
576                    let candidate = variant.join(name);
577                    if candidate.is_file()
578                        && let Some(c) = search.canonical(&candidate)
579                        && seen_paths.insert(c.clone())
580                    {
581                        out.libs.push(c);
582                    }
583                }
584            }
585            let canonical = match search {
586                Search::Host => std::fs::canonicalize(&found).unwrap_or_else(|_| found.clone()),
587                Search::Root(_) => match search.canonical(&found) {
588                    Some(c) => c,
589                    None => {
590                        out.missing.push(name.clone());
591                        continue;
592                    }
593                },
594            };
595            out.found.push((found, canonical.clone()));
596            if seen_paths.insert(canonical.clone()) {
597                out.libs.push(canonical.clone());
598                if let Ok(child) = read_dyn_info(&canonical) {
599                    queue.push_back((canonical, child));
600                }
601            }
602        }
603    }
604    Ok(out)
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610
611    #[test]
612    fn resolves_inside_a_sysroot_only() {
613        let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
614        let host = resolve(&cat).expect("resolve");
615        let (Some(literal), Some(interp)) = (&host.interpreter_literal, &host.interpreter) else {
616            return; // a static cat: nothing to resolve
617        };
618        let kind = read_dyn_info(&cat).expect("elf").kind;
619        let dir = std::env::temp_dir().join(format!("cant-sysroot-{}", std::process::id()));
620        let _ = std::fs::remove_dir_all(&dir);
621        let root = dir.join("root");
622
623        // Nothing there: nothing is found, and nothing comes from the host.
624        std::fs::create_dir_all(&root).expect("mkdir");
625        let empty = resolve_in(&cat, &root).expect("resolve_in");
626        assert!(empty.interpreter.is_none(), "{empty:?}");
627        assert!(
628            !empty.missing.is_empty() && empty.libs.is_empty(),
629            "{empty:?}"
630        );
631
632        // The host's files, laid out like a merged-/usr Debian root.
633        let lib_dir = root
634            .join("usr/lib")
635            .join(triplet(kind.expect("kind").machine));
636        std::fs::create_dir_all(&lib_dir).expect("mkdir");
637        let placed = in_merged_usr(&root, &literal.to_string_lossy());
638        std::fs::create_dir_all(placed.parent().expect("parent")).expect("mkdir");
639        std::fs::copy(interp, &placed).expect("copy loader");
640        for (found, canonical) in &host.found {
641            let name = found.file_name().expect("name");
642            std::fs::copy(canonical, lib_dir.join(name)).expect("copy lib");
643        }
644        let r = resolve_in(&cat, &root).expect("resolve_in");
645        assert!(r.missing.is_empty(), "{r:?}");
646        let canonical_root = std::fs::canonicalize(&root).expect("canonical");
647        assert!(
648            r.libs.iter().all(|l| l.starts_with(&canonical_root)),
649            "{r:?}"
650        );
651        assert_eq!(
652            r.interpreter.as_deref(),
653            std::fs::canonicalize(&placed).ok().as_deref()
654        );
655        assert_eq!(r.interpreter_literal.as_ref(), Some(literal));
656
657        // A library that is a symlink pointing out of the root counts as missing.
658        let (first, _) = &host.found[0];
659        let name = first.file_name().expect("name");
660        std::fs::remove_file(lib_dir.join(name)).expect("rm");
661        std::os::unix::fs::symlink(first, lib_dir.join(name)).expect("symlink");
662        let r = resolve_in(&cat, &root).expect("resolve_in");
663        assert!(
664            r.missing.contains(&name.to_string_lossy().into_owned()),
665            "{r:?}"
666        );
667        let _ = std::fs::remove_dir_all(&dir);
668    }
669
670    #[test]
671    fn merged_usr_paths() {
672        let r = Path::new("/r");
673        assert_eq!(
674            in_merged_usr(r, "/lib/ld-linux-aarch64.so.1"),
675            Path::new("/r/usr/lib/ld-linux-aarch64.so.1")
676        );
677        assert_eq!(
678            in_merged_usr(r, "/lib64/ld-linux-x86-64.so.2"),
679            Path::new("/r/usr/lib64/ld-linux-x86-64.so.2")
680        );
681        assert_eq!(
682            in_merged_usr(r, "/usr/lib/x/libc.so.6"),
683            Path::new("/r/usr/lib/x/libc.so.6")
684        );
685        assert_eq!(in_merged_usr(r, "/opt/x"), Path::new("/r/opt/x"));
686        assert_eq!(
687            in_merged_usr(r, "/library"),
688            Path::new("/r/library"),
689            "only whole components"
690        );
691        assert_eq!(triplet(62), "x86_64-linux-gnu");
692        assert_eq!(triplet(183), "aarch64-linux-gnu");
693        assert_eq!(triplet(1), "unknown");
694    }
695
696    #[test]
697    fn resolves_cat_like_ldd() {
698        let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
699        let r = resolve(&cat).expect("resolve");
700        let libc = r.libs.iter().any(|p| {
701            p.file_name()
702                .is_some_and(|n| n.to_string_lossy().starts_with("libc.so"))
703        });
704        assert!(libc, "libc not found in {r:?}");
705        assert!(r.interpreter.is_some(), "cat should be dynamically linked");
706        assert!(r.missing.is_empty(), "{r:?}");
707        // Compare with ldd when available.
708        if let Ok(out) = std::process::Command::new("ldd").arg(&cat).output() {
709            let text = String::from_utf8_lossy(&out.stdout);
710            for line in text.lines() {
711                if let Some((_, rest)) = line.split_once("=> ")
712                    && let Some(path) = rest.split_whitespace().next()
713                {
714                    let p = std::fs::canonicalize(path).expect("ldd path exists");
715                    assert!(r.libs.contains(&p), "ldd found {p:?}, we did not: {r:?}");
716                }
717            }
718        }
719    }
720
721    #[test]
722    fn rejects_non_elf_and_scripts() {
723        let dir = tempfile::tempdir().expect("tempdir");
724        let script = dir.path().join("s");
725        std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write");
726        assert!(matches!(resolve(&script), Err(ElfError::Script(_))));
727        let junk = dir.path().join("j");
728        std::fs::write(&junk, vec![0u8; 100]).expect("write");
729        assert!(matches!(resolve(&junk), Err(ElfError::Malformed { .. })));
730        let truncated = dir.path().join("t");
731        let mut bytes = std::fs::read("/bin/cat").expect("read cat");
732        bytes.truncate(200);
733        std::fs::write(&truncated, bytes).expect("write");
734        assert!(resolve(&truncated).is_err());
735    }
736
737    #[test]
738    fn origin_expansion() {
739        let o = Path::new("/opt/app/bin");
740        assert_eq!(
741            expand_origin("$ORIGIN/../lib", o),
742            Some(PathBuf::from("/opt/app/bin/../lib"))
743        );
744        assert_eq!(
745            expand_origin("${ORIGIN}/lib", o),
746            Some(PathBuf::from("/opt/app/bin/lib"))
747        );
748        assert_eq!(expand_origin("$LIB/x", o), None);
749        assert_eq!(expand_origin("lib", o), None);
750    }
751
752    /// This machine's ELF machine number: libraries must match it to be found.
753    const HOST: u16 = if cfg!(target_arch = "x86_64") {
754        62
755    } else if cfg!(target_arch = "aarch64") {
756        183
757    } else {
758        243
759    };
760
761    /// A synthetic ELF file for the reader's tests: header, program headers, interpreter,
762    /// string table and dynamic section, all in one `PT_LOAD` at address 0 (so an address is
763    /// its file offset). Segments: `PT_LOAD`, then `PT_INTERP` (if any), then `PT_DYNAMIC` (if
764    /// anything is needed).
765    #[derive(Default)]
766    struct Synth {
767        is_32: bool,
768        big: bool,
769        interp: Option<&'static str>,
770        needed: Vec<&'static str>,
771        rpath: Option<&'static str>,
772        runpath: Option<&'static str>,
773    }
774
775    /// A change to a built file, for the malformed-file cases.
776    type Edit<'a> = &'a dyn Fn(&mut Built);
777
778    struct Built {
779        bytes: Vec<u8>,
780        /// File offset of the dynamic section.
781        dynamic: usize,
782    }
783
784    fn put(buf: &mut Vec<u8>, off: usize, len: usize, v: u64, little: bool) {
785        if buf.len() < off + len {
786            buf.resize(off + len, 0);
787        }
788        for i in 0..len {
789            let shift = 8 * if little { i } else { len - 1 - i };
790            buf[off + i] = (v >> shift) as u8;
791        }
792    }
793
794    impl Synth {
795        fn build(&self) -> Built {
796            let (is_64, little) = (!self.is_32, !self.big);
797            let (hdr, phent, word) = if is_64 { (64, 56, 8) } else { (52, 32, 4) };
798            let mut strtab = vec![0u8];
799            let mut entries: Vec<(u64, u64)> = Vec::new();
800            let strings = self
801                .needed
802                .iter()
803                .map(|n| (DT_NEEDED, *n))
804                .chain(self.rpath.map(|r| (DT_RPATH, r)))
805                .chain(self.runpath.map(|r| (DT_RUNPATH, r)));
806            for (tag, s) in strings {
807                entries.push((tag, strtab.len() as u64));
808                strtab.extend_from_slice(s.as_bytes());
809                strtab.push(0);
810            }
811            let has_dynamic = !entries.is_empty();
812            let nseg = 1 + usize::from(self.interp.is_some()) + usize::from(has_dynamic);
813            let interp: Vec<u8> = self
814                .interp
815                .map(|i| [i.as_bytes(), b"\0"].concat())
816                .unwrap_or_default();
817            let interp_at = hdr + phent * nseg;
818            let strtab_at = interp_at + interp.len();
819            let dynamic = (strtab_at + strtab.len()).next_multiple_of(8);
820            entries.push((DT_STRTAB, strtab_at as u64));
821            entries.push((DT_STRSZ, strtab.len() as u64));
822            entries.push((DT_NULL, 0));
823            let dyn_size = entries.len() * 2 * word;
824            let end = dynamic + if has_dynamic { dyn_size } else { 0 };
825
826            let mut b = vec![0u8; end];
827            b[..4].copy_from_slice(b"\x7fELF");
828            b[4] = if is_64 { 2 } else { 1 };
829            b[5] = if little { 1 } else { 2 };
830            b[6] = 1;
831            put(&mut b, 16, 2, 3, little); // ET_DYN
832            put(&mut b, 18, 2, u64::from(HOST), little);
833            let (phoff, phentsize, phnum) = if is_64 { (32, 54, 56) } else { (28, 42, 44) };
834            put(&mut b, phoff, word, hdr as u64, little);
835            put(&mut b, phentsize, 2, phent as u64, little);
836            put(&mut b, phnum, 2, nseg as u64, little);
837            let mut segs = vec![(PT_LOAD, 0, end)];
838            if self.interp.is_some() {
839                segs.push((PT_INTERP, interp_at, interp.len()));
840            }
841            if has_dynamic {
842                segs.push((PT_DYNAMIC, dynamic, dyn_size));
843            }
844            let (o, v, f) = if is_64 { (8, 16, 32) } else { (4, 8, 16) };
845            for (i, (kind, off, size)) in segs.into_iter().enumerate() {
846                let ph = hdr + i * phent;
847                put(&mut b, ph, 4, u64::from(kind), little);
848                put(&mut b, ph + o, word, off as u64, little);
849                put(&mut b, ph + v, word, off as u64, little);
850                put(&mut b, ph + f, word, size as u64, little);
851            }
852            b[interp_at..strtab_at].copy_from_slice(&interp);
853            b[strtab_at..strtab_at + strtab.len()].copy_from_slice(&strtab);
854            if has_dynamic {
855                for (i, (t, val)) in entries.iter().enumerate() {
856                    let at = dynamic + i * 2 * word;
857                    put(&mut b, at, word, *t, little);
858                    put(&mut b, at + word, word, *val, little);
859                }
860            }
861            Built { bytes: b, dynamic }
862        }
863    }
864
865    /// Rewrites the first dynamic entry tagged `tag` (64-bit little-endian files only).
866    fn set_dyn(b: &mut Built, tag: u64, new_tag: u64, val: u64) {
867        let mut at = b.dynamic;
868        loop {
869            let t = uint(&b.bytes[at..at + 8], true);
870            assert_ne!(t, DT_NULL, "no dynamic entry {tag}");
871            if t == tag {
872                put(&mut b.bytes, at, 8, new_tag, true);
873                put(&mut b.bytes, at + 8, 8, val, true);
874                return;
875            }
876            at += 16;
877        }
878    }
879
880    fn info(bytes: &[u8]) -> Result<DynInfo, ElfError> {
881        let dir = tempfile::tempdir().expect("tempdir");
882        let path = dir.path().join("elf");
883        std::fs::write(&path, bytes).expect("write");
884        read_dyn_info(&path)
885    }
886
887    fn reason(bytes: &[u8]) -> &'static str {
888        match info(bytes) {
889            Err(ElfError::Malformed { reason, .. }) => reason,
890            other => panic!("not refused as malformed: {other:?}"),
891        }
892    }
893
894    #[test]
895    fn every_class_and_byte_order_reads_the_same() {
896        for (is_32, big) in [(false, false), (false, true), (true, false), (true, true)] {
897            let bytes = Synth {
898                is_32,
899                big,
900                interp: Some("/lib/ld-test.so.1"),
901                needed: vec!["liba.so.1", "libb.so.2"],
902                rpath: Some("/r1:/r2"),
903                runpath: Some("$ORIGIN/lib"),
904            }
905            .build()
906            .bytes;
907            let i = info(&bytes).expect("reads");
908            let kind = Kind {
909                is_64: !is_32,
910                little: !big,
911                machine: HOST,
912            };
913            assert_eq!(i.kind, Some(kind));
914            assert_eq!(i.interp.as_deref(), Some("/lib/ld-test.so.1"));
915            assert_eq!(i.needed, ["liba.so.1", "libb.so.2"]);
916            assert_eq!(i.rpath, ["/r1", "/r2"]);
917            assert_eq!(i.runpath, ["$ORIGIN/lib"]);
918            let dir = tempfile::tempdir().expect("tempdir");
919            std::fs::write(dir.path().join("e"), &bytes).expect("write");
920            assert_eq!(kind_of(&dir.path().join("e")), Some(kind));
921        }
922        // Statically linked: no interpreter, no dynamic section.
923        let i = info(&Synth::default().build().bytes).expect("static");
924        assert!(i.interp.is_none() && i.needed.is_empty(), "{i:?}");
925    }
926
927    #[test]
928    fn malformed_files_are_refused_with_a_reason() {
929        let good = || {
930            Synth {
931                interp: Some("/lib/ld.so"),
932                needed: vec!["liba.so"],
933                ..Synth::default()
934            }
935            .build()
936        };
937        let edit = |f: &dyn Fn(&mut Built)| {
938            let mut b = good();
939            f(&mut b);
940            reason(&b.bytes)
941        };
942        // Program header i starts at 64 + 56 i: 0 is PT_LOAD, 1 PT_INTERP, 2 PT_DYNAMIC.
943        let ph = |i: usize, field: usize| 64 + 56 * i + field;
944        let cases: [(Edit<'_>, &str); 16] = [
945            (&|b| b.bytes[4] = 3, "unknown ELF class"),
946            (&|b| b.bytes[5] = 3, "unknown byte order"),
947            (&|b| b.bytes.truncate(60), "truncated header"),
948            (&|b| b.bytes.truncate(40), "not an ELF file"),
949            (
950                &|b| put(&mut b.bytes, 56, 2, MAX_PHNUM + 1, true),
951                "bad program header table",
952            ),
953            (
954                &|b| put(&mut b.bytes, 54, 2, 8, true),
955                "bad program header table",
956            ),
957            (
958                &|b| put(&mut b.bytes, 32, 8, 1 << 20, true),
959                "truncated file",
960            ),
961            (
962                &|b| put(&mut b.bytes, ph(1, 32), 8, 0, true),
963                "bad PT_INTERP",
964            ),
965            (
966                &|b| put(&mut b.bytes, ph(1, 32), 8, MAX_INTERP + 1, true),
967                "bad PT_INTERP",
968            ),
969            (
970                &|b| put(&mut b.bytes, ph(2, 32), 8, MAX_DYNAMIC + 1, true),
971                "PT_DYNAMIC too large",
972            ),
973            (
974                &|b| set_dyn(b, DT_STRTAB, 0x6fff_0000, 0),
975                "dynamic section without string table",
976            ),
977            (
978                &|b| set_dyn(b, DT_STRSZ, DT_STRSZ, MAX_STRTAB + 1),
979                "string table too large",
980            ),
981            (
982                &|b| set_dyn(b, DT_STRTAB, DT_STRTAB, 1 << 40),
983                "string table outside loaded segments",
984            ),
985            (
986                &|b| put(&mut b.bytes, ph(0, 8), 8, u64::MAX, true),
987                "string table offset overflow",
988            ),
989            (
990                &|b| set_dyn(b, DT_NEEDED, DT_NEEDED, 1 << 20),
991                "bad string offset",
992            ),
993            (
994                &|b| set_dyn(b, DT_STRSZ, DT_STRSZ, 2),
995                "unterminated string",
996            ),
997        ];
998        for (f, want) in cases {
999            assert_eq!(edit(f), want);
1000        }
1001        // A dynamic section that needs nothing is fine, string table or not.
1002        let mut b = good();
1003        set_dyn(&mut b, DT_NEEDED, 0x6fff_0000, 0);
1004        assert!(info(&b.bytes).expect("reads").needed.is_empty());
1005        // What can't be read at all is an I/O error.
1006        let dir = tempfile::tempdir().expect("tempdir");
1007        assert!(matches!(
1008            read_dyn_info(&dir.path().join("missing")),
1009            Err(ElfError::Io { .. })
1010        ));
1011        assert!(matches!(
1012            read_dyn_info(dir.path()),
1013            Err(ElfError::Io { .. })
1014        ));
1015        assert_eq!(kind_of(&dir.path().join("missing")), None);
1016    }
1017
1018    #[test]
1019    fn a_sysroot_is_searched_like_the_loader_does() {
1020        let dir = tempfile::tempdir().expect("tempdir");
1021        let root = std::fs::canonicalize(dir.path())
1022            .expect("canonical")
1023            .join("root");
1024        let t = triplet(HOST);
1025        let write = |rel: &str, s: Synth| {
1026            let p = root.join(rel);
1027            std::fs::create_dir_all(p.parent().expect("parent")).expect("mkdir");
1028            std::fs::write(&p, s.build().bytes).expect("write");
1029            p
1030        };
1031        let lib = |needed: Vec<&'static str>| Synth {
1032            needed,
1033            ..Synth::default()
1034        };
1035        let prog = write(
1036            "usr/bin/prog",
1037            Synth {
1038                interp: Some("/lib/ld-test.so"),
1039                needed: vec![
1040                    "libfoo.so.1",
1041                    "/lib/libabs.so",
1042                    "libgone.so",
1043                    "libout.so",
1044                    "libpriv.so",
1045                    "libbar.so",
1046                ],
1047                runpath: Some("$ORIGIN/../lib/private:/opt/vendor/lib"),
1048                ..Synth::default()
1049            },
1050        );
1051        write("usr/lib/ld-test.so", Synth::default());
1052        // libfoo needs libdeep, which needs libfoo again (seen once).
1053        write(&format!("usr/lib/{t}/libfoo.so.1"), lib(vec!["libdeep.so"]));
1054        write(
1055            &format!("usr/lib/{t}/glibc-hwcaps/v3/libfoo.so.1"),
1056            Synth::default(),
1057        );
1058        write("usr/lib64/libdeep.so", lib(vec!["libfoo.so.1"]));
1059        write("usr/lib/libabs.so", Synth::default());
1060        write("usr/lib/private/libpriv.so", Synth::default());
1061        write("opt/vendor/lib/libbar.so", Synth::default());
1062        // A 32-bit libbar earlier in the path ($ORIGIN comes first) is skipped: wrong kind.
1063        write(
1064            "usr/lib/private/libbar.so",
1065            Synth {
1066                is_32: true,
1067                ..Synth::default()
1068            },
1069        );
1070        // libout points out of the root: missing.
1071        let outside = dir.path().join("libout.so");
1072        std::fs::write(&outside, Synth::default().build().bytes).expect("write");
1073        std::os::unix::fs::symlink(&outside, root.join(format!("usr/lib/{t}/libout.so")))
1074            .expect("symlink");
1075
1076        let r = resolve_in(&prog, &root).expect("resolve_in");
1077        assert_eq!(r.missing, ["libgone.so", "libout.so"], "{r:?}");
1078        assert_eq!(
1079            r.interpreter.as_deref(),
1080            Some(root.join("usr/lib/ld-test.so").as_path())
1081        );
1082        assert_eq!(
1083            r.interpreter_literal.as_deref(),
1084            Some(Path::new("/lib/ld-test.so"))
1085        );
1086        let expected = [
1087            format!("usr/lib/{t}/glibc-hwcaps/v3/libfoo.so.1"),
1088            format!("usr/lib/{t}/libfoo.so.1"),
1089            "usr/lib/libabs.so".into(),
1090            "usr/lib/private/libpriv.so".into(),
1091            "opt/vendor/lib/libbar.so".into(),
1092            "usr/lib64/libdeep.so".into(),
1093        ];
1094        let expected: Vec<PathBuf> = expected.iter().map(|p| root.join(p)).collect();
1095        assert_eq!(r.libs, expected);
1096        assert_eq!(r.found.len(), 5, "{r:?}"); // every DT_NEEDED found, not the hwcaps one
1097    }
1098
1099    #[test]
1100    fn ld_so_conf_includes_and_skips_like_glibc() {
1101        let dir = tempfile::tempdir().expect("tempdir");
1102        let d = dir.path();
1103        std::fs::create_dir(d.join("conf.d")).expect("mkdir");
1104        std::fs::write(
1105            d.join("ld.so.conf"),
1106            "# a comment\n\nhwcap 0 nosegneg\ninclude conf.d/*.conf\n\
1107             include /nonexistent/*.conf\nrelative/dir\n/abs/one # trailing\n/abs/one\n",
1108        )
1109        .expect("write");
1110        std::fs::write(d.join("conf.d/b.conf"), "/abs/b\n").expect("write");
1111        std::fs::write(d.join("conf.d/a.conf"), "/abs/a\n").expect("write");
1112        std::fs::write(d.join("conf.d/skip.txt"), "/abs/skipped\n").expect("write");
1113        // Includes itself: stops after a few levels instead of looping.
1114        let looped = d.join("conf.d/z.conf");
1115        std::fs::write(&looped, format!("include {}\n", looped.display())).expect("write");
1116        let mut out = Vec::new();
1117        parse_ld_so_conf(&d.join("ld.so.conf"), &mut out, 0);
1118        let want: Vec<PathBuf> = ["/abs/a", "/abs/b", "/abs/one"]
1119            .iter()
1120            .map(PathBuf::from)
1121            .collect();
1122        assert_eq!(out, want);
1123        // A missing file adds nothing; a pattern without `*` is itself.
1124        parse_ld_so_conf(&d.join("nope"), &mut out, 0);
1125        assert_eq!(out, want);
1126        assert_eq!(
1127            glob_last_component(Path::new("/a/b")),
1128            [PathBuf::from("/a/b")]
1129        );
1130        assert!(glob_last_component(Path::new("/")).is_empty());
1131        assert!(!system_dirs().is_empty());
1132    }
1133}