:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cli): symbol-sets upload command for native ELF symbols (#62592)
Catalin Irimiedfd1f66a9f0a
diff --git a/cli/.sampo/changesets/symbol-sets-upload.md b/cli/.sampo/changesets/symbol-sets-upload.mdnew file mode 100644index 000000000000..5c5f2f805d5b--- /dev/null+++ b/cli/.sampo/changesets/symbol-sets-upload.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Add `symbol-sets upload` for native (ELF) debug symbols: it scans a directory for executables, shared libraries, and `objcopy --only-keep-debug` companions that carry a GNU build id and uploads them to PostHog.diff --git a/cli/Cargo.lock b/cli/Cargo.lockindex cbdc5fe32c55..5998e7f298fc 100644--- a/cli/Cargo.lock+++ b/cli/Cargo.lock@@ -1909,9 +1909,9 @@ dependencies = [[[package]]name = "posthog-symbol-data"-version = "0.4.0"+version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "82e77fd31d8af3c64e6a66e516892dd68321f8df3e77fe519594182409ff92a0"+checksum = "1f3622f11c9f166900b4e7c9c872c1ce63db60fd550c5b055dedde791af9a1b4"dependencies = ["serde","thiserror 2.0.17",diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex 2bff81210015..c7c05ae6ee59 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -26,7 +26,7 @@ clap = { version = "4.5.31", features = ["derive", "env"] }dirs = "6.0.0"inquire = "0.7.5"chrono = "0.4.42"-posthog-symbol-data = "0.4.0"+posthog-symbol-data = "0.5.0"walkdir = "2.5.0"globset = "0.4"ratatui = "0.29.0"diff --git a/cli/src/commands.rs b/cli/src/commands.rsindex d406e482d374..aa6178c1cc72 100644--- a/cli/src/commands.rs+++ b/cli/src/commands.rs@@ -67,6 +67,9 @@ fn dry_run_skipped_command(command: &Commands) -> Option<&'static str> {match command {Commands::Sourcemap { .. } => Some("sourcemap"),Commands::Dsym { .. } => Some("dSYM"),+ Commands::SymbolSets {+ cmd: SymbolSetsSubcommand::Upload(_),+ } => Some("native debug symbols"),Commands::Hermes { .. } => Some("hermes sourcemap"),Commands::Proguard { .. } => Some("proguard"),Commands::Exp { cmd } => match cmd {@@ -142,7 +145,7 @@ pub enum Commands {cmd: ProguardSubcommand,},- #[command(about = "Manage uploaded symbol sets")]+ #[command(about = "Upload, download, and manage symbol sets")]SymbolSets {#[command(subcommand)]cmd: SymbolSetsSubcommand,@@ -337,6 +340,9 @@ impl Cli {}},Commands::SymbolSets { cmd } => match cmd {+ SymbolSetsSubcommand::Upload(args) => {+ crate::debug_symbols::upload::upload(&args)?;+ }SymbolSetsSubcommand::Download(args) => {crate::download::download(&args)?;}diff --git a/cli/src/debug_symbols/mod.rs b/cli/src/debug_symbols/mod.rsnew file mode 100644index 000000000000..2b006927da5c--- /dev/null+++ b/cli/src/debug_symbols/mod.rs@@ -0,0 +1,362 @@+use std::path::{Path, PathBuf};++use anyhow::{anyhow, Result};+use posthog_symbol_data::{write_symbol_data, ElfDebugInfo};+use symbolic::debuginfo::{Archive, FileFormat, ObjectKind};+use tracing::{info, warn};++use crate::api::symbol_sets::SymbolSetUpload;+use crate::dsym::source_bundle;++pub mod upload;++const ELF_MAGIC: &[u8; 4] = b"\x7fELF";++/// A native debug-info file discovered on disk, parsed and validated,+/// ready to be packaged for upload.+pub struct DebugSymbolFile {+ /// The debug id derived from the GNU build id (used as chunk_id)+ pub debug_id: String,+ pub path: PathBuf,+ /// Raw file contents+ data: Vec<u8>,+ /// Size of the file, used to pick the richer candidate on debug_id collisions+ size: usize,+}++/// The outcome of scanning a directory for native debug symbols.+#[derive(Default)]+pub struct DiscoveryReport {+ /// Validated files, deduplicated by debug id+ pub files: Vec<DebugSymbolFile>,+ /// ELF executables/libraries that carry no debug info (skipped)+ pub without_debug_info: Vec<PathBuf>,+ /// ELFs with debug info but no GNU build id (cannot be uploaded)+ pub missing_build_id: Vec<PathBuf>,+ /// dSYM bundles spotted while scanning (handled by `dsym upload`)+ pub dsym_bundles: Vec<PathBuf>,+ /// Split-DWARF artifacts spotted while scanning (unsupported)+ pub split_dwarf: Vec<PathBuf>,+}++impl DebugSymbolFile {+ /// Package the file for upload: a ZIP with the binary stored as `dwarf` at+ /// the root (plus an optional `__source/` bundle), wrapped in the+ /// `ElfDebugInfo` symbol_data container.+ pub fn into_upload(+ self,+ release_id: Option<String>,+ include_source: bool,+ ) -> Result<SymbolSetUpload> {+ use std::io::{Cursor, Write};++ let mut buffer = Cursor::new(Vec::new());+ {+ let mut zip = zip::ZipWriter::new(&mut buffer);+ let options = zip::write::SimpleFileOptions::default()+ .compression_method(zip::CompressionMethod::Deflated);++ zip.start_file("dwarf", options)?;+ zip.write_all(&self.data)?;++ if include_source {+ match source_bundle::extract_source_paths_from_dwarf_bytes(&self.data) {+ Ok(all_paths) => {+ let filtered = filter_native_source_paths(&all_paths);+ info!(+ "Found {} source paths in DWARF ({} after filtering)",+ all_paths.len(),+ filtered.len()+ );+ if !filtered.is_empty() {+ match source_bundle::collect_source_files(&filtered) {+ Ok(source_files) => {+ source_bundle::add_source_to_zip(&mut zip, &source_files)?;+ }+ Err(e) => {+ warn!("Failed to collect source files: {} (continuing without source)", e);+ }+ }+ }+ }+ Err(e) => {+ warn!(+ "Failed to extract DWARF source paths: {} (continuing without source)",+ e+ );+ }+ }+ }++ zip.finish()?;+ }++ let wrapped = write_symbol_data(ElfDebugInfo {+ data: buffer.into_inner(),+ })?;++ Ok(SymbolSetUpload {+ chunk_id: self.debug_id,+ release_id,+ data: wrapped,+ })+ }+}++/// Filter DWARF source paths for native (Rust/C/C++) builds: on top of the+/// shared system-path filters, drop registry/toolchain sources that aren't+/// part of the user's project tree.+fn filter_native_source_paths(paths: &[String]) -> Vec<&str> {+ source_bundle::filter_source_paths(paths)+ .into_iter()+ .filter(|path| {+ const EXCLUDED: &[&str] = &[+ "/.cargo/registry/",+ "/.cargo/git/",+ "/rustc/",+ "/.rustup/toolchains/",+ "/vendor/",+ ];+ if EXCLUDED.iter().any(|sub| path.contains(sub)) {+ tracing::debug!("Filtered out (native toolchain): {}", path);+ return false;+ }+ true+ })+ .collect()+}++/// Walk `directory` and classify everything that looks like native debug+/// symbols. Only ELF executables, shared libraries, and debug companions+/// (e.g. from `objcopy --only-keep-debug`) are considered; relocatable+/// objects and other ELF kinds are ignored.+pub fn discover(directory: &Path) -> Result<DiscoveryReport> {+ use walkdir::WalkDir;++ let mut report = DiscoveryReport::default();+ let mut seen: std::collections::HashMap<String, usize> = std::collections::HashMap::new();++ for entry in WalkDir::new(directory).follow_links(true) {+ // A symlink loop, dangling link, or unreadable directory surfaces here+ // as an iterator error. Skip just that entry rather than aborting the+ // whole scan, which would discard every valid file already found.+ let entry = match entry {+ Ok(entry) => entry,+ Err(e) => {+ warn!("Skipping unreadable path while scanning: {e}");+ continue;+ }+ };+ let path = entry.path();++ if path.is_dir() {+ if path.extension().is_some_and(|e| e == "dSYM") {+ report.dsym_bundles.push(path.to_path_buf());+ }+ continue;+ }++ if path.extension().is_some_and(|e| e == "dwp" || e == "dwo") {+ report.split_dwarf.push(path.to_path_buf());+ continue;+ }++ if !entry.file_type().is_file() {+ continue;+ }++ let Some(file) = parse_candidate(path)? else {+ continue;+ };++ match file {+ Candidate::NoDebugInfo => report.without_debug_info.push(path.to_path_buf()),+ Candidate::NoBuildId => report.missing_build_id.push(path.to_path_buf()),+ Candidate::Valid(file) => {+ // Dedup by debug id (e.g. a binary and its objcopy companion):+ // keep the larger file, which carries at least as much debug data.+ if let Some(&existing) = seen.get(&file.debug_id) {+ let existing_file = &report.files[existing];+ warn!(+ "Duplicate debug id {} for {} and {}; keeping the larger file",+ file.debug_id,+ existing_file.path.display(),+ file.path.display()+ );+ if file.size > existing_file.size {+ report.files[existing] = file;+ }+ } else {+ seen.insert(file.debug_id.clone(), report.files.len());+ report.files.push(file);+ }+ }+ }+ }++ Ok(report)+}++enum Candidate {+ Valid(DebugSymbolFile),+ NoDebugInfo,+ NoBuildId,+}++fn has_elf_magic(path: &Path) -> bool {+ use std::io::Read;++ let Ok(mut file) = std::fs::File::open(path) else {+ warn!("Could not open {} (skipping)", path.display());+ return false;+ };+ let mut magic = [0u8; ELF_MAGIC.len()];+ file.read_exact(&mut magic).is_ok() && &magic == ELF_MAGIC+}++/// Parse a file as a native debug-symbol candidate. Returns `None` for+/// anything that isn't an ELF executable/library/debug companion.+fn parse_candidate(path: &Path) -> Result<Option<Candidate>> {+ // Check the magic before loading the file: build trees contain large+ // non-ELF artifacts that shouldn't be read into memory just to be skipped.+ if !has_elf_magic(path) {+ return Ok(None);+ }++ let Ok(data) = std::fs::read(path) else {+ warn!("Could not read {} (skipping)", path.display());+ return Ok(None);+ };++ // Scope the parsed archive so `data` can move into the result afterwards.+ let debug_id = {+ let archive = match Archive::parse(&data) {+ Ok(archive) => archive,+ Err(e) => {+ warn!("Could not parse {} as ELF: {e} (skipping)", path.display());+ return Ok(None);+ }+ };++ let Some(Ok(object)) = archive.objects().next() else {+ warn!("No objects in {} (skipping)", path.display());+ return Ok(None);+ };++ if object.file_format() != FileFormat::Elf {+ return Ok(None);+ }++ // Relocatable objects (.o) and other kinds aren't loadable images.+ if !matches!(+ object.kind(),+ ObjectKind::Executable | ObjectKind::Library | ObjectKind::Debug+ ) {+ return Ok(None);+ }++ if !object.has_debug_info() {+ return Ok(Some(Candidate::NoDebugInfo));+ }++ // Without a GNU build id (code id), symbolic synthesizes a+ // content-derived debug id that the SDK cannot reproduce at runtime,+ // so the upload would never match any crash event.+ if object.code_id().is_none() {+ return Ok(Some(Candidate::NoBuildId));+ }++ let debug_id = object.debug_id();+ if debug_id.is_nil() {+ return Ok(Some(Candidate::NoBuildId));+ }+ debug_id.to_string()+ };++ let size = data.len();+ Ok(Some(Candidate::Valid(DebugSymbolFile {+ debug_id,+ path: path.to_path_buf(),+ data,+ size,+ })))+}++/// Render guidance for files that couldn't be uploaded; returns an error when+/// nothing usable was found at all.+pub fn report_problems(report: &DiscoveryReport, directory: &Path) -> Result<()> {+ if !report.split_dwarf.is_empty() {+ warn!(+ "Found {} split-DWARF file(s) (.dwp/.dwo), which aren't supported yet. \+ Build with debug info embedded in the binary (the default on Linux), \+ or upload an `objcopy --only-keep-debug` companion instead.",+ report.split_dwarf.len()+ );+ }++ for path in &report.without_debug_info {+ warn!(+ "{} has no debug info (skipping). For release builds, set \+ `debug = \"line-tables-only\"` (or `true`) in [profile.release], \+ and upload before stripping.",+ path.display()+ );+ }++ if !report.missing_build_id.is_empty() {+ let listing = report+ .missing_build_id+ .iter()+ .map(|p| format!(" {}", p.display()))+ .collect::<Vec<_>>()+ .join("\n");+ let guidance = format!(+ "The following files have debug info but no GNU build id, so they cannot be \+ matched to crash events:\n{listing}\n\+ Link with `-Wl,--build-id=sha1` (in Rust: `-C link-arg=-Wl,--build-id=sha1` \+ via RUSTFLAGS); most toolchains add this by default."+ );+ // Only fail the run when there's nothing valid to upload; otherwise a+ // stray build-id-less helper binary would block every valid symbol.+ if report.files.is_empty() {+ anyhow::bail!("{guidance}");+ }+ warn!("{guidance}");+ }++ if report.files.is_empty() {+ if !report.dsym_bundles.is_empty() {+ anyhow::bail!(+ "No ELF debug symbols found in {}, but {} dSYM bundle(s) were. \+ Use `posthog-cli dsym upload` for Apple dSYMs.",+ directory.display(),+ report.dsym_bundles.len()+ );+ }+ anyhow::bail!(+ "No ELF files with debug info found in {}",+ directory.display()+ );+ }++ if !report.dsym_bundles.is_empty() {+ warn!(+ "Skipping {} dSYM bundle(s); use `posthog-cli dsym upload` for those.",+ report.dsym_bundles.len()+ );+ }++ Ok(())+}++/// Extract the debug id of an ELF file, e.g. for testing parity with the SDK.+pub fn elf_debug_id(path: &Path) -> Result<String> {+ let data = std::fs::read(path)?;+ let archive = Archive::parse(&data).map_err(|e| anyhow!("parse {}: {e}", path.display()))?;+ let object = archive+ .objects()+ .next()+ .ok_or_else(|| anyhow!("no objects in {}", path.display()))?+ .map_err(|e| anyhow!("parse object in {}: {e}", path.display()))?;+ Ok(object.debug_id().to_string())+}diff --git a/cli/src/debug_symbols/upload.rs b/cli/src/debug_symbols/upload.rsnew file mode 100644index 000000000000..5c481e988a39--- /dev/null+++ b/cli/src/debug_symbols/upload.rs@@ -0,0 +1,103 @@+use std::path::PathBuf;++use anyhow::{anyhow, Result};+use tracing::info;++use crate::{+ api::{self, releases::ReleaseBuilder, symbol_sets::SymbolSetUpload},+ debug_symbols::{discover, report_problems},+ sourcemaps::args::{pack_version, ReleaseArgs, UploadConflictArgs},+ utils::git::get_git_info,+};++#[derive(clap::Args, Clone)]+pub struct Args {+ /// The directory to scan for native debug symbol files (e.g. target/release).+ /// ELF executables, shared libraries, and `objcopy --only-keep-debug`+ /// companions with debug info are uploaded; everything else is skipped.+ #[arg(short, long)]+ pub directory: PathBuf,++ #[clap(flatten)]+ pub release: ReleaseArgs,++ #[clap(flatten)]+ pub conflict: UploadConflictArgs,++ /// Include source code files in the upload.+ /// When enabled, project source files referenced by DWARF debug info are+ /// bundled in, allowing PostHog to display source context around frames.+ /// Implies --force unless --skip-on-conflict is set.+ #[arg(long, default_value_t = false)]+ pub include_source: bool,+}++pub fn upload(args: &Args) -> Result<()> {+ let Args {+ directory,+ release,+ conflict,+ include_source,+ } = args;+ let release_args = release;++ let directory = directory.canonicalize().map_err(|e| {+ anyhow!(+ "Path {} canonicalization failed: {}",+ directory.display(),+ e+ )+ })?;++ if !directory.is_dir() {+ anyhow::bail!("Path {} is not a directory", directory.display());+ }++ let report = discover(&directory)?;+ report_problems(&report, &directory)?;++ info!("Found {} debug symbol file(s)", report.files.len());++ // Set up release info: explicit flags win, git info is metadata/fallback+ let mut release_builder = ReleaseBuilder::default();+ if let Ok(Some(git_info)) = get_git_info(Some(directory.clone())) {+ release_builder.with_git(git_info);+ }+ if let Some(ref release_name) = release_args.name {+ release_builder.with_name(release_name);+ }+ if let Some(version) = pack_version(&release_args.version, &release_args.build) {+ release_builder.with_version(&version);+ }++ let created_release = release_builder+ .can_create()+ .then(|| release_builder.fetch_or_create())+ .transpose()?;+ let release_id = created_release.map(|r| r.id.to_string());++ let mut uploads: Vec<SymbolSetUpload> = Vec::new();+ for file in report.files {+ info!(+ "Processing {} (debug id {})",+ file.path.display(),+ file.debug_id+ );+ uploads.push(file.into_upload(release_id.clone(), *include_source)?);+ }++ info!("Uploading {} debug symbol file(s)...", uploads.len());+ // --include-source implies force unless the user explicitly asked to keep+ // existing symbol sets with --skip-on-conflict.+ let effective_force = conflict.force || (*include_source && !conflict.skip_on_conflict);+ api::symbol_sets::upload_with_retry(+ uploads,+ 10,+ release_args.skip_release_on_fail,+ effective_force,+ conflict.skip_on_conflict,+ )?;+ info!("Debug symbol upload complete");++ Ok(())+}diff --git a/cli/src/download.rs b/cli/src/download.rsindex ca7ec271c7b1..b3c8990ac269 100644--- a/cli/src/download.rs+++ b/cli/src/download.rs@@ -7,7 +7,8 @@ use std::{use anyhow::{Context, Result};use clap::Subcommand;use posthog_symbol_data::{- read_symbol_data, AppleDsym, HermesMap, ProguardMapping, SourceAndMap, SymbolDataError,+ read_symbol_data, AppleDsym, ElfDebugInfo, HermesMap, ProguardMapping, SourceAndMap,+ SymbolDataError,};use tracing::info;@@ -15,6 +16,10 @@ use crate::{api::symbol_sets, invocation_context::context};#[derive(Subcommand)]pub enum SymbolSetsSubcommand {+ /// Upload native (ELF) debug symbols from a directory. ELF executables,+ /// shared libraries, and `objcopy --only-keep-debug` companions with debug+ /// info are uploaded; other files (dSYM bundles, etc.) are reported and skipped.+ Upload(crate::debug_symbols::upload::Args),/// Download and extract a symbol set (sourcemap, hermes, proguard, or dSYM)Download(DownloadArgs),/// Extract a local symbol set binary file (decompress and split)@@ -84,11 +89,9 @@ pub fn extract(args: &ExtractArgs) -> Result<()> {fn extract_symbol_data(data: &[u8], base_name: &str, output: &Path) -> Result<()> {fs::create_dir_all(output).context("Failed to create output directory")?;- let owned = data.to_vec();-// Try each type — read_symbol_data returns InvalidDataType when the// header type field doesn't match, so we use that to fall through.- if let Ok(parsed) = read_symbol_data::<SourceAndMap>(owned.clone()) {+ if let Ok(parsed) = read_symbol_data::<SourceAndMap>(data) {let source_path = output.join(format!("{base_name}.js"));fs::write(&source_path, &parsed.minified_source).context("Failed to write source file")?;info!("Wrote {}", source_path.display());@@ -101,7 +104,7 @@ fn extract_symbol_data(data: &[u8], base_name: &str, output: &Path) -> Result<()return Ok(());}- if let Ok(parsed) = read_symbol_data::<HermesMap>(owned.clone()) {+ if let Ok(parsed) = read_symbol_data::<HermesMap>(data) {let map_path = output.join(format!("{base_name}.hbc.map"));fs::write(&map_path, &parsed.sourcemap).context("Failed to write hermes sourcemap")?;info!("Wrote {}", map_path.display());@@ -110,7 +113,7 @@ fn extract_symbol_data(data: &[u8], base_name: &str, output: &Path) -> Result<()return Ok(());}- if let Ok(parsed) = read_symbol_data::<ProguardMapping>(owned.clone()) {+ if let Ok(parsed) = read_symbol_data::<ProguardMapping>(data) {let map_path = output.join(format!("{base_name}.txt"));fs::write(&map_path, &parsed.content).context("Failed to write proguard mapping")?;info!("Wrote {}", map_path.display());@@ -119,7 +122,14 @@ fn extract_symbol_data(data: &[u8], base_name: &str, output: &Path) -> Result<()return Ok(());}- match read_symbol_data::<AppleDsym>(owned) {+ if let Ok(parsed) = read_symbol_data::<ElfDebugInfo>(data) {+ // Same ZIP layout as dSYM uploads: the binary as `dwarf` at the root+ // plus an optional `__source/` bundle.+ extract_dsym_zip(&parsed.data, base_name, output)?;+ return Ok(());+ }++ match read_symbol_data::<AppleDsym>(data) {Ok(parsed) => {extract_dsym_zip(&parsed.data, base_name, output)?;Ok(())diff --git a/cli/src/dsym/source_bundle.rs b/cli/src/dsym/source_bundle.rsindex c04b8afd5f91..a936466b90c6 100644--- a/cli/src/dsym/source_bundle.rs+++ b/cli/src/dsym/source_bundle.rs@@ -57,7 +57,13 @@ pub struct SourceFiles {/// first-party dependency source files that live in a different directory tree.pub fn extract_source_paths_from_dwarf(dwarf_path: &Path) -> Result<Vec<String>> {let dwarf_data = fs::read(dwarf_path)?;- let archive = Archive::parse(&dwarf_data)?;+ extract_source_paths_from_dwarf_bytes(&dwarf_data)+}++/// Like [`extract_source_paths_from_dwarf`], but for callers that already+/// hold the binary in memory, avoiding a second read from disk.+pub fn extract_source_paths_from_dwarf_bytes(dwarf_data: &[u8]) -> Result<Vec<String>> {+ let archive = Archive::parse(dwarf_data)?;let mut paths: HashSet<String> = HashSet::new();diff --git a/cli/src/lib.rs b/cli/src/lib.rsindex d58c83c5bafd..85eb9eee8a2f 100644--- a/cli/src/lib.rs+++ b/cli/src/lib.rs@@ -1,6 +1,7 @@pub mod api;pub mod api_proxy;pub mod commands;+pub mod debug_symbols;pub mod download;pub mod dsym;pub mod error;diff --git a/cli/tests/debug_symbols.rs b/cli/tests/debug_symbols.rsnew file mode 100644index 000000000000..50f055d3ea39--- /dev/null+++ b/cli/tests/debug_symbols.rs@@ -0,0 +1,117 @@+use std::io::Read;+use std::path::{Path, PathBuf};++use posthog_cli::debug_symbols::{discover, elf_debug_id};+use posthog_symbol_data::{read_symbol_data, ElfDebugInfo};++/// The native ELF fixtures shared with cymbal's symbolication tests; built by+/// tests/static/native/build.sh, with debug ids derived the same way cymbal+/// derives them when resolving frames.+fn fixtures_dir() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../rust/cymbal/tests/static/native")+}++#[test]+fn extracts_debug_ids_matching_cymbal_fixtures() {+ let dir = fixtures_dir();++ assert_eq!(+ elf_debug_id(&dir.join("test_binary_nopie")).unwrap(),+ "7561847b-1054-7eb3-7763-4415adfaa134"+ );+ assert_eq!(+ elf_debug_id(&dir.join("test_binary_pie")).unwrap(),+ "850c70a2-6592-a70c-3e49-c0e443794d23"+ );+ assert_eq!(+ elf_debug_id(&dir.join("test_binary_inline")).unwrap(),+ "140ab543-c098-09dc-22b6-11f72e46d6fe"+ );+}++#[test]+fn discovers_and_packages_elf_files() {+ let report = discover(&fixtures_dir()).unwrap();++ // The three uncompressed ELF fixtures are found and valid+ let mut debug_ids: Vec<&str> = report.files.iter().map(|f| f.debug_id.as_str()).collect();+ debug_ids.sort();+ assert_eq!(+ debug_ids,+ vec![+ "140ab543-c098-09dc-22b6-11f72e46d6fe",+ "7561847b-1054-7eb3-7763-4415adfaa134",+ "850c70a2-6592-a70c-3e49-c0e443794d23",+ ]+ );+ // The classification fixtures in the same directory triage instead+ assert_eq!(report.without_debug_info.len(), 1);+ assert_eq!(report.missing_build_id.len(), 1);+ assert!(report.dsym_bundles.is_empty());++ // Packaged uploads round-trip through the symbol_data container with the+ // binary stored as `dwarf` at the ZIP root — the layout cymbal parses.+ let file = report+ .files+ .into_iter()+ .find(|f| f.debug_id == "850c70a2-6592-a70c-3e49-c0e443794d23")+ .unwrap();+ let upload = file.into_upload(None, false).unwrap();+ assert_eq!(upload.chunk_id, "850c70a2-6592-a70c-3e49-c0e443794d23");++ let unwrapped: ElfDebugInfo = read_symbol_data(&upload.data).unwrap();+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(unwrapped.data)).unwrap();+ let mut dwarf = zip.by_name("dwarf").unwrap();+ let mut magic = [0u8; 4];+ dwarf.read_exact(&mut magic).unwrap();+ assert_eq!(&magic, b"\x7fELF");+}++#[test]+fn skips_non_elf_and_flags_dsyms() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join("readme.txt"), "not an elf").unwrap();+ std::fs::create_dir_all(dir.path().join("MyApp.app.dSYM/Contents")).unwrap();+ std::fs::write(dir.path().join("split.dwp"), b"\x7fELFfake").unwrap();++ let report = discover(dir.path()).unwrap();+ assert!(report.files.is_empty());+ assert_eq!(report.dsym_bundles.len(), 1);+ assert_eq!(report.split_dwarf.len(), 1);+}++#[test]+fn classifies_elfs_without_debug_info_or_build_id() {+ let dir = tempfile::tempdir().unwrap();+ let fixtures = fixtures_dir();+ std::fs::copy(+ fixtures.join("test_binary_nodebug"),+ dir.path().join("test_binary_nodebug"),+ )+ .unwrap();+ std::fs::copy(+ fixtures.join("test_binary_nobuildid"),+ dir.path().join("test_binary_nobuildid"),+ )+ .unwrap();++ let report = discover(dir.path()).unwrap();+ assert!(report.files.is_empty());+ assert_eq!(report.without_debug_info.len(), 1);+ assert_eq!(report.missing_build_id.len(), 1);++ // With nothing uploadable, the missing build id is a hard error+ // carrying linker guidance.+ let err = posthog_cli::debug_symbols::report_problems(&report, dir.path()).unwrap_err();+ assert!(err.to_string().contains("build id"), "got: {err}");++ // A valid ELF alongside turns the hard error into a warning-only run.+ std::fs::copy(+ fixtures.join("test_binary_pie"),+ dir.path().join("test_binary_pie"),+ )+ .unwrap();+ let report = discover(dir.path()).unwrap();+ assert_eq!(report.files.len(), 1);+ assert!(posthog_cli::debug_symbols::report_problems(&report, dir.path()).is_ok());+}diff --git a/rust/cymbal/tests/static/native/build.sh b/rust/cymbal/tests/static/native/build.shindex 582f192ab22b..51caa0e433b9 100755--- a/rust/cymbal/tests/static/native/build.sh+++ b/rust/cymbal/tests/static/native/build.sh@@ -3,6 +3,7 @@## Requirements:# - zig (any recent version; used as a hermetic x86_64-linux cross C compiler/linker)+# - llvm-objcopy (e.g. from an llvm toolchain)# - rustup with the x86_64-unknown-linux-gnu target installed# (rustup target add x86_64-unknown-linux-gnu)#@@ -29,6 +30,15 @@ zig cc "${CFLAGS[@]}" -fPIE -pie -o test_binary_pie test_binary.c# Inline expansion fixture (PIE).zig cc "${CFLAGS[@]}" -fPIE -pie -o test_binary_inline test_binary_inline.c+# CLI classification fixtures: an ELF without debug info, and one with debug+# info but no GNU build id. Neither can be symbolicated; the CLI must triage+# them instead of uploading them. The strip is explicit because zig links its+# runtime objects with debug info even when -g is absent; any objcopy able to+# read ELF works (llvm-objcopy here since macOS binutils can't).+zig cc -target x86_64-linux-gnu -O1 -Wl,--build-id=sha1 -o test_binary_nodebug test_binary.c+llvm-objcopy --strip-debug test_binary_nodebug test_binary_nodebug+zig cc -target x86_64-linux-gnu -g -O1 "-fdebug-prefix-map=$PWD=/cymbal_tests/native" -Wl,--build-id=none -o test_binary_nobuildid test_binary.c+# Rust fixture: real rustc-mangled symbols for the demangling assertions.# zig is used as the cross linker via the zigcc-x86_64-linux wrapper.cat > .zigcc-x86_64-linux <<'WRAP'@@ -52,5 +62,5 @@ zstd -19 -f -q test_rust_binaryrm test_rust_binaryecho "Built fixtures:"-file test_binary_nopie test_binary_pie test_binary_inline+file test_binary_nopie test_binary_pie test_binary_inline test_binary_nodebug test_binary_nobuildidls -la test_rust_binary.zstdiff --git a/rust/cymbal/tests/static/native/test_binary_nobuildid b/rust/cymbal/tests/static/native/test_binary_nobuildidnew file mode 100755index 000000000000..0d6483d31e33Binary files /dev/null and b/rust/cymbal/tests/static/native/test_binary_nobuildid differdiff --git a/rust/cymbal/tests/static/native/test_binary_nodebug b/rust/cymbal/tests/static/native/test_binary_nodebugnew file mode 100755index 000000000000..c2dd7a87564eBinary files /dev/null and b/rust/cymbal/tests/static/native/test_binary_nodebug differ