Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

13.1 KB
Raw Blame
// ©AngelaMos | 2026
// artifact.rs

use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

pub const MAX_DEPTH: usize = 12;
pub const MAX_INSPECTED_MEMBERS: usize = 8192;

const ELF_MAGIC: [u8; 4] = [0x7f, b'E', b'L', b'F'];
const BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xc0, 0xde];
const AR_MAGIC: [u8; 8] = *b"!<arch>\n";
const AR_HEADER_LEN: usize = 60;
const AR_SIZE_OFFSET: usize = 48;
const AR_SIZE_END: usize = 58;
const AR_NAME_END: usize = 16;
const SPECIAL_MEMBERS: [&str; 4] = ["/", "//", "/SYM64/", "__.SYMDEF"];
const STATIC_LIB_EXT: &str = "a";
const SHARED_LIB_EXT: &str = "so";
const SHARED_LIB_INFIX: &str = ".so.";
const EXCLUDED_DIRS: [&str; 7] = [
    "CMakeFiles",
    "meson-private",
    "meson-logs",
    "meson-info",
    ".git",
    "Testing",
    "_deps",
];
const EXCLUDED_PREFIXES: [&str; 2] = ["conftest", "cmTC_"];

#[derive(Debug, thiserror::Error)]
pub enum ArtifactError {
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArtifactKind {
    StaticLib,
    SharedLib,
    Executable,
}

impl ArtifactKind {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            ArtifactKind::StaticLib => "static-lib",
            ArtifactKind::SharedLib => "shared-lib",
            ArtifactKind::Executable => "executable",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Artifact {
    pub path: PathBuf,
    pub kind: ArtifactKind,
}

fn is_excluded_dir(name: &str) -> bool {
    EXCLUDED_DIRS.contains(&name)
}

fn is_excluded_file(name: &str) -> bool {
    EXCLUDED_PREFIXES
        .iter()
        .any(|prefix| name.starts_with(prefix))
}

#[must_use]
pub fn is_elf(path: &Path) -> bool {
    let Ok(mut file) = std::fs::File::open(path) else {
        return false;
    };
    let mut magic = [0u8; ELF_MAGIC.len()];
    file.read_exact(&mut magic).is_ok() && magic == ELF_MAGIC
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MemberKinds {
    pub bitcode: usize,
    pub native: usize,
}

impl MemberKinds {
    #[must_use]
    pub fn merge(self, other: MemberKinds) -> MemberKinds {
        MemberKinds {
            bitcode: self.bitcode + other.bitcode,
            native: self.native + other.native,
        }
    }

    #[must_use]
    pub fn holds_bitcode(self) -> bool {
        self.bitcode > 0
    }

    #[must_use]
    pub fn is_mixed(self) -> bool {
        self.bitcode > 0 && self.native > 0
    }
}

fn classify_archive(file: &mut std::fs::File) -> std::io::Result<MemberKinds> {
    let mut kinds = MemberKinds::default();
    let mut offset = AR_MAGIC.len() as u64;
    for _ in 0..MAX_INSPECTED_MEMBERS {
        file.seek(SeekFrom::Start(offset))?;
        let mut header = [0u8; AR_HEADER_LEN];
        if file.read_exact(&mut header).is_err() {
            return Ok(kinds);
        }
        let size: u64 = String::from_utf8_lossy(&header[AR_SIZE_OFFSET..AR_SIZE_END])
            .trim()
            .parse()
            .unwrap_or(0);
        let name = String::from_utf8_lossy(&header[..AR_NAME_END]);
        let name = name.trim();
        let mut magic = [0u8; BITCODE_MAGIC.len()];
        let read = file.read(&mut magic)?;
        if read == BITCODE_MAGIC.len() && !SPECIAL_MEMBERS.contains(&name) {
            if magic == BITCODE_MAGIC {
                kinds.bitcode += 1;
            } else if magic == ELF_MAGIC {
                kinds.native += 1;
            }
        }
        offset += AR_HEADER_LEN as u64 + size + (size % 2);
    }
    Ok(kinds)
}

#[must_use]
pub fn member_kinds(path: &Path) -> MemberKinds {
    let Ok(mut file) = std::fs::File::open(path) else {
        return MemberKinds::default();
    };
    let mut head = [0u8; AR_MAGIC.len()];
    let Ok(read) = file.read(&mut head) else {
        return MemberKinds::default();
    };
    if read >= BITCODE_MAGIC.len() && head[..BITCODE_MAGIC.len()] == BITCODE_MAGIC {
        return MemberKinds {
            bitcode: 1,
            native: 0,
        };
    }
    if read != AR_MAGIC.len() || head != AR_MAGIC {
        return MemberKinds::default();
    }
    classify_archive(&mut file).unwrap_or_default()
}

#[must_use]
pub fn holds_llvm_bitcode(path: &Path) -> bool {
    member_kinds(path).holds_bitcode()
}

fn is_executable_file(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
}

#[must_use]
pub fn classify(path: &Path) -> Option<ArtifactKind> {
    let name = path.file_name()?.to_string_lossy().into_owned();
    if is_excluded_file(&name) {
        return None;
    }
    if path.extension().is_some_and(|ext| ext == STATIC_LIB_EXT) {
        return Some(ArtifactKind::StaticLib);
    }
    if path.extension().is_some_and(|ext| ext == SHARED_LIB_EXT) || name.contains(SHARED_LIB_INFIX)
    {
        return Some(ArtifactKind::SharedLib);
    }
    if is_executable_file(path) && is_elf(path) {
        return Some(ArtifactKind::Executable);
    }
    None
}

fn walk(root: &Path, depth: usize, found: &mut Vec<Artifact>) -> Result<(), ArtifactError> {
    if depth > MAX_DEPTH || !root.is_dir() {
        return Ok(());
    }
    let entries = std::fs::read_dir(root).map_err(|source| ArtifactError::Io {
        path: root.to_path_buf(),
        source,
    })?;
    for entry in entries {
        let entry = entry.map_err(|source| ArtifactError::Io {
            path: root.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let file_type = entry.file_type().map_err(|source| ArtifactError::Io {
            path: path.clone(),
            source,
        })?;
        if file_type.is_symlink() {
            continue;
        }
        if file_type.is_dir() {
            if is_excluded_dir(&entry.file_name().to_string_lossy()) {
                continue;
            }
            walk(&path, depth + 1, found)?;
            continue;
        }
        if let Some(kind) = classify(&path) {
            found.push(Artifact { path, kind });
        }
    }
    Ok(())
}

pub fn discover(roots: &[PathBuf]) -> Result<Vec<Artifact>, ArtifactError> {
    let mut found = Vec::new();
    for root in roots {
        walk(root, 0, &mut found)?;
    }
    found.sort_by(|left, right| left.path.cmp(&right.path));
    found.dedup_by(|left, right| left.path == right.path);
    Ok(found)
}

#[must_use]
pub fn libraries(found: &[Artifact]) -> Vec<&Artifact> {
    found
        .iter()
        .filter(|artifact| artifact.kind != ArtifactKind::Executable)
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Tree {
        root: PathBuf,
    }

    impl Tree {
        fn new(name: &str) -> Self {
            let root = lisdex_core::scratch::path(&format!("artifact-{name}"));
            let _ = std::fs::remove_dir_all(&root);
            std::fs::create_dir_all(&root).unwrap();
            Self { root }
        }

        fn file(self, name: &str, bytes: &[u8]) -> Self {
            let path = self.root.join(name);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, bytes).unwrap();
            self
        }

        fn elf(self, name: &str) -> Self {
            use std::os::unix::fs::PermissionsExt;

            let path = self.root.join(name);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, ELF_MAGIC).unwrap();
            let mut perms = std::fs::metadata(&path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&path, perms).unwrap();
            self
        }

        fn discover(&self) -> Vec<Artifact> {
            discover(std::slice::from_ref(&self.root)).unwrap()
        }
    }

    #[test]
    fn static_libraries_are_found() {
        let found = Tree::new("static")
            .file("libpng16.a", b"!<arch>")
            .discover();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].kind, ArtifactKind::StaticLib);
    }

    #[test]
    fn versioned_shared_libraries_are_found() {
        let found = Tree::new("shared")
            .file("libtiff.so.6.0.2", b"\x7fELF")
            .file("libz.so", b"\x7fELF")
            .discover();
        assert_eq!(found.len(), 2);
        assert!(found.iter().all(|a| a.kind == ArtifactKind::SharedLib));
    }

    #[test]
    fn elf_executables_are_found() {
        let found = Tree::new("exe").elf("sqlite3").discover();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].kind, ArtifactKind::Executable);
    }

    #[test]
    fn shell_scripts_are_not_artifacts() {
        let found = Tree::new("script").elf("run.sh").discover();
        let found = found
            .into_iter()
            .filter(|a| a.path.ends_with("run.sh"))
            .count();
        assert_eq!(found, 1);
        let plain = Tree::new("script2")
            .file("libtool", b"#!/bin/sh\n")
            .discover();
        assert!(plain.is_empty());
    }

    #[test]
    fn cmake_compiler_probe_binaries_are_excluded() {
        let found = Tree::new("cmakefiles")
            .elf("CMakeFiles/3.28.3/CompilerIdC/a.out")
            .file("CMakeFiles/probe.a", b"!<arch>")
            .discover();
        assert!(
            found.is_empty(),
            "instrumented compiler probes would falsely satisfy verification"
        );
    }

    #[test]
    fn autotools_conftest_leftovers_are_excluded() {
        let found = Tree::new("conftest").elf("conftest").discover();
        assert!(found.is_empty());
    }

    #[test]
    fn meson_internal_directories_are_excluded() {
        let found = Tree::new("meson")
            .file("meson-private/sanitycheckc.a", b"!<arch>")
            .file("src/libfoo.a", b"!<arch>")
            .discover();
        assert_eq!(found.len(), 1);
        assert!(found[0].path.ends_with("src/libfoo.a"));
    }

    #[test]
    fn nested_libtool_output_is_found() {
        let found = Tree::new("libtool")
            .file(".libs/libpng16.a", b"!<arch>")
            .discover();
        assert_eq!(found.len(), 1);
    }

    #[test]
    fn discovery_is_sorted_and_deduplicated() {
        let tree = Tree::new("dedup")
            .file("b/libb.a", b"!<arch>")
            .file("a/liba.a", b"!<arch>");
        let found = discover(&[tree.root.clone(), tree.root.clone()]).unwrap();
        assert_eq!(found.len(), 2);
        assert!(found[0].path.ends_with("a/liba.a"));
    }

    #[test]
    fn object_files_are_not_reported_as_artifacts() {
        let found = Tree::new("objects").file("png.o", b"\x7fELF").discover();
        assert!(found.is_empty());
    }

    #[test]
    fn libraries_filters_out_executables() {
        let tree = Tree::new("filter").file("libfoo.a", b"!<arch>").elf("tool");
        let found = tree.discover();
        assert_eq!(found.len(), 2);
        assert_eq!(libraries(&found).len(), 1);
    }

    #[test]
    fn a_bare_bitcode_object_is_recognised() {
        let tree = Tree::new("bitcode-object").file("png.bc", &BITCODE_MAGIC);
        assert!(holds_llvm_bitcode(&tree.root.join("png.bc")));
    }

    #[test]
    fn an_archive_of_bitcode_members_is_recognised() {
        let mut archive = Vec::new();
        archive.extend_from_slice(&AR_MAGIC);
        let payload = [BITCODE_MAGIC.as_slice(), b"rest"].concat();
        let mut header = [b' '; AR_HEADER_LEN];
        header[..8].copy_from_slice(b"png.o/  ");
        let size = format!("{}", payload.len());
        header[AR_SIZE_OFFSET..AR_SIZE_OFFSET + size.len()].copy_from_slice(size.as_bytes());
        header[58..60].copy_from_slice(b"`\n");
        archive.extend_from_slice(&header);
        archive.extend_from_slice(&payload);

        let tree = Tree::new("bitcode-archive").file("libpng.a", &archive);
        assert!(holds_llvm_bitcode(&tree.root.join("libpng.a")));
    }

    #[test]
    fn an_archive_of_native_objects_is_not_bitcode() {
        let mut archive = Vec::new();
        archive.extend_from_slice(&AR_MAGIC);
        let payload = [ELF_MAGIC.as_slice(), b"rest"].concat();
        let mut header = [b' '; AR_HEADER_LEN];
        header[..8].copy_from_slice(b"png.o/  ");
        let size = format!("{}", payload.len());
        header[AR_SIZE_OFFSET..AR_SIZE_OFFSET + size.len()].copy_from_slice(size.as_bytes());
        header[58..60].copy_from_slice(b"`\n");
        archive.extend_from_slice(&header);
        archive.extend_from_slice(&payload);

        let tree = Tree::new("native-archive").file("libpng.a", &archive);
        assert!(!holds_llvm_bitcode(&tree.root.join("libpng.a")));
    }

    #[test]
    fn a_text_file_is_not_bitcode() {
        let tree = Tree::new("text").file("README.md", b"# not an object\n");
        assert!(!holds_llvm_bitcode(&tree.root.join("README.md")));
    }

    #[test]
    fn a_missing_file_is_not_bitcode() {
        assert!(!holds_llvm_bitcode(Path::new(
            "/lisdex/definitely/missing.a"
        )));
    }

    #[test]
    fn a_missing_directory_yields_no_artifacts() {
        let missing = lisdex_core::scratch::path("artifact-missing");
        let _ = std::fs::remove_dir_all(&missing);
        assert!(discover(&[missing]).unwrap().is_empty());
    }
}