1use 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#[derive(Debug, thiserror::Error)]
21pub enum ElfError {
22 #[error("cannot read {path}: {source}")]
24 Io {
25 path: PathBuf,
27 source: std::io::Error,
29 },
30 #[error("{0} is a script; cants must currently be native ELF executables")]
32 Script(PathBuf),
33 #[error("{path} is not a usable ELF executable: {reason}")]
35 Malformed {
36 path: PathBuf,
38 reason: &'static str,
40 },
41}
42
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct Resolved {
46 pub interpreter: Option<PathBuf>,
48 pub libs: Vec<PathBuf>,
50 pub missing: Vec<String>,
52 pub interpreter_literal: Option<PathBuf>,
54 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
69const 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 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); };
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
326fn 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
387fn 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 return None;
422 }
423 Some(PathBuf::from(expanded))
424}
425
426enum Search<'a> {
428 Host,
430 Root(&'a Path),
432}
433
434pub 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
446fn 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 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 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
489pub fn resolve(binary: &Path) -> Result<Resolved, ElfError> {
491 resolve_with(binary, &Search::Host)
492}
493
494pub 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 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 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 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; };
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 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 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 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 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
753 const HOST: u16 = if cfg!(target_arch = "x86_64") {
755 62
756 } else if cfg!(target_arch = "aarch64") {
757 183
758 } else {
759 243
760 };
761
762 #[derive(Default)]
767 struct Synth {
768 is_32: bool,
769 big: bool,
770 interp: Option<&'static str>,
771 needed: Vec<&'static str>,
772 rpath: Option<&'static str>,
773 runpath: Option<&'static str>,
774 }
775
776 type Edit<'a> = &'a dyn Fn(&mut Built);
778
779 struct Built {
780 bytes: Vec<u8>,
781 dynamic: usize,
783 }
784
785 fn put(buf: &mut Vec<u8>, off: usize, len: usize, v: u64, little: bool) {
786 if buf.len() < off + len {
787 buf.resize(off + len, 0);
788 }
789 for i in 0..len {
790 let shift = 8 * if little { i } else { len - 1 - i };
791 buf[off + i] = (v >> shift) as u8;
792 }
793 }
794
795 impl Synth {
796 fn build(&self) -> Built {
797 let (is_64, little) = (!self.is_32, !self.big);
798 let (hdr, phent, word) = if is_64 { (64, 56, 8) } else { (52, 32, 4) };
799 let mut strtab = vec![0u8];
800 let mut entries: Vec<(u64, u64)> = Vec::new();
801 let strings = self
802 .needed
803 .iter()
804 .map(|n| (DT_NEEDED, *n))
805 .chain(self.rpath.map(|r| (DT_RPATH, r)))
806 .chain(self.runpath.map(|r| (DT_RUNPATH, r)));
807 for (tag, s) in strings {
808 entries.push((tag, strtab.len() as u64));
809 strtab.extend_from_slice(s.as_bytes());
810 strtab.push(0);
811 }
812 let has_dynamic = !entries.is_empty();
813 let nseg = 1 + usize::from(self.interp.is_some()) + usize::from(has_dynamic);
814 let interp: Vec<u8> = self
815 .interp
816 .map(|i| [i.as_bytes(), b"\0"].concat())
817 .unwrap_or_default();
818 let interp_at = hdr + phent * nseg;
819 let strtab_at = interp_at + interp.len();
820 let dynamic = (strtab_at + strtab.len()).next_multiple_of(8);
821 entries.push((DT_STRTAB, strtab_at as u64));
822 entries.push((DT_STRSZ, strtab.len() as u64));
823 entries.push((DT_NULL, 0));
824 let dyn_size = entries.len() * 2 * word;
825 let end = dynamic + if has_dynamic { dyn_size } else { 0 };
826
827 let mut b = vec![0u8; end];
828 b[..4].copy_from_slice(b"\x7fELF");
829 b[4] = if is_64 { 2 } else { 1 };
830 b[5] = if little { 1 } else { 2 };
831 b[6] = 1;
832 put(&mut b, 16, 2, 3, little); put(&mut b, 18, 2, u64::from(HOST), little);
834 let (phoff, phentsize, phnum) = if is_64 { (32, 54, 56) } else { (28, 42, 44) };
835 put(&mut b, phoff, word, hdr as u64, little);
836 put(&mut b, phentsize, 2, phent as u64, little);
837 put(&mut b, phnum, 2, nseg as u64, little);
838 let mut segs = vec![(PT_LOAD, 0, end)];
839 if self.interp.is_some() {
840 segs.push((PT_INTERP, interp_at, interp.len()));
841 }
842 if has_dynamic {
843 segs.push((PT_DYNAMIC, dynamic, dyn_size));
844 }
845 let (o, v, f) = if is_64 { (8, 16, 32) } else { (4, 8, 16) };
846 for (i, (kind, off, size)) in segs.into_iter().enumerate() {
847 let ph = hdr + i * phent;
848 put(&mut b, ph, 4, u64::from(kind), little);
849 put(&mut b, ph + o, word, off as u64, little);
850 put(&mut b, ph + v, word, off as u64, little);
851 put(&mut b, ph + f, word, size as u64, little);
852 }
853 b[interp_at..strtab_at].copy_from_slice(&interp);
854 b[strtab_at..strtab_at + strtab.len()].copy_from_slice(&strtab);
855 if has_dynamic {
856 for (i, (t, val)) in entries.iter().enumerate() {
857 let at = dynamic + i * 2 * word;
858 put(&mut b, at, word, *t, little);
859 put(&mut b, at + word, word, *val, little);
860 }
861 }
862 Built { bytes: b, dynamic }
863 }
864 }
865
866 fn set_dyn(b: &mut Built, tag: u64, new_tag: u64, val: u64) {
868 let mut at = b.dynamic;
869 loop {
870 let t = uint(&b.bytes[at..at + 8], true);
871 assert_ne!(t, DT_NULL, "no dynamic entry {tag}");
872 if t == tag {
873 put(&mut b.bytes, at, 8, new_tag, true);
874 put(&mut b.bytes, at + 8, 8, val, true);
875 return;
876 }
877 at += 16;
878 }
879 }
880
881 fn info(bytes: &[u8]) -> Result<DynInfo, ElfError> {
882 let dir = tempfile::tempdir().expect("tempdir");
883 let path = dir.path().join("elf");
884 std::fs::write(&path, bytes).expect("write");
885 read_dyn_info(&path)
886 }
887
888 fn reason(bytes: &[u8]) -> &'static str {
889 match info(bytes) {
890 Err(ElfError::Malformed { reason, .. }) => reason,
891 other => panic!("not refused as malformed: {other:?}"),
892 }
893 }
894
895 #[test]
896 fn every_class_and_byte_order_reads_the_same() {
897 for (is_32, big) in [(false, false), (false, true), (true, false), (true, true)] {
898 let bytes = Synth {
899 is_32,
900 big,
901 interp: Some("/lib/ld-test.so.1"),
902 needed: vec!["liba.so.1", "libb.so.2"],
903 rpath: Some("/r1:/r2"),
904 runpath: Some("$ORIGIN/lib"),
905 }
906 .build()
907 .bytes;
908 let i = info(&bytes).expect("reads");
909 let kind = Kind {
910 is_64: !is_32,
911 little: !big,
912 machine: HOST,
913 };
914 assert_eq!(i.kind, Some(kind));
915 assert_eq!(i.interp.as_deref(), Some("/lib/ld-test.so.1"));
916 assert_eq!(i.needed, ["liba.so.1", "libb.so.2"]);
917 assert_eq!(i.rpath, ["/r1", "/r2"]);
918 assert_eq!(i.runpath, ["$ORIGIN/lib"]);
919 let dir = tempfile::tempdir().expect("tempdir");
920 std::fs::write(dir.path().join("e"), &bytes).expect("write");
921 assert_eq!(kind_of(&dir.path().join("e")), Some(kind));
922 }
923 let i = info(&Synth::default().build().bytes).expect("static");
925 assert!(i.interp.is_none() && i.needed.is_empty(), "{i:?}");
926 }
927
928 #[test]
929 fn malformed_files_are_refused_with_a_reason() {
930 let good = || {
931 Synth {
932 interp: Some("/lib/ld.so"),
933 needed: vec!["liba.so"],
934 ..Synth::default()
935 }
936 .build()
937 };
938 let edit = |f: &dyn Fn(&mut Built)| {
939 let mut b = good();
940 f(&mut b);
941 reason(&b.bytes)
942 };
943 let ph = |i: usize, field: usize| 64 + 56 * i + field;
945 let cases: [(Edit<'_>, &str); 16] = [
946 (&|b| b.bytes[4] = 3, "unknown ELF class"),
947 (&|b| b.bytes[5] = 3, "unknown byte order"),
948 (&|b| b.bytes.truncate(60), "truncated header"),
949 (&|b| b.bytes.truncate(40), "not an ELF file"),
950 (
951 &|b| put(&mut b.bytes, 56, 2, MAX_PHNUM + 1, true),
952 "bad program header table",
953 ),
954 (
955 &|b| put(&mut b.bytes, 54, 2, 8, true),
956 "bad program header table",
957 ),
958 (
959 &|b| put(&mut b.bytes, 32, 8, 1 << 20, true),
960 "truncated file",
961 ),
962 (
963 &|b| put(&mut b.bytes, ph(1, 32), 8, 0, true),
964 "bad PT_INTERP",
965 ),
966 (
967 &|b| put(&mut b.bytes, ph(1, 32), 8, MAX_INTERP + 1, true),
968 "bad PT_INTERP",
969 ),
970 (
971 &|b| put(&mut b.bytes, ph(2, 32), 8, MAX_DYNAMIC + 1, true),
972 "PT_DYNAMIC too large",
973 ),
974 (
975 &|b| set_dyn(b, DT_STRTAB, 0x6fff_0000, 0),
976 "dynamic section without string table",
977 ),
978 (
979 &|b| set_dyn(b, DT_STRSZ, DT_STRSZ, MAX_STRTAB + 1),
980 "string table too large",
981 ),
982 (
983 &|b| set_dyn(b, DT_STRTAB, DT_STRTAB, 1 << 40),
984 "string table outside loaded segments",
985 ),
986 (
987 &|b| put(&mut b.bytes, ph(0, 8), 8, u64::MAX, true),
988 "string table offset overflow",
989 ),
990 (
991 &|b| set_dyn(b, DT_NEEDED, DT_NEEDED, 1 << 20),
992 "bad string offset",
993 ),
994 (
995 &|b| set_dyn(b, DT_STRSZ, DT_STRSZ, 2),
996 "unterminated string",
997 ),
998 ];
999 for (f, want) in cases {
1000 assert_eq!(edit(f), want);
1001 }
1002 let mut b = good();
1004 set_dyn(&mut b, DT_NEEDED, 0x6fff_0000, 0);
1005 assert!(info(&b.bytes).expect("reads").needed.is_empty());
1006 let dir = tempfile::tempdir().expect("tempdir");
1008 assert!(matches!(
1009 read_dyn_info(&dir.path().join("missing")),
1010 Err(ElfError::Io { .. })
1011 ));
1012 assert!(matches!(
1013 read_dyn_info(dir.path()),
1014 Err(ElfError::Io { .. })
1015 ));
1016 assert_eq!(kind_of(&dir.path().join("missing")), None);
1017 }
1018
1019 #[test]
1020 fn a_sysroot_is_searched_like_the_loader_does() {
1021 let dir = tempfile::tempdir().expect("tempdir");
1022 let root = std::fs::canonicalize(dir.path())
1023 .expect("canonical")
1024 .join("root");
1025 let t = triplet(HOST);
1026 let write = |rel: &str, s: Synth| {
1027 let p = root.join(rel);
1028 std::fs::create_dir_all(p.parent().expect("parent")).expect("mkdir");
1029 std::fs::write(&p, s.build().bytes).expect("write");
1030 p
1031 };
1032 let lib = |needed: Vec<&'static str>| Synth {
1033 needed,
1034 ..Synth::default()
1035 };
1036 let prog = write(
1037 "usr/bin/prog",
1038 Synth {
1039 interp: Some("/lib/ld-test.so"),
1040 needed: vec![
1041 "libfoo.so.1",
1042 "/lib/libabs.so",
1043 "libgone.so",
1044 "libout.so",
1045 "libpriv.so",
1046 "libbar.so",
1047 ],
1048 runpath: Some("$ORIGIN/../lib/private:/opt/vendor/lib"),
1049 ..Synth::default()
1050 },
1051 );
1052 write("usr/lib/ld-test.so", Synth::default());
1053 write(&format!("usr/lib/{t}/libfoo.so.1"), lib(vec!["libdeep.so"]));
1055 write(
1056 &format!("usr/lib/{t}/glibc-hwcaps/v3/libfoo.so.1"),
1057 Synth::default(),
1058 );
1059 write("usr/lib64/libdeep.so", lib(vec!["libfoo.so.1"]));
1060 write("usr/lib/libabs.so", Synth::default());
1061 write("usr/lib/private/libpriv.so", Synth::default());
1062 write("opt/vendor/lib/libbar.so", Synth::default());
1063 write(
1065 "usr/lib/private/libbar.so",
1066 Synth {
1067 is_32: true,
1068 ..Synth::default()
1069 },
1070 );
1071 let outside = dir.path().join("libout.so");
1073 std::fs::write(&outside, Synth::default().build().bytes).expect("write");
1074 std::os::unix::fs::symlink(&outside, root.join(format!("usr/lib/{t}/libout.so")))
1075 .expect("symlink");
1076
1077 let r = resolve_in(&prog, &root).expect("resolve_in");
1078 assert_eq!(r.missing, ["libgone.so", "libout.so"], "{r:?}");
1079 assert_eq!(
1080 r.interpreter.as_deref(),
1081 Some(root.join("usr/lib/ld-test.so").as_path())
1082 );
1083 assert_eq!(
1084 r.interpreter_literal.as_deref(),
1085 Some(Path::new("/lib/ld-test.so"))
1086 );
1087 let expected = [
1088 format!("usr/lib/{t}/glibc-hwcaps/v3/libfoo.so.1"),
1089 format!("usr/lib/{t}/libfoo.so.1"),
1090 "usr/lib/libabs.so".into(),
1091 "usr/lib/private/libpriv.so".into(),
1092 "opt/vendor/lib/libbar.so".into(),
1093 "usr/lib64/libdeep.so".into(),
1094 ];
1095 let expected: Vec<PathBuf> = expected.iter().map(|p| root.join(p)).collect();
1096 assert_eq!(r.libs, expected);
1097 assert_eq!(r.found.len(), 5, "{r:?}"); }
1099
1100 #[test]
1101 fn ld_so_conf_includes_and_skips_like_glibc() {
1102 let dir = tempfile::tempdir().expect("tempdir");
1103 let d = dir.path();
1104 std::fs::create_dir(d.join("conf.d")).expect("mkdir");
1105 std::fs::write(
1106 d.join("ld.so.conf"),
1107 "# a comment\n\nhwcap 0 nosegneg\ninclude conf.d/*.conf\n\
1108 include /nonexistent/*.conf\nrelative/dir\n/abs/one # trailing\n/abs/one\n",
1109 )
1110 .expect("write");
1111 std::fs::write(d.join("conf.d/b.conf"), "/abs/b\n").expect("write");
1112 std::fs::write(d.join("conf.d/a.conf"), "/abs/a\n").expect("write");
1113 std::fs::write(d.join("conf.d/skip.txt"), "/abs/skipped\n").expect("write");
1114 let looped = d.join("conf.d/z.conf");
1116 std::fs::write(&looped, format!("include {}\n", looped.display())).expect("write");
1117 let mut out = Vec::new();
1118 parse_ld_so_conf(&d.join("ld.so.conf"), &mut out, 0);
1119 let want: Vec<PathBuf> = ["/abs/a", "/abs/b", "/abs/one"]
1120 .iter()
1121 .map(PathBuf::from)
1122 .collect();
1123 assert_eq!(out, want);
1124 parse_ld_so_conf(&d.join("nope"), &mut out, 0);
1126 assert_eq!(out, want);
1127 assert_eq!(
1128 glob_last_component(Path::new("/a/b")),
1129 [PathBuf::from("/a/b")]
1130 );
1131 assert!(glob_last_component(Path::new("/")).is_empty());
1132 assert!(!system_dirs().is_empty());
1133 }
1134}