Skip to main content

sqlite_graphrag/extract/llm_embedding/
binary.rs

1//! Binary resolution for headless LLM embedding CLIs.
2
3/// Follows symlinks and shell-script shim `exec` targets to find
4/// the real ELF binary. Shim wrappers (like `~/.graphrag-shim/codex`)
5/// can strip hardening flags; bypassing them is a security requirement.
6pub fn resolve_real_binary(path: &std::path::Path) -> std::path::PathBuf {
7    if let Ok(canonical) = std::fs::canonicalize(path) {
8        if is_elf_binary(&canonical) {
9            return canonical;
10        }
11        if let Some(exec_target) = extract_exec_target_from_shim(&canonical) {
12            if exec_target.exists() && is_elf_binary(&exec_target) {
13                return exec_target;
14            }
15        }
16        return canonical;
17    }
18    path.to_path_buf()
19}
20
21fn is_elf_binary(path: &std::path::Path) -> bool {
22    std::fs::read(path)
23        .map(|bytes| bytes.len() >= 4 && bytes[..4] == [0x7f, b'E', b'L', b'F'])
24        .unwrap_or(false)
25}
26
27fn extract_exec_target_from_shim(path: &std::path::Path) -> Option<std::path::PathBuf> {
28    let content = std::fs::read_to_string(path).ok()?;
29    if !content.starts_with("#!") {
30        return None;
31    }
32    for line in content.lines().rev() {
33        let trimmed = line.trim();
34        if trimmed.starts_with("exec ") {
35            let after_exec = trimmed.strip_prefix("exec ")?;
36            let binary = after_exec.split_whitespace().next()?;
37            return Some(std::path::PathBuf::from(binary));
38        }
39    }
40    None
41}