use std::{
io::Read as _,
path::{Path, PathBuf},
};
const DEFAULT_PATHS: [&str; 5] = [
"/usr/local/lib64",
"/usr/lib64",
"/lib64",
"/usr/local/lib",
"/usr/lib",
];
const SYSROOT_PREFIX: char = '=';
pub fn find_library(
name: &str,
search: &[PathBuf],
sysroot: Option<&Path>,
) -> Option<PathBuf> {
find_library_kind(name, search, sysroot, LibKind::Any)
}
pub fn find_macho_library(
name: &str,
search: &[PathBuf],
sysroot: Option<&Path>,
) -> Option<PathBuf> {
let exact = name.strip_prefix(':');
let look = |dir: &Path| {
if let Some(file) = exact {
let path = dir.join(file);
return path.exists().then_some(path);
}
for suffix in [".tbd", ".dylib", ".a"] {
let path = dir.join(format!("lib{name}{suffix}"));
if path.exists() {
return Some(path);
}
}
None
};
for dir in search.iter().map(|dir| rooted_search(sysroot, dir)) {
if let Some(found) = look(&dir) {
return Some(found);
}
}
for dir in DEFAULT_PATHS {
if let Some(found) = look(&rooted(sysroot, dir)) {
return Some(found);
}
}
None
}
pub fn find_macho_framework(
name: &str,
search: &[PathBuf],
sysroot: Option<&Path>,
) -> Option<PathBuf> {
let look = |dir: &Path| {
let path = dir
.join(format!("{name}.framework"))
.join(format!("{name}.tbd"));
path.exists().then_some(path)
};
for dir in search {
if let Some(found) = look(dir) {
return Some(found);
}
}
for dir in ["/System/Library/Frameworks", "/Library/Frameworks"] {
if let Some(found) = look(&rooted(sysroot, dir)) {
return Some(found);
}
}
None
}
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum LibKind {
#[default]
Any,
ArchiveOnly,
}
pub fn find_library_kind(
name: &str,
search: &[PathBuf],
sysroot: Option<&Path>,
kind: LibKind,
) -> Option<PathBuf> {
let exact = name.strip_prefix(':');
let look = |dir: &Path| match (exact, kind) {
(Some(file), LibKind::Any) => find_exact(file, dir),
(Some(file), LibKind::ArchiveOnly) => {
let path = dir.join(file);
has_magic(&path, ARCHIVE_MAGIC).then_some(path)
}
(None, LibKind::Any) => find_in(name, dir),
(None, LibKind::ArchiveOnly) => find_archive(name, dir),
};
for dir in search.iter().map(|dir| rooted_search(sysroot, dir)) {
if let Some(found) = look(&dir) {
return Some(found);
}
}
for dir in DEFAULT_PATHS {
if let Some(found) = look(&rooted(sysroot, dir)) {
return Some(found);
}
}
None
}
pub fn find_in_paths(
file: &str,
search: &[PathBuf],
sysroot: Option<&Path>,
) -> Option<PathBuf> {
let named = |dir: &Path| {
let path = dir.join(file);
path.exists().then_some(path)
};
for dir in search.iter().map(|dir| rooted_search(sysroot, dir)) {
if let Some(found) = named(&dir) {
return Some(found);
}
}
for dir in DEFAULT_PATHS {
if let Some(found) = named(&rooted(sysroot, dir)) {
return Some(found);
}
}
None
}
fn rooted_search(sysroot: Option<&Path>, dir: &Path) -> PathBuf {
let Some(rest) = dir.to_str().and_then(|d| d.strip_prefix(SYSROOT_PREFIX))
else {
return dir.to_path_buf();
};
rooted(sysroot, rest)
}
pub fn rooted(sysroot: Option<&Path>, path: &str) -> PathBuf {
sysroot.map_or_else(
|| PathBuf::from(path),
|root| root.join(path.trim_start_matches('/')),
)
}
fn find_exact(file: &str, dir: &Path) -> Option<PathBuf> {
let path = dir.join(file);
(has_magic(&path, ARCHIVE_MAGIC) || is_linkable(&path)).then_some(path)
}
fn find_in(name: &str, dir: &Path) -> Option<PathBuf> {
let prefix = format!("lib{name}.so.");
let bare = format!("lib{name}.so");
let lead = dir.join(&bare);
if is_linkable(&lead) {
return Some(lead);
}
let entries = std::fs::read_dir(dir).ok()?;
let mut best: Option<(PathBuf, Vec<u64>, String)> = None;
let mut bare_so: Option<PathBuf> = None;
for entry in entries.flatten() {
let file_name = entry.file_name();
let Some(fname) = file_name.to_str() else {
continue;
};
if fname == bare {
bare_so = Some(entry.path());
} else if let Some(rest) = fname.strip_prefix(&prefix) {
let key = version_key(rest);
let better =
best.as_ref().is_none_or(|(_, prev_key, prev_name)| {
(&key, fname) > (prev_key, prev_name.as_str())
});
if better {
best = Some((entry.path(), key, fname.to_owned()));
}
}
}
if let Some(path) = bare_so.filter(|p| is_linkable(p)) {
return Some(path);
}
if let Some(path) = best.map(|(p, _, _)| p).filter(|p| is_linkable(p)) {
return Some(path);
}
let archive = dir.join(format!("lib{name}.a"));
(has_magic(&archive, ARCHIVE_MAGIC) || is_script(&archive))
.then_some(archive)
}
fn find_archive(name: &str, dir: &Path) -> Option<PathBuf> {
let archive = dir.join(format!("lib{name}.a"));
(has_magic(&archive, ARCHIVE_MAGIC) || is_script(&archive))
.then_some(archive)
}
fn is_linkable(path: &Path) -> bool {
has_magic(path, ELF_MAGIC) || is_script(path)
}
fn is_script(path: &Path) -> bool {
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut head = [0u8; SCRIPT_PROBE];
let mut filled = 0usize;
while filled < head.len() {
let Ok(n @ 1..) = file.read(&mut head[filled..]) else {
break;
};
filled = filled.saturating_add(n);
}
crate::script::looks_like(head.get(..filled).unwrap_or(&head))
}
const SCRIPT_PROBE: usize = 64;
fn version_key(suffix: &str) -> Vec<u64> {
suffix
.split('.')
.map(|part| part.parse::<u64>().unwrap_or(0))
.collect()
}
const ELF_MAGIC: &[u8] = b"\x7fELF";
const ARCHIVE_MAGIC: &[u8] = b"!<arch>\n";
const MAGIC_MAX: usize = 8;
fn has_magic(path: &Path, magic: &[u8]) -> bool {
debug_assert!(magic.len() <= MAGIC_MAX, "magic fits the probe buffer");
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut head = [0u8; MAGIC_MAX];
let Some(slot) = head.get_mut(..magic.len()) else {
return false;
};
let mut filled = 0usize;
while filled < slot.len() {
let Ok(n @ 1..) = file.read(&mut slot[filled..]) else {
return false;
};
filled = filled.saturating_add(n);
}
slot == magic
}