: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): upload Mach-O executables as native debug symbols (#72776)
Catalin Irimie845de8f80c30
diff --git a/cli/.sampo/changesets/macho-symbol-upload.md b/cli/.sampo/changesets/macho-symbol-upload.mdnew file mode 100644index 000000000000..df72e1e11eab--- /dev/null+++ b/cli/.sampo/changesets/macho-symbol-upload.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: minor+---++`symbol-sets upload` now accepts standalone Mach-O executables and dylibs, not just ELF files and `.dSYM` bundles. Binaries that embed their own DWARF — Go binaries on macOS, which never produce a dSYM (`dsymutil` reports "no debug symbols in executable") — upload directly, with the `LC_UUID` as the symbol set id. Universal (fat) binaries upload one symbol set per architecture slice. Go's default darwin build compresses the embedded DWARF, which the server cannot read yet; such binaries are skipped with guidance to rebuild with `-ldflags=-compressdwarf=false`.diff --git a/cli/README.md b/cli/README.mdindex b0b75bfd4a05..fe0ba25d9633 100644--- a/cli/README.md+++ b/cli/README.md@@ -67,6 +67,7 @@ A single command handles both desktop/server formats:- **Linux (ELF):** executables, shared libraries, and `objcopy --only-keep-debug` companions that carry a GNU build id. This branch is cross-platform.- **macOS (Apple `.dSYM`):** dSYM bundles are packaged through the same path as `posthog-cli dsym upload`. That path shells out to `dwarfdump` (bundled with Xcode), so it only runs on macOS — if `dwarfdump` is missing, the bundle is reported and skipped while any ELF symbols in the same directory still upload.+- **macOS (Mach-O executables):** binaries that embed their own DWARF upload directly, keyed by their `LC_UUID`; universal (fat) binaries upload one symbol set per architecture slice. This branch is cross-platform. It exists mainly for Go, which never produces a dSYM (`dsymutil` reports "no debug symbols in executable") — but note Go compresses the embedded DWARF by default, which symbolication can't read yet, so build with `-ldflags=-compressdwarf=false`. C/Swift/Rust executables normally carry no embedded DWARF; upload their dSYMs instead.Pass `--include-source` to bundle the referenced source files for richer context around frames.diff --git a/cli/src/api/symbol_sets.rs b/cli/src/api/symbol_sets.rsindex 7b71d1239188..a80652d7be16 100644--- a/cli/src/api/symbol_sets.rs+++ b/cli/src/api/symbol_sets.rs@@ -16,7 +16,7 @@ use crate::{utils::{files::content_hash, raise_for_err},};-const MAX_FILE_SIZE: usize = 100 * 1024 * 1024; // 100 MB+pub(crate) const MAX_FILE_SIZE: usize = 100 * 1024 * 1024; // 100 MBconst FINISH_UPLOAD_ERROR_MESSAGE: &str ="Failed to finalize symbol upload; maps were not attached";pub const DEFAULT_UPLOAD_CONCURRENCY: NonZeroUsize = NonZeroUsize::new(10).unwrap();diff --git a/cli/src/debug_symbols/mod.rs b/cli/src/debug_symbols/mod.rsindex d482252a963b..d6832dd02198 100644--- a/cli/src/debug_symbols/mod.rs+++ b/cli/src/debug_symbols/mod.rs@@ -1,7 +1,7 @@use std::path::{Path, PathBuf};use anyhow::{anyhow, Result};-use posthog_symbol_data::{write_symbol_data, ElfDebugInfo};+use posthog_symbol_data::{write_symbol_data, AppleDsym, ElfDebugInfo};use symbolic::debuginfo::{Archive, FileFormat, ObjectKind};use tracing::{info, warn};@@ -11,17 +11,30 @@ use crate::dsym::{source_bundle, DsymFile};pub mod upload;const ELF_MAGIC: &[u8; 4] = b"\x7fELF";+// Thin little-endian 64/32-bit Mach-O and the big-endian fat header — the+// on-disk layouts produced by Apple toolchains and Go, and the ones the+// symbolic archive parser understands (fat64, `0xcafebabf`, is not supported+// and stays skipped).+const MACHO_MAGICS: [[u8; 4]; 3] = [+ [0xcf, 0xfa, 0xed, 0xfe],+ [0xce, 0xfa, 0xed, 0xfe],+ [0xca, 0xfe, 0xba, 0xbe],+];/// 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)+ /// The debug id used as chunk_id: derived from the GNU build id for ELF+ /// (lowercase), or the `LC_UUID` for Mach-O (uppercase, matching the SDK+ /// and `dsym upload`)pub debug_id: String,pub path: PathBuf,- /// Raw file contents+ /// Raw contents: the whole file for ELF, one architecture slice for Mach-O+ /// (a fat binary yields one `DebugSymbolFile` per slice)data: Vec<u8>,- /// Size of the file, used to pick the richer candidate on debug_id collisions+ /// Size of the data, used to pick the richer candidate on debug_id collisionssize: usize,+ format: FileFormat,}/// The outcome of scanning a directory for native debug symbols.@@ -29,10 +42,15 @@ pub struct DebugSymbolFile {pub struct DiscoveryReport {/// Validated files, deduplicated by debug idpub files: Vec<DebugSymbolFile>,- /// ELF executables/libraries that carry no debug info (skipped)+ /// ELF/Mach-O 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>,+ /// Mach-O binaries with debug info but no `LC_UUID` (cannot be uploaded)+ pub missing_uuid: Vec<PathBuf>,+ /// Mach-O binaries whose DWARF is compressed (`__zdebug_*` sections, Go's+ /// default on macOS), which the symbolication server can't read yet+ pub compressed_dwarf: Vec<PathBuf>,/// Apple dSYM bundles spotted while scanning (packaged via the dsym path)pub dsym_bundles: Vec<PathBuf>,/// Split-DWARF artifacts spotted while scanning (unsupported)@@ -42,7 +60,8 @@ pub struct DiscoveryReport {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.+ /// symbol_data container matching its format (`ElfDebugInfo` for ELF,+ /// `AppleDsym` for Mach-O — the layout the server expects per chunk kind).pub fn into_upload(self,release_id: Option<String>,@@ -91,9 +110,12 @@ impl DebugSymbolFile {zip.finish()?;}- let wrapped = write_symbol_data(ElfDebugInfo {- data: buffer.into_inner(),- })?;+ let zip_data = buffer.into_inner();+ let wrapped = if self.format == FileFormat::MachO {+ write_symbol_data(AppleDsym { data: zip_data })?+ } else {+ write_symbol_data(ElfDebugInfo { data: zip_data })?+ };Ok(SymbolSetUpload {chunk_id: self.debug_id,@@ -128,9 +150,9 @@ fn filter_native_source_paths(paths: &[String]) -> Vec<&str> {}/// 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.+/// symbols. Only ELF and Mach-O executables, shared libraries, and debug+/// companions (e.g. from `objcopy --only-keep-debug`) are considered;+/// relocatable objects and other kinds are ignored.pub fn discover(directory: &Path) -> Result<DiscoveryReport> {use walkdir::WalkDir;@@ -166,30 +188,40 @@ pub fn discover(directory: &Path) -> Result<DiscoveryReport> {continue;}- let Some(file) = parse_candidate(path)? else {+ // Files inside a .dSYM bundle (its inner DWARF Mach-O) belong to the+ // bundle, which is packaged wholesale via the dsym path.+ if path+ .ancestors()+ .skip(1)+ .any(|p| p.extension().is_some_and(|e| e == "dSYM"))+ {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;+ for file in parse_candidates(path)? {+ 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::MissingUuid => report.missing_uuid.push(path.to_path_buf()),+ Candidate::CompressedDwarf => report.compressed_dwarf.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);}- } else {- seen.insert(file.debug_id.clone(), report.files.len());- report.files.push(file);}}}@@ -202,50 +234,58 @@ enum Candidate {Valid(DebugSymbolFile),NoDebugInfo,NoBuildId,+ MissingUuid,+ CompressedDwarf,}-fn has_elf_magic(path: &Path) -> bool {+fn has_native_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+ let mut magic = [0u8; 4];+ if file.read_exact(&mut magic).is_err() {+ return false;+ }+ &magic == ELF_MAGIC || MACHO_MAGICS.contains(&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>> {+/// Parse a file into native debug-symbol candidates. Returns an empty vec for+/// anything that isn't an ELF or Mach-O executable/library/debug companion.+/// A universal (fat) Mach-O yields one candidate per architecture slice, each+/// carrying just that slice's bytes and its own `LC_UUID`.+fn parse_candidates(path: &Path) -> Result<Vec<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);+ // unrelated artifacts that shouldn't be read into memory just to be skipped.+ if !has_native_magic(path) {+ return Ok(Vec::new());}let Ok(data) = std::fs::read(path) else {warn!("Could not read {} (skipping)", path.display());- return Ok(None);+ return Ok(Vec::new());};- // 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 archive = match Archive::parse(&data) {+ Ok(archive) => archive,+ Err(e) => {+ warn!("Could not parse {} (skipping): {e}", path.display());+ return Ok(Vec::new());+ }+ };- let Some(Ok(object)) = archive.objects().next() else {- warn!("No objects in {} (skipping)", path.display());- return Ok(None);+ let mut candidates = Vec::new();+ for object in archive.objects() {+ let Ok(object) = object else {+ warn!("Unparseable object in {} (skipping it)", path.display());+ continue;};- if object.file_format() != FileFormat::Elf {- return Ok(None);+ let format = object.file_format();+ if format != FileFormat::Elf && format != FileFormat::MachO {+ continue;}// Relocatable objects (.o) and other kinds aren't loadable images.@@ -253,34 +293,64 @@ fn parse_candidate(path: &Path) -> Result<Option<Candidate>> {object.kind(),ObjectKind::Executable | ObjectKind::Library | ObjectKind::Debug) {- return Ok(None);+ continue;}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));+ // Go's darwin linker compresses the DWARF it embeds (`__zdebug_*`+ // sections) by default, which the server can't read — surface+ // that as its own case so the guidance can name the fix.+ if format == FileFormat::MachO && contains_zdebug_section(object.data()) {+ candidates.push(Candidate::CompressedDwarf);+ } else {+ candidates.push(Candidate::NoDebugInfo);+ }+ continue;}+ // Without an identity the SDK can reproduce at runtime — the GNU+ // build id for ELF, the LC_UUID for Mach-O — the upload would never+ // match any crash event. For ELF specifically, symbolic synthesizes a+ // content-derived debug id when the build id is missing, so the+ // code_id check must come first.let debug_id = object.debug_id();- if debug_id.is_nil() {- return Ok(Some(Candidate::NoBuildId));+ if (format == FileFormat::Elf && object.code_id().is_none()) || debug_id.is_nil() {+ candidates.push(match format {+ FileFormat::MachO => Candidate::MissingUuid,+ _ => Candidate::NoBuildId,+ });+ continue;}- debug_id.to_string()- };- let size = data.len();- Ok(Some(Candidate::Valid(DebugSymbolFile {- debug_id,- path: path.to_path_buf(),- data,- size,- })))+ // Chunk id casing is per-format and case-sensitive on the server:+ // ELF ids are lowercase, Mach-O ids are uppercase (matching the SDKs+ // and `dsym upload`).+ let debug_id = match format {+ FileFormat::MachO => debug_id.to_string().to_uppercase(),+ _ => debug_id.to_string(),+ };++ // For a fat Mach-O, upload the slice, not the whole container: the+ // server resolves one binary per chunk id.+ let object_data = object.data().to_vec();+ candidates.push(Candidate::Valid(DebugSymbolFile {+ debug_id,+ path: path.to_path_buf(),+ size: object_data.len(),+ data: object_data,+ format,+ }));+ }++ Ok(candidates)+}++/// Detect Go-style compressed DWARF in a Mach-O slice. Section names live+/// verbatim in the section headers, so a plain byte scan is sufficient for a+/// diagnostic.+fn contains_zdebug_section(data: &[u8]) -> bool {+ data.windows(b"__zdebug_".len())+ .any(|window| window == b"__zdebug_")}/// Render guidance for files that couldn't be uploaded; returns an error when@@ -308,6 +378,25 @@ pub fn report_problems(report: &DiscoveryReport, directory: &Path) -> Result<()>);}+ for path in &report.missing_uuid {+ warn!(+ "{} has debug info but no LC_UUID, so it cannot be matched to \+ crash events (skipping). Relink without stripping the UUID load \+ command (ld adds one by default; `-no_uuid` removes it).",+ path.display()+ );+ }++ for path in &report.compressed_dwarf {+ warn!(+ "{} carries compressed DWARF (`__zdebug` sections), which can't be \+ used for symbolication yet (skipping). Go compresses DWARF by \+ default on macOS — rebuild with `-ldflags=-compressdwarf=false` \+ and upload that binary.",+ path.display()+ );+ }+if !report.missing_build_id.is_empty() {let listing = report.missing_build_id@@ -333,7 +422,7 @@ pub fn report_problems(report: &DiscoveryReport, directory: &Path) -> Result<()>if nothing_to_upload {anyhow::bail!(- "No ELF files with debug info or dSYM bundles found in {}",+ "No ELF or Mach-O files with debug info or dSYM bundles found in {}",directory.display());}@@ -375,11 +464,12 @@ pub fn package_dsym_bundles(bundles: &[PathBuf], include_source: bool) -> Vec<Sy/// Coalesce uploads that share a chunk_id, keeping the first occurrence.///-/// ELF chunk_ids are lowercase (derived by `symbolic`) and Mach-O dSYM chunk_ids-/// are uppercase (to match what the SDK and `dsym upload` emit), so the two-/// formats never collide — this only merges the same dSYM UUID appearing in more-/// than one bundle. Casing is preserved exactly and must never be normalized:-/// the SDK matches chunk_ids case-sensitively, per format.+/// ELF chunk_ids are lowercase (derived by `symbolic`) and Mach-O chunk_ids —+/// executables and dSYMs alike — are uppercase (to match what the SDKs emit),+/// so the two formats never collide; this merges the same Mach-O UUID+/// appearing both as a binary and in a dSYM bundle, or a dSYM UUID appearing+/// in more than one bundle. Casing is preserved exactly and must never be+/// normalized: the SDK matches chunk_ids case-sensitively, per format.pub fn dedup_uploads_by_chunk_id(uploads: Vec<SymbolSetUpload>) -> Vec<SymbolSetUpload> {let mut seen = std::collections::HashSet::new();let mut deduped = Vec::with_capacity(uploads.len());diff --git a/cli/src/debug_symbols/upload.rs b/cli/src/debug_symbols/upload.rsindex bca12cb8ef10..e34af0e853ef 100644--- a/cli/src/debug_symbols/upload.rs+++ b/cli/src/debug_symbols/upload.rs@@ -4,7 +4,11 @@ use anyhow::{anyhow, Result};use tracing::info;use crate::{- api::{self, releases::ReleaseBuilder, symbol_sets::SymbolSetUpload},+ api::{+ self,+ releases::ReleaseBuilder,+ symbol_sets::{SymbolSetUpload, MAX_FILE_SIZE},+ },debug_symbols::{dedup_uploads_by_chunk_id, discover, package_dsym_bundles, report_problems},sourcemaps::args::{pack_version, ReleaseArgs, UploadConflictArgs},utils::git::get_git_info,@@ -13,9 +17,10 @@ use crate::{#[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, as are Apple `.dSYM` bundles- /// (macOS only — needs `dwarfdump` from Xcode); everything else is skipped.+ /// ELF and Mach-O executables, shared libraries, and `objcopy+ /// --only-keep-debug` companions with debug info are uploaded, as are Apple+ /// `.dSYM` bundles (macOS only — needs `dwarfdump` from Xcode); everything+ /// else is skipped.#[arg(short, long)]pub directory: PathBuf,@@ -58,7 +63,7 @@ pub fn upload(args: &Args) -> Result<()> {report_problems(&report, &directory)?;info!(- "Found {} ELF debug file(s) and {} dSYM bundle(s)",+ "Found {} native debug file(s) and {} dSYM bundle(s)",report.files.len(),report.dsym_bundles.len());@@ -68,25 +73,20 @@ pub fn upload(args: &Args) -> Result<()> {// logs-and-skips failures (e.g. a missing dwarfdump), so a dSYM-only// directory can yield zero uploads — creating the release up front would// leave a release record behind with no symbols attached to it.- let mut uploads: Vec<SymbolSetUpload> = Vec::new();+ let mut native_uploads = Vec::with_capacity(report.files.len());for file in report.files {info!("Processing {} (debug id {})",file.path.display(),file.debug_id);- uploads.push(file.into_upload(None, *include_source)?);+ native_uploads.push(file.into_upload(None, *include_source)?);}- // Apple dSYM bundles run through the same packaging path as- // `posthog-cli dsym upload` (uppercase UUID chunk_ids, AppleDsym container);- // a bundle that can't be processed (e.g. no dwarfdump on Linux) is skipped- // with a warning so any ELF symbols above still upload.- uploads.extend(package_dsym_bundles(&report.dsym_bundles, *include_source));-- // ELF (lowercase) and dSYM (uppercase) chunk_ids can't collide, but the same- // dSYM UUID can appear in more than one bundle — keep one upload per chunk_id.- let mut uploads = dedup_uploads_by_chunk_id(uploads);+ // A failed or oversized dSYM leaves a matching standalone Mach-O as the+ // fallback. Successfully packaged, uploadable dSYMs take priority.+ let dsym_uploads = package_dsym_bundles(&report.dsym_bundles, *include_source);+ let mut uploads = merge_uploads_prefer_dsym(dsym_uploads, native_uploads, MAX_FILE_SIZE);if uploads.is_empty() {anyhow::bail!(@@ -134,3 +134,61 @@ pub fn upload(args: &Args) -> Result<()> {Ok(())}++/// Merge packaged native symbols, preferring an uploadable dSYM when both+/// inputs carry the same uppercase Mach-O UUID. Oversized dSYMs come last so a+/// matching native upload wins, but remain available when there is no fallback+/// and the upload layer can preserve its existing warning behavior. ELF ids+/// remain lowercase and cannot collide.+fn merge_uploads_prefer_dsym(+ dsym_uploads: Vec<SymbolSetUpload>,+ native_uploads: Vec<SymbolSetUpload>,+ max_file_size: usize,+) -> Vec<SymbolSetUpload> {+ let (mut preferred_dsyms, oversized_dsyms): (Vec<_>, Vec<_>) = dsym_uploads+ .into_iter()+ .partition(|upload| upload.data.len() <= max_file_size);+ preferred_dsyms.extend(native_uploads);+ preferred_dsyms.extend(oversized_dsyms);+ dedup_uploads_by_chunk_id(preferred_dsyms)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn merge_uploads_prefers_dsym_over_matching_macho() {+ let uuid = "77C2F55F-C959-487A-9601-6A715A9BB5DE";+ let upload = |chunk_id: &str, data: &[u8]| SymbolSetUpload {+ chunk_id: chunk_id.to_string(),+ release_id: None,+ data: data.to_vec(),+ };++ let uploads = merge_uploads_prefer_dsym(+ vec![upload(uuid, b"dsym")],+ vec![upload(uuid, b"macho")],+ 10,+ );++ assert_eq!(uploads.len(), 1);+ assert_eq!(uploads[0].data, b"dsym");+ }++ #[test]+ fn merge_uploads_uses_macho_when_matching_dsym_is_oversized() {+ let uuid = "77C2F55F-C959-487A-9601-6A715A9BB5DE";+ let upload = |data: &[u8]| SymbolSetUpload {+ chunk_id: uuid.to_string(),+ release_id: None,+ data: data.to_vec(),+ };++ let uploads =+ merge_uploads_prefer_dsym(vec![upload(b"oversized-dsym")], vec![upload(b"macho")], 5);++ assert_eq!(uploads.len(), 1);+ assert_eq!(uploads[0].data, b"macho");+ }+}diff --git a/cli/tests/debug_symbols.rs b/cli/tests/debug_symbols.rsindex edf1e4661914..5e83ee7fd3ed 100644--- a/cli/tests/debug_symbols.rs+++ b/cli/tests/debug_symbols.rs@@ -159,6 +159,117 @@ fn classifies_elfs_without_debug_info_or_build_id() {assert!(posthog_cli::debug_symbols::report_problems(&report, dir.path()).is_ok());}+/// Decompress a zstd-packed binary fixture into a scratch directory.+fn unpack_fixture(name: &str, dir: &Path, as_name: &str) -> PathBuf {+ let compressed = std::fs::read(fixtures_dir().join(name)).unwrap();+ let target = dir.join(as_name);+ std::fs::write(&target, zstd::decode_all(compressed.as_slice()).unwrap()).unwrap();+ target+}++#[test]+fn discovers_and_packages_macho_executables() {+ let dir = tempfile::tempdir().unwrap();+ let path = unpack_fixture("test_go_binary_macho.zst", dir.path(), "gohello");++ let report = discover(dir.path()).unwrap();+ assert_eq!(+ report.files.len(),+ 1,+ "expected the Mach-O binary to be valid"+ );+ assert!(report.compressed_dwarf.is_empty());++ // Mach-O chunk ids are the LC_UUID, uppercased to match the SDKs and+ // `dsym upload` (elf_debug_id parses any object and reports the+ // symbolic-cased id, which is lowercase).+ let file = report.files.into_iter().next().unwrap();+ assert_eq!(file.debug_id, elf_debug_id(&path).unwrap().to_uppercase());++ // Packaged as an AppleDsym container with the thin Mach-O at `dwarf`.+ let upload = file.into_upload(None, false).unwrap();+ let unwrapped: AppleDsym = read_symbol_data(&upload.data).unwrap();+ assert_eq!(dwarf_magic(&unwrapped.data), [0xcf, 0xfa, 0xed, 0xfe]);+}++#[test]+fn flags_compressed_dwarf_macho_with_guidance() {+ let dir = tempfile::tempdir().unwrap();+ unpack_fixture("test_go_binary_macho_zdebug.zst", dir.path(), "gohello");++ // Go's default darwin build compresses DWARF (__zdebug sections), which+ // symbolication can't read — classified separately so the guidance can+ // name -compressdwarf=false, and never uploaded as a names-only set.+ let report = discover(dir.path()).unwrap();+ assert!(report.files.is_empty());+ assert!(report.without_debug_info.is_empty());+ assert_eq!(report.compressed_dwarf.len(), 1);++ assert!(posthog_cli::debug_symbols::report_problems(&report, dir.path()).is_err());+}++#[test]+fn discovers_every_fat_macho_slice() {+ let dir = tempfile::tempdir().unwrap();+ let thin_path = unpack_fixture("test_go_binary_macho.zst", dir.path(), "thin");+ let thin = std::fs::read(&thin_path).unwrap();+ std::fs::remove_file(&thin_path).unwrap();++ // Second slice: same binary with one LC_UUID byte flipped, standing in+ // for another architecture's build (each slice carries its own UUID).+ let lc_uuid_header = b"\x1b\x00\x00\x00\x18\x00\x00\x00";+ let uuid_pos = thin+ .windows(lc_uuid_header.len())+ .position(|w| w == lc_uuid_header)+ .expect("fixture must carry LC_UUID")+ + lc_uuid_header.len();+ let mut thin_b = thin.clone();+ thin_b[uuid_pos] ^= 0xff;++ // Wrap both in a universal (fat) container: fat_header + two fat_arch+ // entries (big-endian), then the slices at aligned offsets, with+ // cputype/cpusubtype copied from each slice's own header.+ const ALIGN: usize = 0x4000;+ let slice_a_offset = ALIGN;+ let slice_b_offset = (slice_a_offset + thin.len()).next_multiple_of(ALIGN);+ let mut fat = vec![0u8; slice_b_offset + thin_b.len()];+ fat[0..4].copy_from_slice(&0xcafebabe_u32.to_be_bytes());+ fat[4..8].copy_from_slice(&2_u32.to_be_bytes());+ for (index, (slice, offset)) in [(&thin, slice_a_offset), (&thin_b, slice_b_offset)]+ .into_iter()+ .enumerate()+ {+ let entry = &mut fat[8 + index * 20..8 + (index + 1) * 20];+ entry[0..4]+ .copy_from_slice(&u32::from_le_bytes(slice[4..8].try_into().unwrap()).to_be_bytes());+ entry[4..8]+ .copy_from_slice(&u32::from_le_bytes(slice[8..12].try_into().unwrap()).to_be_bytes());+ entry[8..12].copy_from_slice(&(offset as u32).to_be_bytes());+ entry[12..16].copy_from_slice(&(slice.len() as u32).to_be_bytes());+ entry[16..20].copy_from_slice(&14_u32.to_be_bytes());+ fat[offset..offset + slice.len()].copy_from_slice(slice);+ }+ std::fs::write(dir.path().join("universal"), &fat).unwrap();++ let report = discover(dir.path()).unwrap();+ assert_eq!(report.files.len(), 2, "expected one candidate per slice");++ // Each upload carries its own slice's bytes under that slice's UUID, not+ // the fat container: the server resolves one thin binary per chunk id.+ for (file, expected_slice) in report.files.into_iter().zip([&thin, &thin_b]) {+ assert_eq!(file.debug_id, file.debug_id.to_uppercase());+ let upload = file.into_upload(None, false).unwrap();+ let unwrapped: AppleDsym = read_symbol_data(&upload.data).unwrap();+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(unwrapped.data)).unwrap();+ let mut dwarf = Vec::new();+ zip.by_name("dwarf")+ .unwrap()+ .read_to_end(&mut dwarf)+ .unwrap();+ assert_eq!(&dwarf, expected_slice);+ }+}+#[test]fn dsym_only_directory_is_uploadable() {// A directory with only a dSYM bundle (no ELF) used to be a hard error@@ -182,7 +293,7 @@ fn empty_directory_errors_on_both_formats() {let err = report_problems(&report, dir.path()).unwrap_err();assert!(err.to_string()- .contains("No ELF files with debug info or dSYM bundles"),+ .contains("No ELF or Mach-O files with debug info or dSYM bundles"),"got: {err}");}diff --git a/rust/cymbal/tests/static/native/build.sh b/rust/cymbal/tests/static/native/build.shindex d1b53fd99461..1df5d852460b 100755--- a/rust/cymbal/tests/static/native/build.sh+++ b/rust/cymbal/tests/static/native/build.sh@@ -79,6 +79,17 @@ GOOS=linux GOARCH=amd64 go build -ldflags "-B gobuildid" \zstd -19 -f -q test_go_binary_pathsrm test_go_binary_paths+# Go Mach-O fixtures: DWARF lives in the executable itself (Go never emits a+# dSYM). -compressdwarf=false keeps the DWARF readable by symbolic; the+# default build carries compressed __zdebug sections and is the fixture for+# the "rebuild with -compressdwarf=false" guidance.+GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags "-compressdwarf=false" -o test_go_binary_macho test_go.go+zstd -19 -f -q test_go_binary_macho+rm test_go_binary_macho+GOOS=darwin GOARCH=arm64 go build -trimpath -o test_go_binary_macho_zdebug test_go.go+zstd -19 -f -q test_go_binary_macho_zdebug+rm test_go_binary_macho_zdebug+echo "Built fixtures:"file test_binary_nopie test_binary_pie test_binary_inline test_binary_nodebug test_binary_nobuildid-ls -la test_rust_binary.zst test_go_binary.zst test_go_binary_paths.zst+ls -la test_rust_binary.zst test_go_binary.zst test_go_binary_paths.zst test_go_binary_macho.zst test_go_binary_macho_zdebug.zstdiff --git a/rust/cymbal/tests/static/native/test_go_binary_macho.zst b/rust/cymbal/tests/static/native/test_go_binary_macho.zstnew file mode 100755index 000000000000..e2fb8722daa5Binary files /dev/null and b/rust/cymbal/tests/static/native/test_go_binary_macho.zst differdiff --git a/rust/cymbal/tests/static/native/test_go_binary_macho_zdebug.zst b/rust/cymbal/tests/static/native/test_go_binary_macho_zdebug.zstnew file mode 100755index 000000000000..56348c88252bBinary files /dev/null and b/rust/cymbal/tests/static/native/test_go_binary_macho_zdebug.zst differ