Skip to main content

kh_loader/
deps.rs

1//! Dependency walk helpers for multi-image load (Phase 6 dyld-lite).
2//!
3//! Main is mapped outside the BFS; this module only enqueues and classifies
4//! followable load edges (`LC_LOAD_DYLIB` / weak / reexport).
5
6use std::path::{Path, PathBuf};
7
8use crate::image::{DylibDep, DylibKind, MachOImage};
9
10/// Maximum number of **dylib** images (not counting main).
11pub const MAX_DYLIBS: usize = 64;
12
13/// One pending dependency edge in the BFS queue.
14#[derive(Debug, Clone)]
15pub struct DepEdge {
16    /// Install name from the load command.
17    pub install_name: String,
18    /// Load command kind (Load / Weak / Reexport).
19    pub kind: DylibKind,
20    /// Host directory of the image that issued this load command.
21    pub loader_dir: PathBuf,
22    /// Rpath list for resolve: loader rpaths then main rpaths.
23    pub rpaths: Vec<String>,
24}
25
26/// Returns true when Phase 6 follows this dependency kind as a map edge.
27#[must_use]
28pub const fn is_followable(kind: DylibKind) -> bool {
29    matches!(
30        kind,
31        DylibKind::Load | DylibKind::Weak | DylibKind::Reexport
32    )
33}
34
35/// Collects followable deps from an image into BFS edges.
36#[must_use]
37pub fn edges_from_image(image: &MachOImage, loader_dir: &Path, rpaths: &[String]) -> Vec<DepEdge> {
38    image
39        .dylibs
40        .iter()
41        .filter(|dep| is_followable(dep.kind))
42        .map(|dep| DepEdge {
43            install_name: dep.name.clone(),
44            kind: dep.kind,
45            loader_dir: loader_dir.to_path_buf(),
46            rpaths: rpaths.to_vec(),
47        })
48        .collect()
49}
50
51/// Concatenates loader then main rpath lists (loader first).
52#[must_use]
53pub fn concat_rpaths(loader_rpaths: &[String], main_rpaths: &[String]) -> Vec<String> {
54    let mut out = Vec::with_capacity(loader_rpaths.len().saturating_add(main_rpaths.len()));
55    out.extend(loader_rpaths.iter().cloned());
56    out.extend(main_rpaths.iter().cloned());
57    out
58}
59
60/// Install name for a mapped image: `LC_ID_DYLIB` if present, else fallback.
61#[must_use]
62pub fn image_install_name(image: &MachOImage, fallback: &str) -> String {
63    image
64        .dylibs
65        .iter()
66        .find(|d| d.kind == DylibKind::Id)
67        .map_or_else(|| fallback.to_owned(), |d| d.name.clone())
68}
69
70/// Filters dylib deps by followable kinds (for tests / inspect helpers).
71#[must_use]
72pub fn followable_deps(image: &MachOImage) -> Vec<&DylibDep> {
73    image
74        .dylibs
75        .iter()
76        .filter(|d| is_followable(d.kind))
77        .collect()
78}