17.3 KiB · text History bbb2a48
//! Native, JVM and minidump symbolication for Vigil (`Vigil.Symbolic.Native`).
//!
//! * `object_info(data, max_objects)`: what a debug information file is
//!   (sentry-cli `debug-files upload`): every object in it (a fat Mach-O
//!   holds several) with its debug id, code id, arch, kind, format and
//!   features, as Sentry's `DebugInfoFile` reports them.
//! * `symcache_build(data, debug_id, max_size)`: the object's SymCache
//!   (address → function, file, line, inlinees), built once and stored.
//! * `symcache_lookup(symcache, addresses)`: many image-relative addresses
//!   resolved through one SymCache, inlined frames expanded (innermost
//!   first), names demangled.
//! * `proguard_info(data)`, `proguard_remap(mapping, frames, classes)`:
//!   Proguard/R8 mapping UUID and line info; JVM frames and class names
//!   deobfuscated.
//! * `minidump_process(data, max_threads, max_frames)`: a Breakpad/Crashpad
//!   minidump unwound (stack scanning and frame pointers, no symbols) into
//!   threads, frames, modules, system info and the crash reason.
//! * `read_zip(data, max_total, max_files)`: a legacy DIF upload's zip,
//!   inflated under a cap.
//! * `normalize_debug_ids(ids)`: debug ids in any form SDKs send (UUID,
//!   with an age appendix, Breakpad hex) as symbolic writes them.
//!
//! Everything but `normalize_debug_ids` runs on dirty CPU schedulers.
//! Inputs are capped by the caller (Vigil.Symbolic); outputs are capped
//! here.

use std::future::Future;
use std::io::{Cursor, Read};
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};

use rustler::{Atom, Binary, Encoder, Env, NifMap, NifResult, OwnedBinary, Term};
use symbolic_common::{Arch, DebugId, InstructionInfo, Language, Name, NameMangling};
use symbolic_debuginfo::{Archive, FileFormat, Object};
use symbolic_demangle::{Demangle, DemangleOptions};
use symbolic_symcache::{SymCache, SymCacheConverter};

mod atoms {
    rustler::atoms! {
        ok,
        error,
        unsupported,
        invalid,
        not_found,
        too_large,
        too_many_objects,
        too_many_files,
        invalid_zip,
    }
}

// ---------------------------------------------------------------------------
// Debug information files
// ---------------------------------------------------------------------------

#[derive(NifMap)]
struct ObjectInfo {
    debug_id: String,
    code_id: Option<String>,
    arch: String,
    kind: String,
    file_format: String,
    features: Vec<String>,
}

#[rustler::nif(schedule = "DirtyCpu")]
fn object_info<'a>(env: Env<'a>, data: Binary<'a>, max_objects: usize) -> Term<'a> {
    match objects(data.as_slice(), max_objects) {
        Ok(infos) => (atoms::ok(), infos).encode(env),
        Err(reason) => (atoms::error(), reason).encode(env),
    }
}

fn objects(data: &[u8], max_objects: usize) -> Result<Vec<ObjectInfo>, Atom> {
    if Archive::peek(data) == FileFormat::Unknown {
        return Err(atoms::unsupported());
    }
    let archive = Archive::parse(data).map_err(|_| atoms::invalid())?;
    if archive.object_count() > max_objects {
        return Err(atoms::too_many_objects());
    }

    archive
        .objects()
        .map(|object| object.map(|o| info(&o)).map_err(|_| atoms::invalid()))
        .collect()
}

fn info(object: &Object<'_>) -> ObjectInfo {
    // Sentry's feature names (`symtab`, `debug`, `unwind`, `sources`).
    let mut features = Vec::new();
    if object.has_symbols() {
        features.push("symtab".to_owned());
    }
    if object.has_debug_info() {
        features.push("debug".to_owned());
    }
    if object.has_unwind_info() {
        features.push("unwind".to_owned());
    }
    if object.has_sources() {
        features.push("sources".to_owned());
    }

    ObjectInfo {
        debug_id: object.debug_id().to_string(),
        code_id: object.code_id().map(|id| id.to_string()),
        arch: object.arch().name().to_owned(),
        kind: object.kind().name().to_owned(),
        file_format: object.file_format().name().to_owned(),
        features,
    }
}

// ---------------------------------------------------------------------------
// SymCache
// ---------------------------------------------------------------------------

#[rustler::nif(schedule = "DirtyCpu")]
fn symcache_build<'a>(
    env: Env<'a>,
    data: Binary,
    debug_id: Option<String>,
    max_size: usize,
) -> NifResult<Term<'a>> {
    match build(data.as_slice(), debug_id.as_deref(), max_size) {
        Ok(bytes) => Ok((atoms::ok(), to_binary(env, &bytes)?).encode(env)),
        Err(reason) => Ok((atoms::error(), reason).encode(env)),
    }
}

fn build(data: &[u8], debug_id: Option<&str>, max_size: usize) -> Result<Vec<u8>, Atom> {
    let wanted = match debug_id {
        Some(id) => Some(id.parse::<DebugId>().map_err(|_| atoms::invalid())?),
        None => None,
    };

    let archive = Archive::parse(data).map_err(|_| atoms::invalid())?;
    let object = archive
        .objects()
        .filter_map(Result::ok)
        .find(|o| wanted.is_none_or(|id| o.debug_id() == id))
        .ok_or_else(atoms::not_found)?;

    let mut converter = SymCacheConverter::new();
    converter
        .process_object(&object)
        .map_err(|_| atoms::invalid())?;

    let mut out = Vec::new();
    converter
        .serialize(&mut out)
        .map_err(|_| atoms::invalid())?;

    if out.len() > max_size {
        return Err(atoms::too_large());
    }
    Ok(out)
}

#[derive(NifMap)]
struct NativeFrame {
    function: Option<String>,
    raw_function: Option<String>,
    symbol: Option<String>,
    abs_path: Option<String>,
    filename: Option<String>,
    lineno: Option<u32>,
    sym_addr: Option<u64>,
    lang: Option<String>,
}

/// `addresses`: `(image-relative address, adjust)`, `adjust` true when the
/// address is a return address to be moved back into its call instruction
/// (every frame but the crashing one, unless the SDK said not to).
#[rustler::nif(schedule = "DirtyCpu")]
fn symcache_lookup<'a>(env: Env<'a>, symcache: Binary, addresses: Vec<(u64, bool)>) -> Term<'a> {
    let cache = match SymCache::parse(symcache.as_slice()) {
        Ok(cache) => cache,
        Err(_) => return (atoms::error(), atoms::invalid()).encode(env),
    };
    let arch = cache.arch();

    let results: Vec<Vec<NativeFrame>> = addresses
        .iter()
        .map(|&(addr, adjust)| lookup(&cache, arch, addr, adjust))
        .collect();

    (atoms::ok(), results).encode(env)
}

fn lookup(cache: &SymCache<'_>, arch: Arch, addr: u64, adjust: bool) -> Vec<NativeFrame> {
    let addr = if adjust && arch != Arch::Unknown {
        InstructionInfo::new(arch, addr)
            .is_crashing_frame(false)
            .caller_address()
    } else {
        addr
    };

    cache
        .lookup(addr)
        .map(|location| {
            let function = location.function();
            let name = function.name();
            let (short, full) = demangle(name, function.language());
            let path = location.file().map(|f| f.full_path());
            let filename = path
                .as_deref()
                .map(|p| p.rsplit(['/', '\\']).next().unwrap_or(p).to_owned());
            let entry = function.entry_pc();

            NativeFrame {
                function: Some(short.clone()),
                raw_function: full.filter(|f| *f != short),
                symbol: (name != short).then(|| name.to_owned()),
                abs_path: path,
                filename,
                lineno: Some(location.line()).filter(|l| *l > 0),
                sym_addr: (entry != u32::MAX).then_some(u64::from(entry)),
                lang: language(function.language()),
            }
        })
        .collect()
}

/// `(name without arguments, full demangled name)`, as Sentry shows
/// `function` and `raw_function`.
fn demangle(name: &str, language: Language) -> (String, Option<String>) {
    let name = Name::new(name, NameMangling::Unknown, language);
    let short = name
        .demangle(DemangleOptions::name_only())
        .unwrap_or_else(|| name.as_str().to_owned());
    let full = name.demangle(DemangleOptions::complete());
    (short, full)
}

fn language(language: Language) -> Option<String> {
    match language {
        Language::Unknown => None,
        other => Some(other.name().to_owned()),
    }
}

// ---------------------------------------------------------------------------
// Proguard
// ---------------------------------------------------------------------------

#[derive(NifMap)]
struct ProguardInfo {
    uuid: String,
    line_info: bool,
}

#[rustler::nif(schedule = "DirtyCpu")]
fn proguard_info<'a>(env: Env<'a>, data: Binary<'a>) -> Term<'a> {
    let mapping = proguard::ProguardMapping::new(data.as_slice());
    if !mapping.is_valid() {
        return (atoms::error(), atoms::invalid()).encode(env);
    }
    let info = ProguardInfo {
        uuid: mapping.uuid().to_string(),
        line_info: mapping.has_line_info(),
    };
    (atoms::ok(), info).encode(env)
}

#[derive(NifMap)]
struct JvmFrame {
    class: String,
    method: String,
    file: Option<String>,
    line: Option<u64>,
}

/// `frames`: `(class, method, line)` (0 for none); `classes`: obfuscated
/// class names (exception types). Each frame answers its deobfuscated
/// frames (several when inlined, innermost first; none when the mapping
/// doesn't know it); each class its original name or `nil`.
#[rustler::nif(schedule = "DirtyCpu")]
fn proguard_remap<'a>(
    env: Env<'a>,
    mapping: Binary,
    frames: Vec<(String, String, u64)>,
    classes: Vec<String>,
) -> Term<'a> {
    let mapping = proguard::ProguardMapping::new(mapping.as_slice());
    if !mapping.is_valid() {
        return (atoms::error(), atoms::invalid()).encode(env);
    }
    let mapper = proguard::ProguardMapper::new(mapping);

    let remapped: Vec<Vec<JvmFrame>> = frames
        .iter()
        .map(|(class, method, line)| {
            let frame = proguard::StackFrame::new(class, method, *line as usize);
            mapper
                .remap_frame(&frame)
                .map(|f| JvmFrame {
                    class: f.class().to_owned(),
                    method: f.method().to_owned(),
                    file: f.file().map(str::to_owned),
                    line: f.line().map(|l| l as u64).filter(|l| *l > 0),
                })
                .collect()
        })
        .collect();

    let classes: Vec<Option<String>> = classes
        .iter()
        .map(|c| mapper.remap_class(c).map(str::to_owned))
        .collect();

    (atoms::ok(), (remapped, classes)).encode(env)
}

// ---------------------------------------------------------------------------
// Minidumps
// ---------------------------------------------------------------------------

#[derive(NifMap)]
struct DumpFrame {
    instruction_addr: u64,
    trust: String,
}

#[derive(NifMap)]
struct DumpThread {
    id: u32,
    name: Option<String>,
    crashed: bool,
    frames: Vec<DumpFrame>,
}

#[derive(NifMap)]
struct DumpModule {
    code_file: String,
    code_id: Option<String>,
    debug_file: Option<String>,
    debug_id: Option<String>,
    image_addr: u64,
    image_size: u64,
}

#[derive(NifMap)]
struct DumpState {
    crashed: bool,
    crash_reason: Option<String>,
    crash_address: Option<u64>,
    assertion: Option<String>,
    requesting_thread: Option<u32>,
    os_name: String,
    os_version: Option<String>,
    os_build: Option<String>,
    cpu_arch: String,
    cpu_family: Option<String>,
    cpu_count: u64,
    timestamp: u64,
    threads: Vec<DumpThread>,
    modules: Vec<DumpModule>,
}

#[rustler::nif(schedule = "DirtyCpu")]
fn minidump_process<'a>(
    env: Env<'a>,
    data: Binary<'a>,
    max_threads: usize,
    max_frames: usize,
) -> Term<'a> {
    match process(data.as_slice(), max_threads, max_frames) {
        Ok(state) => (atoms::ok(), state).encode(env),
        Err(reason) => (atoms::error(), reason).encode(env),
    }
}

fn process(data: &[u8], max_threads: usize, max_frames: usize) -> Result<DumpState, Atom> {
    use minidump::Module;

    let dump = minidump::Minidump::read(data).map_err(|_| atoms::invalid())?;

    // No symbol files: unwinding goes by the stack memory in the dump
    // (frame pointers, then scanning). Vigil symbolicates the frames
    // afterwards against the project's debug files.
    let provider =
        minidump_unwind::Symbolizer::new(minidump_unwind::simple_symbol_supplier(Vec::new()));
    let state = block_on(minidump_processor::process_minidump(&dump, &provider))
        .map_err(|_| atoms::invalid())?;

    let requesting = state.requesting_thread;
    let threads = state
        .threads
        .iter()
        .enumerate()
        .take(max_threads)
        .map(|(i, stack)| DumpThread {
            id: stack.thread_id,
            name: stack.thread_name.clone(),
            crashed: requesting == Some(i),
            frames: stack
                .frames
                .iter()
                .take(max_frames)
                .map(|f| DumpFrame {
                    instruction_addr: f.instruction,
                    trust: f.trust.as_str().to_owned(),
                })
                .collect(),
        })
        .collect();

    let modules = state
        .modules
        .iter()
        .map(|m| DumpModule {
            code_file: m.code_file().into_owned(),
            code_id: m.code_identifier().map(|id| id.to_string().to_lowercase()),
            debug_file: m.debug_file().map(|f| f.into_owned()),
            debug_id: m.debug_identifier().map(|id| id.to_string()),
            image_addr: m.base_address(),
            image_size: m.size(),
        })
        .collect();

    let info = &state.system_info;
    let timestamp = state
        .time
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    Ok(DumpState {
        crashed: state.crashed(),
        crash_reason: state.exception_info.as_ref().map(|e| e.reason.to_string()),
        crash_address: state.exception_info.as_ref().map(|e| e.address.0),
        assertion: state.assertion.clone(),
        requesting_thread: requesting
            .and_then(|i| state.threads.get(i))
            .map(|t| t.thread_id),
        os_name: info.os.long_name().into_owned(),
        os_version: info.os_version.clone(),
        os_build: info.os_build.clone(),
        cpu_arch: info.cpu.to_string(),
        cpu_family: info.cpu_info.clone(),
        cpu_count: info.cpu_count as u64,
        timestamp,
        threads,
        modules,
    })
}

/// minidump-processor is async (for symbol servers); with no symbol files
/// to fetch nothing ever waits, so a parked-thread executor is enough.
fn block_on<F: Future>(future: F) -> F::Output {
    struct Unpark(Thread);
    impl Wake for Unpark {
        fn wake(self: Arc<Self>) {
            self.0.unpark();
        }
    }

    let waker = Waker::from(Arc::new(Unpark(thread::current())));
    let mut cx = Context::from_waker(&waker);
    let mut future = pin!(future);
    loop {
        match future.as_mut().poll(&mut cx) {
            Poll::Ready(output) => return output,
            Poll::Pending => thread::park(),
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

#[rustler::nif(schedule = "DirtyCpu")]
fn read_zip<'a>(
    env: Env<'a>,
    data: Binary<'a>,
    max_total: u64,
    max_files: usize,
) -> NifResult<Term<'a>> {
    match unzip(data.as_slice(), max_total, max_files) {
        Ok(files) => {
            let files = files
                .into_iter()
                .map(|(name, bytes)| Ok((name, to_binary(env, &bytes)?)))
                .collect::<NifResult<Vec<_>>>()?;
            Ok((atoms::ok(), files).encode(env))
        }
        Err(reason) => Ok((atoms::error(), reason).encode(env)),
    }
}

type Files = Vec<(String, Vec<u8>)>;

fn unzip(data: &[u8], max_total: u64, max_files: usize) -> Result<Files, Atom> {
    let mut archive = zip::ZipArchive::new(Cursor::new(data)).map_err(|_| atoms::invalid_zip())?;
    let mut remaining = max_total;
    let mut files = Vec::new();

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i).map_err(|_| atoms::invalid_zip())?;
        if entry.is_dir() {
            continue;
        }
        if files.len() >= max_files {
            return Err(atoms::too_many_files());
        }
        let name = entry.name().map_err(|_| atoms::invalid_zip())?.into_owned();
        let mut bytes = Vec::new();
        (&mut entry)
            .take(remaining.saturating_add(1))
            .read_to_end(&mut bytes)
            .map_err(|_| atoms::invalid_zip())?;
        let len = bytes.len() as u64;
        if len > remaining {
            return Err(atoms::too_large());
        }
        remaining -= len;
        files.push((name, bytes));
    }
    Ok(files)
}

#[rustler::nif]
fn normalize_debug_ids(ids: Vec<String>) -> Vec<Option<String>> {
    ids.iter()
        .map(|id| {
            let id = id.trim();
            id.parse::<DebugId>()
                .or_else(|_| DebugId::from_breakpad(id))
                .ok()
                .filter(|id| !id.is_nil())
                .map(|id| id.to_string())
        })
        .collect()
}

fn to_binary<'a>(env: Env<'a>, bytes: &[u8]) -> NifResult<Binary<'a>> {
    let mut binary =
        OwnedBinary::new(bytes.len()).ok_or(rustler::Error::Term(Box::new("allocation failed")))?;
    binary.as_mut_slice().copy_from_slice(bytes);
    Ok(binary.release(env))
}

rustler::init!("Elixir.Vigil.Symbolic.Native");