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}
53
54const PT_LOAD: u32 = 1;
55const PT_DYNAMIC: u32 = 2;
56const PT_INTERP: u32 = 3;
57const DT_NULL: u64 = 0;
58const DT_NEEDED: u64 = 1;
59const DT_STRTAB: u64 = 5;
60const DT_STRSZ: u64 = 10;
61const DT_RPATH: u64 = 15;
62const DT_RUNPATH: u64 = 29;
63
64/// Sanity limits so a hostile file cannot make us allocate without bound.
65const MAX_PHNUM: u64 = 4096;
66const MAX_DYNAMIC: u64 = 1 << 20;
67const MAX_STRTAB: u64 = 16 << 20;
68const MAX_INTERP: u64 = 4096;
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71struct Kind {
72    is_64: bool,
73    little: bool,
74    machine: u16,
75}
76
77#[derive(Debug, Default)]
78struct DynInfo {
79    kind: Option<Kind>,
80    interp: Option<String>,
81    needed: Vec<String>,
82    rpath: Vec<String>,
83    runpath: Vec<String>,
84}
85
86struct Reader<'a> {
87    file: &'a File,
88    path: &'a Path,
89}
90
91impl Reader<'_> {
92    fn bad(&self, reason: &'static str) -> ElfError {
93        ElfError::Malformed {
94            path: self.path.to_path_buf(),
95            reason,
96        }
97    }
98
99    fn read(&self, offset: u64, len: u64) -> Result<Vec<u8>, ElfError> {
100        let len = usize::try_from(len).map_err(|_| self.bad("size overflow"))?;
101        let mut buf = vec![0u8; len];
102        self.file
103            .read_exact_at(&mut buf, offset)
104            .map_err(|e| match e.kind() {
105                std::io::ErrorKind::UnexpectedEof => self.bad("truncated file"),
106                _ => ElfError::Io {
107                    path: self.path.to_path_buf(),
108                    source: e,
109                },
110            })?;
111        Ok(buf)
112    }
113}
114
115fn uint(bytes: &[u8], little: bool) -> u64 {
116    let mut v: u64 = 0;
117    if little {
118        for &b in bytes.iter().rev() {
119            v = (v << 8) | u64::from(b);
120        }
121    } else {
122        for &b in bytes {
123            v = (v << 8) | u64::from(b);
124        }
125    }
126    v
127}
128
129fn field(buf: &[u8], off: usize, len: usize, little: bool) -> u64 {
130    // Callers only pass offsets inside fixed-size structures they already read.
131    buf.get(off..off + len).map_or(0, |b| uint(b, little))
132}
133
134struct Segment {
135    kind: u32,
136    offset: u64,
137    vaddr: u64,
138    filesz: u64,
139}
140
141fn read_dyn_info(path: &Path) -> Result<DynInfo, ElfError> {
142    let file = File::open(path).map_err(|source| ElfError::Io {
143        path: path.to_path_buf(),
144        source,
145    })?;
146    let r = Reader { file: &file, path };
147    let mut ident = [0u8; 64];
148    let n = read_prefix(&file, &mut ident).map_err(|source| ElfError::Io {
149        path: path.to_path_buf(),
150        source,
151    })?;
152    if ident.starts_with(b"#!") {
153        return Err(ElfError::Script(path.to_path_buf()));
154    }
155    if n < 52 || &ident[..4] != b"\x7fELF" {
156        return Err(r.bad("not an ELF file"));
157    }
158    let is_64 = match ident[4] {
159        1 => false,
160        2 => true,
161        _ => return Err(r.bad("unknown ELF class")),
162    };
163    let little = match ident[5] {
164        1 => true,
165        2 => false,
166        _ => return Err(r.bad("unknown byte order")),
167    };
168    if is_64 && n < 64 {
169        return Err(r.bad("truncated header"));
170    }
171    let machine = field(&ident, 18, 2, little) as u16;
172    let (phoff, phentsize, phnum) = if is_64 {
173        (
174            field(&ident, 32, 8, little),
175            field(&ident, 54, 2, little),
176            field(&ident, 56, 2, little),
177        )
178    } else {
179        (
180            field(&ident, 28, 4, little),
181            field(&ident, 42, 2, little),
182            field(&ident, 44, 2, little),
183        )
184    };
185    let min_phent = if is_64 { 56 } else { 32 };
186    if phnum > MAX_PHNUM || (phnum > 0 && phentsize < min_phent) {
187        return Err(r.bad("bad program header table"));
188    }
189    let table = r.read(phoff, phentsize * phnum)?;
190    let mut segments = Vec::with_capacity(phnum as usize);
191    for i in 0..phnum as usize {
192        let ph = &table[i * phentsize as usize..];
193        let seg = if is_64 {
194            Segment {
195                kind: field(ph, 0, 4, little) as u32,
196                offset: field(ph, 8, 8, little),
197                vaddr: field(ph, 16, 8, little),
198                filesz: field(ph, 32, 8, little),
199            }
200        } else {
201            Segment {
202                kind: field(ph, 0, 4, little) as u32,
203                offset: field(ph, 4, 4, little),
204                vaddr: field(ph, 8, 4, little),
205                filesz: field(ph, 16, 4, little),
206            }
207        };
208        segments.push(seg);
209    }
210
211    let mut info = DynInfo {
212        kind: Some(Kind {
213            is_64,
214            little,
215            machine,
216        }),
217        ..DynInfo::default()
218    };
219
220    if let Some(seg) = segments.iter().find(|s| s.kind == PT_INTERP) {
221        if seg.filesz == 0 || seg.filesz > MAX_INTERP {
222            return Err(r.bad("bad PT_INTERP"));
223        }
224        let raw = r.read(seg.offset, seg.filesz)?;
225        let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
226        info.interp = Some(String::from_utf8_lossy(&raw[..end]).into_owned());
227    }
228
229    let Some(dynamic) = segments.iter().find(|s| s.kind == PT_DYNAMIC) else {
230        return Ok(info); // statically linked
231    };
232    if dynamic.filesz > MAX_DYNAMIC {
233        return Err(r.bad("PT_DYNAMIC too large"));
234    }
235    let entries = r.read(dynamic.offset, dynamic.filesz)?;
236    let entsize = if is_64 { 16 } else { 8 };
237    let word = entsize / 2;
238    let mut strtab_vaddr = None;
239    let mut strsz = None;
240    let mut wanted: Vec<(u64, u64)> = Vec::new();
241    for entry in entries.chunks_exact(entsize) {
242        let tag = field(entry, 0, word, little);
243        let val = field(entry, word, word, little);
244        match tag {
245            DT_NULL => break,
246            DT_STRTAB => strtab_vaddr = Some(val),
247            DT_STRSZ => strsz = Some(val),
248            DT_NEEDED | DT_RPATH | DT_RUNPATH => wanted.push((tag, val)),
249            _ => {}
250        }
251    }
252    if wanted.is_empty() {
253        return Ok(info);
254    }
255    let (Some(strtab_vaddr), Some(strsz)) = (strtab_vaddr, strsz) else {
256        return Err(r.bad("dynamic section without string table"));
257    };
258    if strsz > MAX_STRTAB {
259        return Err(r.bad("string table too large"));
260    }
261    let load = segments
262        .iter()
263        .find(|s| s.kind == PT_LOAD && strtab_vaddr >= s.vaddr && strtab_vaddr - s.vaddr < s.filesz)
264        .ok_or_else(|| r.bad("string table outside loaded segments"))?;
265    let strtab_offset = load
266        .offset
267        .checked_add(strtab_vaddr - load.vaddr)
268        .ok_or_else(|| r.bad("string table offset overflow"))?;
269    let strtab = r.read(strtab_offset, strsz)?;
270    let string_at = |off: u64| -> Result<String, ElfError> {
271        let start = usize::try_from(off).map_err(|_| r.bad("bad string offset"))?;
272        let rest = strtab
273            .get(start..)
274            .ok_or_else(|| r.bad("bad string offset"))?;
275        let end = rest
276            .iter()
277            .position(|&b| b == 0)
278            .ok_or_else(|| r.bad("unterminated string"))?;
279        Ok(String::from_utf8_lossy(&rest[..end]).into_owned())
280    };
281    for (tag, val) in wanted {
282        let s = string_at(val)?;
283        match tag {
284            DT_NEEDED => info.needed.push(s),
285            DT_RPATH => info.rpath.extend(s.split(':').map(str::to_owned)),
286            DT_RUNPATH => info.runpath.extend(s.split(':').map(str::to_owned)),
287            _ => {}
288        }
289    }
290    Ok(info)
291}
292
293fn read_prefix(file: &File, buf: &mut [u8]) -> std::io::Result<usize> {
294    let mut filled = 0;
295    while filled < buf.len() {
296        match file.read_at(&mut buf[filled..], filled as u64) {
297            Ok(0) => break,
298            Ok(n) => filled += n,
299            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
300            Err(e) => return Err(e),
301        }
302    }
303    Ok(filled)
304}
305
306fn kind_of(path: &Path) -> Option<Kind> {
307    let file = File::open(path).ok()?;
308    let mut ident = [0u8; 20];
309    let n = read_prefix(&file, &mut ident).ok()?;
310    if n < 20 || &ident[..4] != b"\x7fELF" {
311        return None;
312    }
313    let little = ident[5] == 1;
314    Some(Kind {
315        is_64: ident[4] == 2,
316        little,
317        machine: uint(&ident[18..20], little) as u16,
318    })
319}
320
321/// Directories from `/etc/ld.so.conf` (with `include`s) followed by the system defaults.
322fn system_dirs() -> &'static [PathBuf] {
323    static DIRS: OnceLock<Vec<PathBuf>> = OnceLock::new();
324    DIRS.get_or_init(|| {
325        let mut dirs = Vec::new();
326        parse_ld_so_conf(Path::new("/etc/ld.so.conf"), &mut dirs, 0);
327        let triplet = if cfg!(target_arch = "x86_64") {
328            "x86_64-linux-gnu"
329        } else if cfg!(target_arch = "aarch64") {
330            "aarch64-linux-gnu"
331        } else {
332            "unknown"
333        };
334        for d in [
335            format!("/lib/{triplet}"),
336            format!("/usr/lib/{triplet}"),
337            "/lib64".into(),
338            "/usr/lib64".into(),
339            "/lib".into(),
340            "/usr/lib".into(),
341        ] {
342            let d = PathBuf::from(d);
343            if !dirs.contains(&d) {
344                dirs.push(d);
345            }
346        }
347        dirs
348    })
349}
350
351fn parse_ld_so_conf(path: &Path, out: &mut Vec<PathBuf>, depth: u32) {
352    if depth > 8 {
353        return;
354    }
355    let Ok(text) = std::fs::read_to_string(path) else {
356        return;
357    };
358    for line in text.lines() {
359        let line = line.split('#').next().unwrap_or("").trim();
360        if line.is_empty() || line.starts_with("hwcap ") {
361            continue;
362        }
363        if let Some(pattern) = line.strip_prefix("include") {
364            let pattern = pattern.trim();
365            let pattern = if pattern.starts_with('/') {
366                PathBuf::from(pattern)
367            } else {
368                path.parent().unwrap_or(Path::new("/")).join(pattern)
369            };
370            for file in glob_last_component(&pattern) {
371                parse_ld_so_conf(&file, out, depth + 1);
372            }
373        } else {
374            let dir = PathBuf::from(line);
375            if dir.is_absolute() && !out.contains(&dir) {
376                out.push(dir);
377            }
378        }
379    }
380}
381
382/// Expands a single `*` in the last path component (all `ld.so.conf` needs).
383fn glob_last_component(pattern: &Path) -> Vec<PathBuf> {
384    let (Some(dir), Some(name)) = (
385        pattern.parent(),
386        pattern.file_name().and_then(|n| n.to_str()),
387    ) else {
388        return Vec::new();
389    };
390    let Some((prefix, suffix)) = name.split_once('*') else {
391        return vec![pattern.to_path_buf()];
392    };
393    let Ok(entries) = std::fs::read_dir(dir) else {
394        return Vec::new();
395    };
396    let mut out: Vec<PathBuf> = entries
397        .filter_map(|e| e.ok())
398        .filter_map(|e| {
399            let n = e.file_name();
400            let n = n.to_str()?;
401            (n.len() >= prefix.len() + suffix.len() && n.starts_with(prefix) && n.ends_with(suffix))
402                .then(|| e.path())
403        })
404        .collect();
405    out.sort();
406    out
407}
408
409fn expand_origin(entry: &str, origin: &Path) -> Option<PathBuf> {
410    let origin = origin.to_str()?;
411    let expanded = entry
412        .replace("${ORIGIN}", origin)
413        .replace("$ORIGIN", origin);
414    if expanded.contains('$') || !expanded.starts_with('/') {
415        // $LIB, $PLATFORM and relative entries are not supported.
416        return None;
417    }
418    Some(PathBuf::from(expanded))
419}
420
421/// Resolves the interpreter and all shared libraries of `binary`.
422pub fn resolve(binary: &Path) -> Result<Resolved, ElfError> {
423    let main = read_dyn_info(binary)?;
424    let kind = main.kind;
425    let mut out = Resolved::default();
426    if let Some(interp) = &main.interp {
427        out.interpreter = Some(std::fs::canonicalize(interp).unwrap_or_else(|_| interp.into()));
428    }
429    // glibc: DT_RPATH of the executable applies to all its dependencies unless DT_RUNPATH exists.
430    let exe_rpath: Vec<String> = if main.runpath.is_empty() {
431        main.rpath.clone()
432    } else {
433        Vec::new()
434    };
435
436    let mut seen_names: HashSet<String> = HashSet::new();
437    let mut seen_paths: HashSet<PathBuf> = HashSet::new();
438    let mut queue: VecDeque<(PathBuf, DynInfo)> = VecDeque::new();
439    queue.push_back((binary.to_path_buf(), main));
440
441    while let Some((obj_path, info)) = queue.pop_front() {
442        let origin = obj_path.parent().unwrap_or(Path::new("/")).to_path_buf();
443        let mut dirs: Vec<PathBuf> = Vec::new();
444        if info.runpath.is_empty() {
445            for e in info.rpath.iter().chain(exe_rpath.iter()) {
446                dirs.extend(expand_origin(e, &origin));
447            }
448        }
449        for e in &info.runpath {
450            dirs.extend(expand_origin(e, &origin));
451        }
452        dirs.extend(system_dirs().iter().cloned());
453
454        for name in &info.needed {
455            if !seen_names.insert(name.clone()) {
456                continue;
457            }
458            let found = if name.contains('/') {
459                Some(PathBuf::from(name)).filter(|p| p.is_file())
460            } else {
461                dirs.iter()
462                    .map(|d| d.join(name))
463                    .find(|p| p.is_file() && kind_of(p) == kind)
464            };
465            let Some(found) = found else {
466                out.missing.push(name.clone());
467                continue;
468            };
469            // Optimized variants the loader may prefer (glibc-hwcaps).
470            if let Some(dir) = found.parent() {
471                for variant in glob_last_component(&dir.join("glibc-hwcaps").join("*")) {
472                    let candidate = variant.join(name);
473                    if candidate.is_file() {
474                        if let Ok(c) = std::fs::canonicalize(&candidate) {
475                            if seen_paths.insert(c.clone()) {
476                                out.libs.push(c);
477                            }
478                        }
479                    }
480                }
481            }
482            let canonical = std::fs::canonicalize(&found).unwrap_or(found);
483            if seen_paths.insert(canonical.clone()) {
484                out.libs.push(canonical.clone());
485                if let Ok(child) = read_dyn_info(&canonical) {
486                    queue.push_back((canonical, child));
487                }
488            }
489        }
490    }
491    Ok(out)
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497
498    #[test]
499    fn resolves_cat_like_ldd() {
500        let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
501        let r = resolve(&cat).expect("resolve");
502        let libc = r.libs.iter().any(|p| {
503            p.file_name()
504                .is_some_and(|n| n.to_string_lossy().starts_with("libc.so"))
505        });
506        assert!(libc, "libc not found in {r:?}");
507        assert!(r.interpreter.is_some(), "cat should be dynamically linked");
508        assert!(r.missing.is_empty(), "{r:?}");
509        // Compare with ldd when available.
510        if let Ok(out) = std::process::Command::new("ldd").arg(&cat).output() {
511            let text = String::from_utf8_lossy(&out.stdout);
512            for line in text.lines() {
513                if let Some((_, rest)) = line.split_once("=> ") {
514                    if let Some(path) = rest.split_whitespace().next() {
515                        let p = std::fs::canonicalize(path).expect("ldd path exists");
516                        assert!(r.libs.contains(&p), "ldd found {p:?}, we did not: {r:?}");
517                    }
518                }
519            }
520        }
521    }
522
523    #[test]
524    fn rejects_non_elf_and_scripts() {
525        let dir = tempfile::tempdir().expect("tempdir");
526        let script = dir.path().join("s");
527        std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write");
528        assert!(matches!(resolve(&script), Err(ElfError::Script(_))));
529        let junk = dir.path().join("j");
530        std::fs::write(&junk, vec![0u8; 100]).expect("write");
531        assert!(matches!(resolve(&junk), Err(ElfError::Malformed { .. })));
532        let truncated = dir.path().join("t");
533        let mut bytes = std::fs::read("/bin/cat").expect("read cat");
534        bytes.truncate(200);
535        std::fs::write(&truncated, bytes).expect("write");
536        assert!(resolve(&truncated).is_err());
537    }
538
539    #[test]
540    fn origin_expansion() {
541        let o = Path::new("/opt/app/bin");
542        assert_eq!(
543            expand_origin("$ORIGIN/../lib", o),
544            Some(PathBuf::from("/opt/app/bin/../lib"))
545        );
546        assert_eq!(
547            expand_origin("${ORIGIN}/lib", o),
548            Some(PathBuf::from("/opt/app/bin/lib"))
549        );
550        assert_eq!(expand_origin("$LIB/x", o), None);
551        assert_eq!(expand_origin("lib", o), None);
552    }
553}