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 👇

11.6 KB
Raw Blame
// ©AngelaMos | 2026
// symbolize.rs

use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};

pub const LLVM_SYMBOLIZER_BIN: &str = "llvm-symbolizer";

pub const DEBUGINFOD_URLS: &str = "DEBUGINFOD_URLS";
pub const DEBUGINFOD_DISABLED: &str = "";

pub const SYMBOLIZER_TIMEOUT: Duration = Duration::from_secs(30);
const SYMBOLIZER_POLL: Duration = Duration::from_millis(10);

const UNKNOWN_SYMBOL: &str = "??";
const FRAME_PREFIX: char = '#';
const MODULE_OFFSET_MARKER: &str = "+0x";
const HEX_RADIX: u32 = 16;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameLocation {
    pub line: usize,
    pub module: String,
    pub offset: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Symbol {
    pub function: String,
    pub location: String,
}

#[must_use]
pub fn frame_locations(report: &str) -> Vec<FrameLocation> {
    let mut found = Vec::new();
    for (index, line) in report.lines().enumerate() {
        let trimmed = line.trim_start();
        if !trimmed.starts_with(FRAME_PREFIX) {
            continue;
        }
        let Some(marker) = line.find(MODULE_OFFSET_MARKER) else {
            continue;
        };
        let Some(open) = line[..marker].rfind('(') else {
            continue;
        };
        let Some(close) = line[marker..].find(')').map(|at| marker + at) else {
            continue;
        };
        let inner = &line[open + 1..close];
        let Some((module, offset_text)) = inner.split_once(MODULE_OFFSET_MARKER) else {
            continue;
        };
        let Ok(offset) = u64::from_str_radix(offset_text, HEX_RADIX) else {
            continue;
        };
        found.push(FrameLocation {
            line: index,
            module: module.to_owned(),
            offset,
        });
    }
    found
}

#[must_use]
pub fn apply_symbols(report: &str, symbols: &BTreeMap<(String, u64), Symbol>) -> String {
    let locations = frame_locations(report);
    let mut by_line: BTreeMap<usize, &Symbol> = BTreeMap::new();
    for location in &locations {
        if let Some(symbol) = symbols
            .get(&(location.module.clone(), location.offset))
            .filter(|symbol| symbol.function != UNKNOWN_SYMBOL)
        {
            by_line.insert(location.line, symbol);
        }
    }

    let mut out = String::with_capacity(report.len());
    for (index, line) in report.lines().enumerate() {
        if let Some(symbol) = by_line.get(&index) {
            let head = line
                .find(MODULE_OFFSET_MARKER)
                .and_then(|marker| line[..marker].rfind('('))
                .map_or(line, |open| &line[..open]);
            out.push_str(head.trim_end());
            out.push_str(" in ");
            out.push_str(&symbol.function);
            if symbol.location != UNKNOWN_SYMBOL && !symbol.location.is_empty() {
                out.push(' ');
                out.push_str(&symbol.location);
            }
        } else {
            out.push_str(line);
        }
        out.push('\n');
    }
    out
}

#[must_use]
pub fn parse_symbolizer_output(
    text: &str,
    offsets: &[u64],
    module: &str,
) -> BTreeMap<(String, u64), Symbol> {
    let mut symbols = BTreeMap::new();
    let mut lines = text.lines();
    for offset in offsets {
        let Some(function) = lines.next() else {
            break;
        };
        let location = lines.next().unwrap_or(UNKNOWN_SYMBOL);
        if lines
            .clone()
            .next()
            .is_some_and(|next| next.trim().is_empty())
        {
            lines.next();
        }
        symbols.insert(
            (module.to_owned(), *offset),
            Symbol {
                function: function.trim().to_owned(),
                location: location.trim().to_owned(),
            },
        );
    }
    symbols
}

#[must_use]
pub fn symbolize_report(report: &str) -> String {
    let locations = frame_locations(report);
    if locations.is_empty() {
        return report.to_owned();
    }

    let mut by_module: BTreeMap<String, Vec<u64>> = BTreeMap::new();
    for location in &locations {
        by_module
            .entry(location.module.clone())
            .or_default()
            .push(location.offset);
    }

    let mut symbols = BTreeMap::new();
    for (module, offsets) in by_module {
        if !Path::new(&module).is_file() {
            continue;
        }
        if let Some(resolved) = run_symbolizer(&module, &offsets) {
            symbols.extend(resolved);
        }
    }

    apply_symbols(report, &symbols)
}

fn symbolizer_command(module: &str) -> Command {
    let mut command = Command::new(LLVM_SYMBOLIZER_BIN);
    command
        .arg(format!("--obj={module}"))
        .arg("--functions=short")
        .arg("--demangle")
        .env(DEBUGINFOD_URLS, DEBUGINFOD_DISABLED)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null());
    command
}

fn run_symbolizer(module: &str, offsets: &[u64]) -> Option<BTreeMap<(String, u64), Symbol>> {
    let child = symbolizer_command(module).spawn().ok()?;
    let text = drive_symbolizer(child, offsets, SYMBOLIZER_TIMEOUT)?;
    Some(parse_symbolizer_output(&text, offsets, module))
}

fn reap(child: &mut Child) {
    let _ = child.kill();
    let _ = child.wait();
}

fn drive_symbolizer(mut child: Child, offsets: &[u64], timeout: Duration) -> Option<String> {
    let Some(mut stdin) = child.stdin.take() else {
        reap(&mut child);
        return None;
    };
    for offset in offsets {
        if writeln!(stdin, "0x{offset:x}").is_err() {
            break;
        }
    }
    drop(stdin);

    let Some(mut stdout) = child.stdout.take() else {
        reap(&mut child);
        return None;
    };
    let reader = thread::spawn(move || {
        let mut text = String::new();
        let _ = stdout.read_to_string(&mut text);
        text
    });

    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait() {
            Ok(Some(_)) => break,
            Ok(None) => {
                if Instant::now() >= deadline {
                    reap(&mut child);
                    break;
                }
                thread::sleep(SYMBOLIZER_POLL);
            }
            Err(_) => {
                reap(&mut child);
                break;
            }
        }
    }

    reader.join().ok()
}

#[cfg(test)]
mod tests {
    use std::ffi::OsStr;
    use std::sync::mpsc;

    use super::*;

    const SETTLE_TIMEOUT: Duration = Duration::from_secs(5);
    const SETTLE_BUDGET: Duration = Duration::from_secs(2);
    const NEVER_EXITS_ARG: &str = "60";
    const NEVER_EXITS_TIMEOUT: Duration = Duration::from_millis(100);
    const RETURN_BUDGET: Duration = Duration::from_secs(10);

    const RAW: &str = "\
==38182==ERROR: AddressSanitizer: SEGV on unknown address 0x9526 (pc 0x7fb bp 0x7ff sp 0x7ff T0)
    #0 0x7f66678b253b  (/lib/x86_64-linux-gnu/libc.so.6+0x4553b) (BuildId: 8e9f)
    #1 0x555a29663260  (/opt/out/harness+0x163260) (BuildId: bda3)
    #2 0x555a296caa6e  (/opt/out/harness+0x1caa6e) (BuildId: bda3)
";

    #[test]
    fn extracts_module_and_offset_from_unsymbolized_frames() {
        let found = frame_locations(RAW);
        assert_eq!(found.len(), 3);
        assert_eq!(found[1].module, "/opt/out/harness");
        assert_eq!(found[1].offset, 0x0016_3260);
        assert_eq!(found[1].line, 2);
    }

    #[test]
    fn ignores_lines_that_are_not_frames() {
        let found = frame_locations("no frames here\njust text\n");
        assert!(found.is_empty());
    }

    #[test]
    fn rewrites_frames_with_resolved_symbols() {
        let mut symbols = BTreeMap::new();
        symbols.insert(
            ("/opt/out/harness".to_owned(), 0x0016_3260),
            Symbol {
                function: "magma_log".to_owned(),
                location: "/opt/magma/src/canary.c:92:5".to_owned(),
            },
        );
        let out = apply_symbols(RAW, &symbols);
        assert!(out.contains("#1 0x555a29663260 in magma_log /opt/magma/src/canary.c:92:5"));
        assert!(out.contains("#0 0x7f66678b253b  (/lib/x86_64-linux-gnu/libc.so.6+0x4553b)"));
    }

    #[test]
    fn unresolved_symbols_leave_the_frame_untouched() {
        let mut symbols = BTreeMap::new();
        symbols.insert(
            ("/opt/out/harness".to_owned(), 0x0016_3260),
            Symbol {
                function: UNKNOWN_SYMBOL.to_owned(),
                location: UNKNOWN_SYMBOL.to_owned(),
            },
        );
        let out = apply_symbols(RAW, &symbols);
        assert!(out.contains("(/opt/out/harness+0x163260)"));
        assert!(!out.contains(" in ??"));
    }

    #[test]
    fn parses_symbolizer_pairs_in_order() {
        let text = "magma_log\n/opt/magma/src/canary.c:92:5\n\nMAGMA_png_handle_PLTE\n/repo/pngrutil.c:992:4\n\n";
        let offsets = [0x0016_3260_u64, 0x001c_aa6e_u64];
        let symbols = parse_symbolizer_output(text, &offsets, "/opt/out/harness");
        assert_eq!(
            symbols
                .get(&("/opt/out/harness".to_owned(), 0x0016_3260))
                .unwrap()
                .function,
            "magma_log"
        );
        assert_eq!(
            symbols
                .get(&("/opt/out/harness".to_owned(), 0x001c_aa6e))
                .unwrap()
                .location,
            "/repo/pngrutil.c:992:4"
        );
    }

    #[test]
    fn symbolizing_a_report_without_frames_is_a_noop() {
        assert_eq!(symbolize_report("nothing here\n"), "nothing here\n");
    }

    fn piped(program: &str, arg: Option<&str>) -> Option<Child> {
        let mut command = Command::new(program);
        if let Some(arg) = arg {
            command.arg(arg);
        }
        command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .ok()
    }

    #[test]
    fn the_child_sees_end_of_input_and_exits_on_its_own() {
        let Some(child) = piped("cat", None) else {
            return;
        };
        let started = Instant::now();
        let text = drive_symbolizer(child, &[0x10, 0x20], SETTLE_TIMEOUT)
            .expect("the reader thread must return the child's output");
        let elapsed = started.elapsed();
        assert_eq!(text, "0x10\n0x20\n", "the child's output must be collected");
        assert!(
            elapsed < SETTLE_BUDGET,
            "the child was still waiting for input and had to be killed at the deadline after {elapsed:?}, so stdin is not being closed; output alone cannot detect this because cat writes with raw syscalls and flushes before it dies"
        );
    }

    #[test]
    fn a_child_that_never_exits_is_killed_instead_of_waited_on() {
        let (sender, receiver) = mpsc::channel();
        thread::spawn(move || {
            let outcome = piped("sleep", Some(NEVER_EXITS_ARG))
                .map(|child| drive_symbolizer(child, &[0x10], NEVER_EXITS_TIMEOUT));
            let _ = sender.send(outcome);
        });
        assert!(
            receiver.recv_timeout(RETURN_BUDGET).is_ok(),
            "drive_symbolizer never returned: the deadline is not enforced and the crash path can hang forever"
        );
    }

    #[test]
    fn the_symbolizer_never_inherits_a_debuginfod_server() {
        let command = symbolizer_command("/opt/out/harness");
        let found = command
            .get_envs()
            .find(|(key, _)| *key == OsStr::new(DEBUGINFOD_URLS))
            .map(|(_, value)| value);
        assert_eq!(
            found,
            Some(Some(OsStr::new(DEBUGINFOD_DISABLED))),
            "the container exports DEBUGINFOD_URLS, and a symbolizer that inherits it attempts a network fetch per query and never returns; reproduced as a 30s hang on the live crash path"
        );
    }
}