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/// Resolves the interpreter and all shared libraries of `binary`.
427pub fn resolve(binary: &Path) -> Result<Resolved, ElfError> {
428    let main = read_dyn_info(binary)?;
429    let kind = main.kind;
430    let mut out = Resolved::default();
431    if let Some(interp) = &main.interp {
432        out.interpreter = Some(std::fs::canonicalize(interp).unwrap_or_else(|_| interp.into()));
433        out.interpreter_literal = Some(PathBuf::from(interp));
434    }
435    // glibc: DT_RPATH of the executable applies to all its dependencies unless DT_RUNPATH exists.
436    let exe_rpath: Vec<String> = if main.runpath.is_empty() {
437        main.rpath.clone()
438    } else {
439        Vec::new()
440    };
441
442    let mut seen_names: HashSet<String> = HashSet::new();
443    let mut seen_paths: HashSet<PathBuf> = HashSet::new();
444    let mut queue: VecDeque<(PathBuf, DynInfo)> = VecDeque::new();
445    queue.push_back((binary.to_path_buf(), main));
446
447    while let Some((obj_path, info)) = queue.pop_front() {
448        let origin = obj_path.parent().unwrap_or(Path::new("/")).to_path_buf();
449        let mut dirs: Vec<PathBuf> = Vec::new();
450        if info.runpath.is_empty() {
451            for e in info.rpath.iter().chain(exe_rpath.iter()) {
452                dirs.extend(expand_origin(e, &origin));
453            }
454        }
455        for e in &info.runpath {
456            dirs.extend(expand_origin(e, &origin));
457        }
458        dirs.extend(system_dirs().iter().cloned());
459
460        for name in &info.needed {
461            if !seen_names.insert(name.clone()) {
462                continue;
463            }
464            let found = if name.contains('/') {
465                Some(PathBuf::from(name)).filter(|p| p.is_file())
466            } else {
467                dirs.iter()
468                    .map(|d| d.join(name))
469                    .find(|p| p.is_file() && kind_of(p) == kind)
470            };
471            let Some(found) = found else {
472                out.missing.push(name.clone());
473                continue;
474            };
475            // Optimized variants the loader may prefer (glibc-hwcaps).
476            if let Some(dir) = found.parent() {
477                for variant in glob_last_component(&dir.join("glibc-hwcaps").join("*")) {
478                    let candidate = variant.join(name);
479                    if candidate.is_file() {
480                        if let Ok(c) = std::fs::canonicalize(&candidate) {
481                            if seen_paths.insert(c.clone()) {
482                                out.libs.push(c);
483                            }
484                        }
485                    }
486                }
487            }
488            let canonical = std::fs::canonicalize(&found).unwrap_or_else(|_| found.clone());
489            out.found.push((found, canonical.clone()));
490            if seen_paths.insert(canonical.clone()) {
491                out.libs.push(canonical.clone());
492                if let Ok(child) = read_dyn_info(&canonical) {
493                    queue.push_back((canonical, child));
494                }
495            }
496        }
497    }
498    Ok(out)
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[test]
506    fn resolves_cat_like_ldd() {
507        let cat = std::fs::canonicalize("/bin/cat").expect("cat exists");
508        let r = resolve(&cat).expect("resolve");
509        let libc = r.libs.iter().any(|p| {
510            p.file_name()
511                .is_some_and(|n| n.to_string_lossy().starts_with("libc.so"))
512        });
513        assert!(libc, "libc not found in {r:?}");
514        assert!(r.interpreter.is_some(), "cat should be dynamically linked");
515        assert!(r.missing.is_empty(), "{r:?}");
516        // Compare with ldd when available.
517        if let Ok(out) = std::process::Command::new("ldd").arg(&cat).output() {
518            let text = String::from_utf8_lossy(&out.stdout);
519            for line in text.lines() {
520                if let Some((_, rest)) = line.split_once("=> ") {
521                    if let Some(path) = rest.split_whitespace().next() {
522                        let p = std::fs::canonicalize(path).expect("ldd path exists");
523                        assert!(r.libs.contains(&p), "ldd found {p:?}, we did not: {r:?}");
524                    }
525                }
526            }
527        }
528    }
529
530    #[test]
531    fn rejects_non_elf_and_scripts() {
532        let dir = tempfile::tempdir().expect("tempdir");
533        let script = dir.path().join("s");
534        std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write");
535        assert!(matches!(resolve(&script), Err(ElfError::Script(_))));
536        let junk = dir.path().join("j");
537        std::fs::write(&junk, vec![0u8; 100]).expect("write");
538        assert!(matches!(resolve(&junk), Err(ElfError::Malformed { .. })));
539        let truncated = dir.path().join("t");
540        let mut bytes = std::fs::read("/bin/cat").expect("read cat");
541        bytes.truncate(200);
542        std::fs::write(&truncated, bytes).expect("write");
543        assert!(resolve(&truncated).is_err());
544    }
545
546    #[test]
547    fn origin_expansion() {
548        let o = Path::new("/opt/app/bin");
549        assert_eq!(
550            expand_origin("$ORIGIN/../lib", o),
551            Some(PathBuf::from("/opt/app/bin/../lib"))
552        );
553        assert_eq!(
554            expand_origin("${ORIGIN}/lib", o),
555            Some(PathBuf::from("/opt/app/bin/lib"))
556        );
557        assert_eq!(expand_origin("$LIB/x", o), None);
558        assert_eq!(expand_origin("lib", o), None);
559    }
560}