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                        if let Some(c) = search.canonical(&candidate) {
579                            if seen_paths.insert(c.clone()) {
580                                out.libs.push(c);
581                            }
582                        }
583                    }
584                }
585            }
586            let canonical = match search {
587                Search::Host => std::fs::canonicalize(&found).unwrap_or_else(|_| found.clone()),
588                Search::Root(_) => match search.canonical(&found) {
589                    Some(c) => c,
590                    None => {
591                        out.missing.push(name.clone());
592                        continue;
593                    }
594                },
595            };
596            out.found.push((found, canonical.clone()));
597            if seen_paths.insert(canonical.clone()) {
598                out.libs.push(canonical.clone());
599                if let Ok(child) = read_dyn_info(&canonical) {
600                    queue.push_back((canonical, child));
601                }
602            }
603        }
604    }
605    Ok(out)
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611
612    #[test]
613    fn resolves_inside_a_sysroot_only() {
614        let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
615        let host = resolve(&cat).expect("resolve");
616        let (Some(literal), Some(interp)) = (&host.interpreter_literal, &host.interpreter) else {
617            return; // a static cat: nothing to resolve
618        };
619        let kind = read_dyn_info(&cat).expect("elf").kind;
620        let dir = std::env::temp_dir().join(format!("cant-sysroot-{}", std::process::id()));
621        let _ = std::fs::remove_dir_all(&dir);
622        let root = dir.join("root");
623
624        // Nothing there: nothing is found, and nothing comes from the host.
625        std::fs::create_dir_all(&root).expect("mkdir");
626        let empty = resolve_in(&cat, &root).expect("resolve_in");
627        assert!(empty.interpreter.is_none(), "{empty:?}");
628        assert!(
629            !empty.missing.is_empty() && empty.libs.is_empty(),
630            "{empty:?}"
631        );
632
633        // The host's files, laid out like a merged-/usr Debian root.
634        let lib_dir = root
635            .join("usr/lib")
636            .join(triplet(kind.expect("kind").machine));
637        std::fs::create_dir_all(&lib_dir).expect("mkdir");
638        let placed = in_merged_usr(&root, &literal.to_string_lossy());
639        std::fs::create_dir_all(placed.parent().expect("parent")).expect("mkdir");
640        std::fs::copy(interp, &placed).expect("copy loader");
641        for (found, canonical) in &host.found {
642            let name = found.file_name().expect("name");
643            std::fs::copy(canonical, lib_dir.join(name)).expect("copy lib");
644        }
645        let r = resolve_in(&cat, &root).expect("resolve_in");
646        assert!(r.missing.is_empty(), "{r:?}");
647        let canonical_root = std::fs::canonicalize(&root).expect("canonical");
648        assert!(
649            r.libs.iter().all(|l| l.starts_with(&canonical_root)),
650            "{r:?}"
651        );
652        assert_eq!(
653            r.interpreter.as_deref(),
654            std::fs::canonicalize(&placed).ok().as_deref()
655        );
656        assert_eq!(r.interpreter_literal.as_ref(), Some(literal));
657
658        // A library that is a symlink pointing out of the root counts as missing.
659        let (first, _) = &host.found[0];
660        let name = first.file_name().expect("name");
661        std::fs::remove_file(lib_dir.join(name)).expect("rm");
662        std::os::unix::fs::symlink(first, lib_dir.join(name)).expect("symlink");
663        let r = resolve_in(&cat, &root).expect("resolve_in");
664        assert!(
665            r.missing.contains(&name.to_string_lossy().into_owned()),
666            "{r:?}"
667        );
668        let _ = std::fs::remove_dir_all(&dir);
669    }
670
671    #[test]
672    fn merged_usr_paths() {
673        let r = Path::new("/r");
674        assert_eq!(
675            in_merged_usr(r, "/lib/ld-linux-aarch64.so.1"),
676            Path::new("/r/usr/lib/ld-linux-aarch64.so.1")
677        );
678        assert_eq!(
679            in_merged_usr(r, "/lib64/ld-linux-x86-64.so.2"),
680            Path::new("/r/usr/lib64/ld-linux-x86-64.so.2")
681        );
682        assert_eq!(
683            in_merged_usr(r, "/usr/lib/x/libc.so.6"),
684            Path::new("/r/usr/lib/x/libc.so.6")
685        );
686        assert_eq!(in_merged_usr(r, "/opt/x"), Path::new("/r/opt/x"));
687        assert_eq!(
688            in_merged_usr(r, "/library"),
689            Path::new("/r/library"),
690            "only whole components"
691        );
692        assert_eq!(triplet(62), "x86_64-linux-gnu");
693        assert_eq!(triplet(183), "aarch64-linux-gnu");
694        assert_eq!(triplet(1), "unknown");
695    }
696
697    #[test]
698    fn resolves_cat_like_ldd() {
699        let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
700        let r = resolve(&cat).expect("resolve");
701        let libc = r.libs.iter().any(|p| {
702            p.file_name()
703                .is_some_and(|n| n.to_string_lossy().starts_with("libc.so"))
704        });
705        assert!(libc, "libc not found in {r:?}");
706        assert!(r.interpreter.is_some(), "cat should be dynamically linked");
707        assert!(r.missing.is_empty(), "{r:?}");
708        // Compare with ldd when available.
709        if let Ok(out) = std::process::Command::new("ldd").arg(&cat).output() {
710            let text = String::from_utf8_lossy(&out.stdout);
711            for line in text.lines() {
712                if let Some((_, rest)) = line.split_once("=> ") {
713                    if let Some(path) = rest.split_whitespace().next() {
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
722    #[test]
723    fn rejects_non_elf_and_scripts() {
724        let dir = tempfile::tempdir().expect("tempdir");
725        let script = dir.path().join("s");
726        std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write");
727        assert!(matches!(resolve(&script), Err(ElfError::Script(_))));
728        let junk = dir.path().join("j");
729        std::fs::write(&junk, vec![0u8; 100]).expect("write");
730        assert!(matches!(resolve(&junk), Err(ElfError::Malformed { .. })));
731        let truncated = dir.path().join("t");
732        let mut bytes = std::fs::read("/bin/cat").expect("read cat");
733        bytes.truncate(200);
734        std::fs::write(&truncated, bytes).expect("write");
735        assert!(resolve(&truncated).is_err());
736    }
737
738    #[test]
739    fn origin_expansion() {
740        let o = Path::new("/opt/app/bin");
741        assert_eq!(
742            expand_origin("$ORIGIN/../lib", o),
743            Some(PathBuf::from("/opt/app/bin/../lib"))
744        );
745        assert_eq!(
746            expand_origin("${ORIGIN}/lib", o),
747            Some(PathBuf::from("/opt/app/bin/lib"))
748        );
749        assert_eq!(expand_origin("$LIB/x", o), None);
750        assert_eq!(expand_origin("lib", o), None);
751    }
752}