Skip to content

: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.

refactor(cymbal): extract shared native symbolication module from apple (#62581)

Catalin Irimiefc39dcc06de8
diff --git a/rust/cymbal-resolution/src/service/resolve.rs b/rust/cymbal-resolution/src/service/resolve.rs
index 88771090f61b..3dd3dd374e95 100644
--- a/rust/cymbal-resolution/src/service/resolve.rs
+++ b/rust/cymbal-resolution/src/service/resolve.rs
@@ -5,7 +5,7 @@ use tonic::{Status, Streaming};
use tracing::{debug, warn};
use cymbal::error::UnhandledError;
-use cymbal::langs::apple::AppleDebugImage;
+use cymbal::langs::native::DebugImage;
use cymbal::stages::resolution::exception::ExceptionResolver;
use cymbal::stages::resolution::frame::FrameResolver;
use cymbal::stages::resolution::ResolutionStage;
@@ -240,7 +240,7 @@ async fn resolve_item(stage: &ResolutionStage, item: &ResolveItem) -> Result<Vec
let exception: Exception = serde_json::from_slice(&item.exception_json)
.map_err(|e| ItemFailure::InvalidPayload(format!("invalid exception_json: {e}")))?;
- let debug_images = apple_debug_images_from_metadata(&item.metadata)?;
+ let debug_images = debug_images_from_metadata(&item.metadata)?;
let resolved = resolve_one_exception(stage.clone(), item.team_id, exception, debug_images)
.await
@@ -255,7 +255,7 @@ async fn resolve_item(stage: &ResolutionStage, item: &ResolveItem) -> Result<Vec
.map_err(|e| ItemFailure::Unhandled(format!("serialize resolved exception: {e}")))
}
-fn apple_debug_images_from_metadata(metadata: &[u8]) -> Result<Vec<AppleDebugImage>, ItemFailure> {
+fn debug_images_from_metadata(metadata: &[u8]) -> Result<Vec<DebugImage>, ItemFailure> {
if metadata.is_empty() {
return Ok(Vec::new());
}
@@ -279,7 +279,7 @@ async fn resolve_one_exception(
stage: ResolutionStage,
team_id: i32,
exception: Exception,
- debug_images: Vec<AppleDebugImage>,
+ debug_images: Vec<DebugImage>,
) -> Result<Exception, ResolveOneError> {
let exception = if ExceptionResolver::is_java_exception(&exception) {
let _permit = acquire_permit(&stage).await?;
diff --git a/rust/cymbal-resolution/tests/service_tests.rs b/rust/cymbal-resolution/tests/service_tests.rs
index 12cfe0dd8efd..5f191e74d40c 100644
--- a/rust/cymbal-resolution/tests/service_tests.rs
+++ b/rust/cymbal-resolution/tests/service_tests.rs
@@ -7,7 +7,7 @@ use std::time::Duration;
use async_trait::async_trait;
use cymbal::error::{ResolveError, UnhandledError};
use cymbal::frames::{Frame, RawFrame};
-use cymbal::langs::apple::AppleDebugImage;
+use cymbal::langs::native::DebugImage;
use cymbal::stages::resolution::symbol::SymbolResolver;
use cymbal::symbol_store::{chunk_id::OrChunkId, proguard::ProguardRef};
use cymbal::types::operator::TeamId;
@@ -37,7 +37,7 @@ impl SymbolResolver for FakeResolver {
&self,
_team_id: TeamId,
_frame: &RawFrame,
- _debug_images: &[AppleDebugImage],
+ _debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
if self.fail_unhandled {
return Err(UnhandledError::Other("forced resolver failure".to_string()));
@@ -78,7 +78,7 @@ impl SymbolResolver for SlowResolver {
&self,
_team_id: TeamId,
_frame: &RawFrame,
- _debug_images: &[AppleDebugImage],
+ _debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
let call_index = self.started.fetch_add(1, Ordering::AcqRel);
let active = self.active.fetch_add(1, Ordering::AcqRel) + 1;
diff --git a/rust/cymbal/src/error.rs b/rust/cymbal/src/error.rs
index 28dc68b9853e..2595f3179585 100644
--- a/rust/cymbal/src/error.rs
+++ b/rust/cymbal/src/error.rs
@@ -71,6 +71,8 @@ pub enum FrameError {
Proguard(#[from] ProguardError),
#[error(transparent)]
Apple(#[from] AppleError),
+ #[error(transparent)]
+ Native(#[from] NativeError),
#[error("No symbol set for chunk id: {0}")]
MissingChunkIdData(String),
}
@@ -179,6 +181,41 @@ pub enum AppleError {
NoMatchingDebugImage,
}
+// Errors produced by the shared native (DWARF/symcache) resolution machinery.
+// Apple frames map these 1:1 onto AppleError so that stored failure reasons
+// and metric labels for apple keep their existing shape.
+#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
+pub enum NativeError {
+ #[error("Data error: {0}")]
+ DataError(#[from] SymbolDataError),
+ #[error("No debug symbols uploaded for debug_id: {0}")]
+ MissingSymbolSet(String),
+ #[error("No debug_id found for frame")]
+ NoDebugId,
+ #[error("Invalid address format: {0}")]
+ InvalidAddress(String),
+ #[error("Symbol not found at address: {0:#x}")]
+ SymbolNotFound(u64),
+ #[error("Failed to parse debug symbols: {0}")]
+ ParseError(String),
+ #[error("No matching debug image found for frame")]
+ NoMatchingDebugImage,
+}
+
+impl From<NativeError> for AppleError {
+ fn from(e: NativeError) -> Self {
+ match e {
+ NativeError::DataError(e) => AppleError::DataError(e),
+ NativeError::MissingSymbolSet(id) => AppleError::MissingDsym(id),
+ NativeError::NoDebugId => AppleError::NoDebugId,
+ NativeError::InvalidAddress(s) => AppleError::InvalidAddress(s),
+ NativeError::SymbolNotFound(addr) => AppleError::SymbolNotFound(addr),
+ NativeError::ParseError(s) => AppleError::ParseError(s),
+ NativeError::NoMatchingDebugImage => AppleError::NoMatchingDebugImage,
+ }
+ }
+}
+
#[derive(Debug, Error, Clone, Serialize, PartialEq)]
pub enum EventError {
#[error("Wrong event type: {0} for event {1}")]
@@ -247,6 +284,17 @@ impl AppleError {
}
}
+impl NativeError {
+ pub fn metric_reason(&self) -> &'static str {
+ match self {
+ Self::NoDebugId | Self::NoMatchingDebugImage => "no_reference",
+ Self::MissingSymbolSet(_) => "no_symbol_set",
+ Self::SymbolNotFound(_) => "symbol_not_found",
+ Self::DataError(_) | Self::InvalidAddress(_) | Self::ParseError(_) => "invalid_data",
+ }
+ }
+}
+
impl FrameError {
pub fn metric_reason(&self) -> &'static str {
match self {
@@ -254,6 +302,7 @@ impl FrameError {
Self::Hermes(e) => e.metric_reason(),
Self::Proguard(e) => e.metric_reason(),
Self::Apple(e) => e.metric_reason(),
+ Self::Native(e) => e.metric_reason(),
Self::MissingChunkIdData(_) => "no_symbol_set",
}
}
@@ -283,6 +332,12 @@ impl From<AppleError> for ResolveError {
}
}
+impl From<NativeError> for ResolveError {
+ fn from(e: NativeError) -> Self {
+ FrameError::Native(e).into()
+ }
+}
+
impl From<FrameError> for UnhandledError {
fn from(e: FrameError) -> Self {
// TODO - this should be unreachable, but I need to reconsider the error enum structure to make it possible to assert that
diff --git a/rust/cymbal/src/frames/mod.rs b/rust/cymbal/src/frames/mod.rs
index 44c0fe55cf16..68f1a67e01c1 100644
--- a/rust/cymbal/src/frames/mod.rs
+++ b/rust/cymbal/src/frames/mod.rs
@@ -9,17 +9,9 @@ use crate::{
error::UnhandledError,
fingerprinting::{FingerprintBuilder, FingerprintComponent, FingerprintRecordPart},
langs::{
- apple::{AppleDebugImage, RawAppleFrame},
- custom::CustomFrame,
- dart::RawDartFrame,
- go::RawGoFrame,
- hermes::RawHermesFrame,
- java::RawJavaFrame,
- js::RawJSFrame,
- node::RawNodeFrame,
- php::RawPHPFrame,
- python::RawPythonFrame,
- ruby::RawRubyFrame,
+ apple::RawAppleFrame, custom::CustomFrame, dart::RawDartFrame, go::RawGoFrame,
+ hermes::RawHermesFrame, java::RawJavaFrame, js::RawJSFrame, native::DebugImage,
+ node::RawNodeFrame, php::RawPHPFrame, python::RawPythonFrame, ruby::RawRubyFrame,
rust::RawRustFrame,
},
metric_consts::{FRAME_NOT_RESOLVED, FRAME_RESOLVED, LEGACY_JS_FRAME_RESOLVED, PER_FRAME_TIME},
@@ -89,7 +81,7 @@ impl RawFrame {
&self,
team_id: i32,
catalog: &Catalog,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
let frame_resolve_time = common_metrics::timing_guard(PER_FRAME_TIME, &[]);
let (res, lang_tag) = match self {
@@ -170,7 +162,7 @@ impl RawFrame {
}
}
- pub fn raw_id(&self, team_id: i32, debug_images: &[AppleDebugImage]) -> RawFrameId {
+ pub fn raw_id(&self, team_id: i32, debug_images: &[DebugImage]) -> RawFrameId {
let hash_id = match self {
RawFrame::JavaScriptWeb(raw) | RawFrame::LegacyJS(raw) => raw.frame_id(),
RawFrame::JavaScriptNode(raw) => raw.frame_id(),
@@ -189,12 +181,7 @@ impl RawFrame {
RawFrameId::new(hash_id, team_id)
}
- pub fn frame_id(
- &self,
- team_id: i32,
- index: usize,
- debug_images: &[AppleDebugImage],
- ) -> FrameId {
+ pub fn frame_id(&self, team_id: i32, index: usize, debug_images: &[DebugImage]) -> FrameId {
self.raw_id(team_id, debug_images).to_full(index as i32)
}
diff --git a/rust/cymbal/src/langs/apple.rs b/rust/cymbal/src/langs/apple.rs
index 1ea4757bdf07..489eb684b748 100644
--- a/rust/cymbal/src/langs/apple.rs
+++ b/rust/cymbal/src/langs/apple.rs
@@ -12,11 +12,13 @@ use crate::{
config::FRAME_CONTEXT_LINES,
error::{AppleError, FrameError, ResolveError, UnhandledError},
frames::{record_frame_resolution_failure, Frame},
+ langs::native::{self, DebugImage},
langs::utils::{add_raw_to_junk, get_context_lines},
langs::CommonFrameMetadata,
symbol_store::{
- apple::{AppleRef, ParsedAppleSymbols},
+ apple::AppleRef,
chunk_id::OrChunkId,
+ native::{ParsedNativeSymbols, SymbolInfo},
SymbolCatalog,
},
};
@@ -69,22 +71,6 @@ fn is_system_module(module: &Option<String>) -> bool {
})
}
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct AppleDebugImage {
- pub debug_id: String,
- pub image_addr: String,
- #[serde(default)]
- pub image_vmaddr: Option<String>,
- #[serde(default)]
- pub image_size: Option<u64>,
- #[serde(default)]
- pub code_file: Option<String>,
- #[serde(default, rename = "type")]
- pub image_type: Option<String>,
- #[serde(default)]
- pub arch: Option<String>,
-}
-
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RawAppleFrame {
pub instruction_addr: Option<String>,
@@ -105,10 +91,10 @@ impl RawAppleFrame {
&self,
team_id: i32,
catalog: &C,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError>
where
- C: SymbolCatalog<OrChunkId<AppleRef>, ParsedAppleSymbols>,
+ C: SymbolCatalog<OrChunkId<AppleRef>, ParsedNativeSymbols>,
{
tracing::debug!(
"[apple-debug] resolve() called: instruction_addr={:?}, module={:?}, function={:?}, debug_images_count={}",
@@ -151,10 +137,10 @@ impl RawAppleFrame {
&self,
team_id: i32,
catalog: &C,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<Frame>, ResolveError>
where
- C: SymbolCatalog<OrChunkId<AppleRef>, ParsedAppleSymbols>,
+ C: SymbolCatalog<OrChunkId<AppleRef>, ParsedNativeSymbols>,
{
let instruction_addr = self
.instruction_addr
@@ -163,20 +149,24 @@ impl RawAppleFrame {
"missing instruction_addr".into(),
))?;
- let instruction_addr = parse_hex_address(instruction_addr)?;
+ let instruction_addr =
+ native::parse_hex_address(instruction_addr).map_err(AppleError::from)?;
tracing::debug!(
"[apple-debug] resolve_impl: parsed instruction_addr=0x{:x}",
instruction_addr
);
- let debug_image = self.find_debug_image(instruction_addr, debug_images)?;
+ let debug_image =
+ native::find_debug_image(instruction_addr, self.image_addr.as_deref(), debug_images)
+ .map_err(AppleError::from)?;
tracing::debug!(
"[apple-debug] resolve_impl: matched debug_image debug_id={}, image_addr={}",
debug_image.debug_id,
debug_image.image_addr
);
- let relative_addr = self.calculate_relative_addr(instruction_addr, debug_image)?;
+ let relative_addr = native::calculate_relative_addr(instruction_addr, debug_image)
+ .map_err(AppleError::from)?;
// Subtract 1 from return-address frames so the lookup targets the call instruction
// rather than the instruction after it, giving the correct source line.
@@ -193,12 +183,12 @@ impl RawAppleFrame {
"[apple-debug] resolve_impl: looking up symbols for chunk_id={}",
debug_image.debug_id
);
- let symbols: Arc<ParsedAppleSymbols> = catalog
+ let symbols: Arc<ParsedNativeSymbols> = catalog
.lookup(team_id, OrChunkId::chunk_id(debug_image.debug_id.clone()))
.await?;
tracing::debug!("[apple-debug] resolve_impl: symbols loaded successfully");
- let symbol_infos = symbols.lookup(lookup_addr)?;
+ let symbol_infos = symbols.lookup(lookup_addr).map_err(AppleError::from)?;
if symbol_infos.is_empty() {
return Err(AppleError::SymbolNotFound(lookup_addr).into());
}
@@ -248,60 +238,7 @@ impl RawAppleFrame {
Ok(frames)
}
- fn find_debug_image<'a>(
- &self,
- instruction_addr: u64,
- debug_images: &'a [AppleDebugImage],
- ) -> Result<&'a AppleDebugImage, AppleError> {
- let frame_image_addr = self
- .image_addr
- .as_ref()
- .and_then(|addr| parse_hex_address(addr).ok());
-
- for image in debug_images {
- let image_base = parse_hex_address(&image.image_addr).ok();
-
- if let (Some(frame_addr), Some(base)) = (frame_image_addr, image_base) {
- if frame_addr == base {
- return Ok(image);
- }
- }
-
- if let (Some(base), Some(size)) = (image_base, image.image_size) {
- if instruction_addr >= base && instruction_addr < base.saturating_add(size) {
- return Ok(image);
- }
- }
- }
-
- Err(AppleError::NoMatchingDebugImage)
- }
-
- fn calculate_relative_addr(
- &self,
- instruction_addr: u64,
- debug_image: &AppleDebugImage,
- ) -> Result<u64, AppleError> {
- let image_addr = parse_hex_address(&debug_image.image_addr)?;
-
- if instruction_addr < image_addr {
- return Err(AppleError::InvalidAddress(format!(
- "instruction_addr 0x{:x} < image_addr 0x{:x}",
- instruction_addr, image_addr
- )));
- }
-
- // Calculate the offset from the runtime load address
- // The symcache already contains addresses relative to the binary's VM base,
- // so we just need the offset from where it was loaded
- Ok(instruction_addr - image_addr)
- }
-
- fn build_resolved_frame(
- &self,
- symbol_info: &crate::symbol_store::apple::SymbolInfo,
- _debug_image: &AppleDebugImage,
- ) -> Frame {
+ fn build_resolved_frame(&self, symbol_info: &SymbolInfo, _debug_image: &DebugImage) -> Frame {
// Override in_app to false for system frameworks or compiler-generated code
let is_compiler_generated = symbol_info
.filename
@@ -410,14 +347,18 @@ impl RawAppleFrame {
frame
}
- pub fn frame_id(&self, debug_images: &[AppleDebugImage]) -> String {
+ pub fn frame_id(&self, debug_images: &[DebugImage]) -> String {
let mut hasher = Sha512::new();
// Absolute instruction addresses are ASLR-slid per process launch, so hashing
// them directly gives the same logical frame a different id every launch and
// the frame record cache never hits. Hash the launch-invariant
// (debug image, relative offset) identity instead whenever we can compute it.
- match self.launch_invariant_addr(debug_images) {
+ match native::launch_invariant_addr(
+ self.instruction_addr.as_deref(),
+ self.image_addr.as_deref(),
+ debug_images,
+ ) {
Some((debug_id, relative_addr)) => {
hasher.update(debug_id.as_bytes());
hasher.update(format!("rel:0x{relative_addr:x}").as_bytes());
@@ -443,15 +384,6 @@ impl RawAppleFrame {
format!("{:x}", hasher.finalize())
}
-
- fn launch_invariant_addr(&self, debug_images: &[AppleDebugImage]) -> Option<(String, u64)> {
- let instruction_addr = parse_hex_address(self.instruction_addr.as_ref()?).ok()?;
- let debug_image = self.find_debug_image(instruction_addr, debug_images).ok()?;
- let relative_addr = self
- .calculate_relative_addr(instruction_addr, debug_image)
- .ok()?;
- Some((debug_image.debug_id.clone(), relative_addr))
- }
}
/// Infer the programming language from a source filename for syntax highlighting.
@@ -468,11 +400,6 @@ fn lang_from_filename(filename: Option<&str>) -> &'static str {
}
}
-fn parse_hex_address(s: &str) -> Result<u64, AppleError> {
- let s = s.trim().trim_start_matches("0x").trim_start_matches("0X");
- u64::from_str_radix(s, 16).map_err(|_| AppleError::InvalidAddress(s.to_string()))
-}
-
impl From<&RawAppleFrame> for Frame {
fn from(raw: &RawAppleFrame) -> Self {
let mut f = Frame {
@@ -506,189 +433,6 @@ impl From<&RawAppleFrame> for Frame {
mod test {
use super::*;
- #[test]
- fn test_parse_hex_address_with_0x_prefix() {
- assert_eq!(parse_hex_address("0x100000000").unwrap(), 0x100000000);
- assert_eq!(parse_hex_address("0X100000000").unwrap(), 0x100000000);
- }
-
- #[test]
- fn test_parse_hex_address_without_prefix() {
- assert_eq!(parse_hex_address("100000000").unwrap(), 0x100000000);
- assert_eq!(parse_hex_address("deadbeef").unwrap(), 0xdeadbeef);
- }
-
- #[test]
- fn test_parse_hex_address_with_whitespace() {
- assert_eq!(parse_hex_address(" 0x100000000 ").unwrap(), 0x100000000);
- }
-
- #[test]
- fn test_parse_hex_address_invalid() {
- assert!(parse_hex_address("not_hex").is_err());
- assert!(parse_hex_address("0xGGGG").is_err());
- }
-
- #[test]
- fn test_calculate_relative_addr_with_vmaddr() {
- let frame = RawAppleFrame {
- instruction_addr: Some("0x100004000".to_string()),
- symbol_addr: None,
- image_addr: Some("0x100000000".to_string()),
- image_uuid: None,
- module: None,
- function: None,
- filename: None,
- lineno: None,
- colno: None,
- meta: CommonFrameMetadata::default(),
- };
-
- let debug_image = AppleDebugImage {
- debug_id: "test-uuid".to_string(),
- image_addr: "0x100000000".to_string(),
- image_vmaddr: Some("0x100000000".to_string()),
- image_size: Some(0x10000),
- code_file: None,
- image_type: None,
- arch: None,
- };
-
- let result = frame
- .calculate_relative_addr(0x100004000, &debug_image)
- .unwrap();
- assert_eq!(result, 0x4000);
- }
-
- #[test]
- fn test_calculate_relative_addr_default_vmaddr() {
- let frame = RawAppleFrame {
- instruction_addr: Some("0x100004000".to_string()),
- symbol_addr: None,
- image_addr: Some("0x100000000".to_string()),
- image_uuid: None,
- module: None,
- function: None,
- filename: None,
- lineno: None,
- colno: None,
- meta: CommonFrameMetadata::default(),
- };
-
- let debug_image = AppleDebugImage {
- debug_id: "test-uuid".to_string(),
- image_addr: "0x100000000".to_string(),
- image_vmaddr: None,
- image_size: Some(0x10000),
- code_file: None,
- image_type: None,
- arch: None,
- };
-
- let result = frame
- .calculate_relative_addr(0x100004000, &debug_image)
- .unwrap();
- assert_eq!(result, 0x4000);
- }
-
- #[test]
- fn test_find_debug_image_by_image_addr() {
- let frame = RawAppleFrame {
- instruction_addr: Some("0x100004000".to_string()),
- symbol_addr: None,
- image_addr: Some("0x100000000".to_string()),
- image_uuid: None,
- module: None,
- function: None,
- filename: None,
- lineno: None,
- colno: None,
- meta: CommonFrameMetadata::default(),
- };
-
- let debug_images = vec![
- AppleDebugImage {
- debug_id: "other-uuid".to_string(),
- image_addr: "0x200000000".to_string(),
- image_vmaddr: None,
- image_size: Some(0x10000),
- code_file: None,
- image_type: None,
- arch: None,
- },
- AppleDebugImage {
- debug_id: "matching-uuid".to_string(),
- image_addr: "0x100000000".to_string(),
- image_vmaddr: None,
- image_size: Some(0x10000),
- code_file: None,
- image_type: None,
- arch: None,
- },
- ];
-
- let result = frame.find_debug_image(0x100004000, &debug_images).unwrap();
- assert_eq!(result.debug_id, "matching-uuid");
- }
-
- #[test]
- fn test_find_debug_image_by_address_range() {
- let frame = RawAppleFrame {
- instruction_addr: Some("0x100004000".to_string()),
- symbol_addr: None,
- image_addr: None, // No image_addr on frame
- image_uuid: None,
- module: None,
- function: None,
- filename: None,
- lineno: None,
- colno: None,
- meta: CommonFrameMetadata::default(),
- };
-
- let debug_images = vec![AppleDebugImage {
- debug_id: "range-match".to_string(),
- image_addr: "0x100000000".to_string(),
- image_vmaddr: None,
- image_size: Some(0x10000),
- code_file: None,
- image_type: None,
- arch: None,
- }];
-
- let result = frame.find_debug_image(0x100004000, &debug_images).unwrap();
- assert_eq!(result.debug_id, "range-match");
- }
-
- #[test]
- fn test_find_debug_image_no_match() {
- let frame = RawAppleFrame {
- instruction_addr: Some("0x300000000".to_string()),
- symbol_addr: None,
- image_addr: None,
- image_uuid: None,
- module: None,
- function: None,
- filename: None,
- lineno: None,
- colno: None,
- meta: CommonFrameMetadata::default(),
- };
-
- let debug_images = vec![AppleDebugImage {
- debug_id: "some-uuid".to_string(),
- image_addr: "0x100000000".to_string(),
- image_vmaddr: None,
- image_size: Some(0x10000),
- code_file: None,
- image_type: None,
- arch: None,
- }];
-
- let result = frame.find_debug_image(0x300000000, &debug_images);
- assert!(matches!(result, Err(AppleError::NoMatchingDebugImage)));
- }
-
#[sqlx::test(migrations = "./tests/test_migrations")]
async fn test_apple_symbolication(db: sqlx::PgPool) {
use chrono::Utc;
@@ -787,7 +531,7 @@ mod test {
meta: CommonFrameMetadata::default(),
};
- let debug_images = vec![AppleDebugImage {
+ let debug_images = vec![DebugImage {
debug_id: chunk_id.clone(),
image_addr: "0x100000000".to_string(),
image_vmaddr: Some("0x100000000".to_string()),
@@ -943,7 +687,7 @@ mod test {
meta: CommonFrameMetadata::default(),
};
- let debug_images = vec![AppleDebugImage {
+ let debug_images = vec![DebugImage {
debug_id: chunk_id.clone(),
image_addr: "0x100000000".to_string(),
image_vmaddr: Some("0x100000000".to_string()),
@@ -1020,8 +764,8 @@ mod test {
}
}
- fn image_at(debug_id: &str, image_addr: u64) -> AppleDebugImage {
- AppleDebugImage {
+ fn image_at(debug_id: &str, image_addr: u64) -> DebugImage {
+ DebugImage {
debug_id: debug_id.to_string(),
image_addr: format!("0x{image_addr:x}"),
image_vmaddr: None,
diff --git a/rust/cymbal/src/langs/mod.rs b/rust/cymbal/src/langs/mod.rs
index 4d4e1fe59619..c28cf58b3409 100644
--- a/rust/cymbal/src/langs/mod.rs
+++ b/rust/cymbal/src/langs/mod.rs
@@ -7,6 +7,7 @@ pub mod go;
pub mod hermes;
pub mod java;
pub mod js;
+pub mod native;
pub mod node;
pub mod php;
pub mod python;
diff --git a/rust/cymbal/src/langs/native.rs b/rust/cymbal/src/langs/native.rs
new file mode 100644
index 000000000000..d359854fc4ac
--- /dev/null
+++ b/rust/cymbal/src/langs/native.rs
@@ -0,0 +1,182 @@
+use serde::{Deserialize, Serialize};
+
+use crate::error::NativeError;
+
+/// A loaded module (binary image) reported by an SDK alongside native stack
+/// frames, used to map absolute instruction addresses onto an uploaded debug
+/// symbol set. Sent as the event-level `$debug_images` property.
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct DebugImage {
+ pub debug_id: String,
+ pub image_addr: String,
+ #[serde(default)]
+ pub image_vmaddr: Option<String>,
+ #[serde(default)]
+ pub image_size: Option<u64>,
+ #[serde(default)]
+ pub code_file: Option<String>,
+ #[serde(default, rename = "type")]
+ pub image_type: Option<String>,
+ #[serde(default)]
+ pub arch: Option<String>,
+}
+
+pub fn parse_hex_address(s: &str) -> Result<u64, NativeError> {
+ let s = s.trim().trim_start_matches("0x").trim_start_matches("0X");
+ u64::from_str_radix(s, 16).map_err(|_| NativeError::InvalidAddress(s.to_string()))
+}
+
+/// Find the debug image containing `instruction_addr`, preferring an exact
+/// match on the frame's own `image_addr` and falling back to a range check
+/// against each image's `[image_addr, image_addr + image_size)`.
+pub fn find_debug_image<'a>(
+ instruction_addr: u64,
+ frame_image_addr: Option<&str>,
+ debug_images: &'a [DebugImage],
+) -> Result<&'a DebugImage, NativeError> {
+ let frame_image_addr = frame_image_addr.and_then(|addr| parse_hex_address(addr).ok());
+
+ for image in debug_images {
+ let image_base = parse_hex_address(&image.image_addr).ok();
+
+ if let (Some(frame_addr), Some(base)) = (frame_image_addr, image_base) {
+ if frame_addr == base {
+ return Ok(image);
+ }
+ }
+
+ if let (Some(base), Some(size)) = (image_base, image.image_size) {
+ if instruction_addr >= base && instruction_addr < base.saturating_add(size) {
+ return Ok(image);
+ }
+ }
+ }
+
+ Err(NativeError::NoMatchingDebugImage)
+}
+
+/// Offset of `instruction_addr` from the image's runtime load address. The
+/// symcache contains addresses relative to the binary's VM base, so the load
+/// offset is all that's needed for lookup.
+pub fn calculate_relative_addr(
+ instruction_addr: u64,
+ debug_image: &DebugImage,
+) -> Result<u64, NativeError> {
+ let image_addr = parse_hex_address(&debug_image.image_addr)?;
+
+ if instruction_addr < image_addr {
+ return Err(NativeError::InvalidAddress(format!(
+ "instruction_addr 0x{:x} < image_addr 0x{:x}",
+ instruction_addr, image_addr
+ )));
+ }
+
+ Ok(instruction_addr - image_addr)
+}
+
+/// The launch-invariant identity of a frame: the debug image it belongs to and
+/// the offset within it. Absolute instruction addresses are ASLR-slid per
+/// process launch, so anything that needs a stable per-build frame identity
+/// (e.g. frame-record caching) should prefer this over the raw address.
+pub fn launch_invariant_addr(
+ instruction_addr: Option<&str>,
+ frame_image_addr: Option<&str>,
+ debug_images: &[DebugImage],
+) -> Option<(String, u64)> {
+ let instruction_addr = parse_hex_address(instruction_addr?).ok()?;
+ let debug_image = find_debug_image(instruction_addr, frame_image_addr, debug_images).ok()?;
+ let relative_addr = calculate_relative_addr(instruction_addr, debug_image).ok()?;
+ Some((debug_image.debug_id.clone(), relative_addr))
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ fn image_at(debug_id: &str, image_addr: u64) -> DebugImage {
+ DebugImage {
+ debug_id: debug_id.to_string(),
+ image_addr: format!("0x{image_addr:x}"),
+ image_vmaddr: None,
+ image_size: Some(0x10000),
+ code_file: None,
+ image_type: None,
+ arch: None,
+ }
+ }
+
+ #[test]
+ fn test_parse_hex_address_with_0x_prefix() {
+ assert_eq!(parse_hex_address("0x100000000").unwrap(), 0x100000000);
+ assert_eq!(parse_hex_address("0X100000000").unwrap(), 0x100000000);
+ }
+
+ #[test]
+ fn test_parse_hex_address_without_prefix() {
+ assert_eq!(parse_hex_address("100000000").unwrap(), 0x100000000);
+ assert_eq!(parse_hex_address("deadbeef").unwrap(), 0xdeadbeef);
+ }
+
+ #[test]
+ fn test_parse_hex_address_with_whitespace() {
+ assert_eq!(parse_hex_address(" 0x100000000 ").unwrap(), 0x100000000);
+ }
+
+ #[test]
+ fn test_parse_hex_address_invalid() {
+ assert!(parse_hex_address("not_hex").is_err());
+ assert!(parse_hex_address("0xGGGG").is_err());
+ }
+
+ #[test]
+ fn test_calculate_relative_addr() {
+ let result = calculate_relative_addr(0x100004000, &image_at("test-uuid", 0x100000000));
+ assert_eq!(result.unwrap(), 0x4000);
+ }
+
+ #[test]
+ fn test_calculate_relative_addr_below_image_base() {
+ let result = calculate_relative_addr(0x100, &image_at("test-uuid", 0x100000000));
+ assert!(matches!(result, Err(NativeError::InvalidAddress(_))));
+ }
+
+ #[test]
+ fn test_find_debug_image_by_image_addr() {
+ let debug_images = vec![
+ image_at("other-uuid", 0x200000000),
+ image_at("matching-uuid", 0x100000000),
+ ];
+
+ let result = find_debug_image(0x100004000, Some("0x100000000"), &debug_images).unwrap();
+ assert_eq!(result.debug_id, "matching-uuid");
+ }
+
+ #[test]
+ fn test_find_debug_image_by_address_range() {
+ let debug_images = vec![image_at("range-match", 0x100000000)];
+
+ let result = find_debug_image(0x100004000, None, &debug_images).unwrap();
+ assert_eq!(result.debug_id, "range-match");
+ }
+
+ #[test]
+ fn test_find_debug_image_no_match() {
+ let debug_images = vec![image_at("some-uuid", 0x100000000)];
+
+ let result = find_debug_image(0x300000000, None, &debug_images);
+ assert!(matches!(result, Err(NativeError::NoMatchingDebugImage)));
+ }
+
+ #[test]
+ fn test_launch_invariant_addr() {
+ let images = [image_at("uuid-build-1", 0x104f00000)];
+ let result = launch_invariant_addr(Some("0x104f04000"), Some("0x104f00000"), &images);
+ assert_eq!(result, Some(("uuid-build-1".to_string(), 0x4000)));
+ }
+
+ #[test]
+ fn test_launch_invariant_addr_without_matching_image() {
+ let result = launch_invariant_addr(Some("0x104f04000"), None, &[]);
+ assert_eq!(result, None);
+ }
+}
diff --git a/rust/cymbal/src/stages/resolution/frame.rs b/rust/cymbal/src/stages/resolution/frame.rs
index 7799de5403da..70a4b814c130 100644
--- a/rust/cymbal/src/stages/resolution/frame.rs
+++ b/rust/cymbal/src/stages/resolution/frame.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use crate::{
error::UnhandledError,
frames::{Frame, RawFrame},
- langs::apple::AppleDebugImage,
+ langs::native::DebugImage,
metric_consts::FRAME_RESOLVER_OPERATOR,
stages::{pipeline::HandledError, resolution::ResolutionStage},
types::{
@@ -21,7 +21,7 @@ impl FrameResolver {
pub async fn resolve_exception_list_frames(
team_id: i32,
list: ExceptionList,
- debug_images: Arc<Vec<AppleDebugImage>>,
+ debug_images: Arc<Vec<DebugImage>>,
ctx: ResolutionStage,
) -> Result<ExceptionList, UnhandledError> {
let res = Batch::from(list.0)
@@ -42,7 +42,7 @@ impl FrameResolver {
pub async fn resolve_exception_frames(
team_id: i32,
mut exc: Exception,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
ctx: ResolutionStage,
) -> Result<Exception, UnhandledError> {
exc.stack = match exc.stack {
@@ -72,7 +72,7 @@ impl FrameResolver {
pub async fn resolve_frame(
team_id: i32,
frame: &RawFrame,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
ctx: ResolutionStage,
) -> Result<Vec<Frame>, UnhandledError> {
let _permit = ctx.acquire_symbol_resolution_permit().await?;
diff --git a/rust/cymbal/src/stages/resolution/symbol/local.rs b/rust/cymbal/src/stages/resolution/symbol/local.rs
index 125251fed155..385d47bccfae 100644
--- a/rust/cymbal/src/stages/resolution/symbol/local.rs
+++ b/rust/cymbal/src/stages/resolution/symbol/local.rs
@@ -21,7 +21,7 @@ use crate::{
releases::ReleaseRecord,
Frame, RawFrame,
},
- langs::apple::AppleDebugImage,
+ langs::native::DebugImage,
metric_consts::{
FRAME_CACHE_HITS, FRAME_CACHE_MISSES, FRAME_DB_HITS, FRAME_DB_MISSES,
SUSPICIOUS_FRAMES_DETECTED,
@@ -104,7 +104,7 @@ impl LocalSymbolResolver {
&self,
team_id: i32,
frame: &RawFrame,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
if frame.is_suspicious() {
metrics::counter!(SUSPICIOUS_FRAMES_DETECTED, "frame_type" => "raw").increment(1);
@@ -133,7 +133,7 @@ impl LocalSymbolResolver {
&self,
frame: &RawFrame,
raw_id: RawFrameId,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<ErrorTrackingStackFrame>, UnhandledError> {
let loaded =
ErrorTrackingStackFrame::load_all(&self.pool, &raw_id, self.ttl_policy).await?;
@@ -198,7 +198,7 @@ impl SymbolResolver for LocalSymbolResolver {
&self,
team_id: TeamId,
frame: &RawFrame,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
self.resolve(team_id, frame, debug_images).await
}
diff --git a/rust/cymbal/src/stages/resolution/symbol/mod.rs b/rust/cymbal/src/stages/resolution/symbol/mod.rs
index 031cbf011dc7..f2af32209383 100644
--- a/rust/cymbal/src/stages/resolution/symbol/mod.rs
+++ b/rust/cymbal/src/stages/resolution/symbol/mod.rs
@@ -3,7 +3,7 @@ use async_trait::async_trait;
use crate::{
error::{ProguardError, ResolveError, UnhandledError},
frames::{Frame, RawFrame},
- langs::apple::AppleDebugImage,
+ langs::native::DebugImage,
metric_consts::JAVA_EXCEPTION_REMAP_FAILED,
symbol_store::{chunk_id::OrChunkId, proguard::ProguardRef},
types::{operator::TeamId, Exception},
@@ -17,7 +17,7 @@ pub trait SymbolResolver: Send + Sync + 'static {
&self,
team_id: TeamId,
frame: &RawFrame,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError>;
async fn resolve_java_class(
diff --git a/rust/cymbal/src/symbol_store/apple.rs b/rust/cymbal/src/symbol_store/apple.rs
index 50971c90c72c..c22ede96e7b0 100644
--- a/rust/cymbal/src/symbol_store/apple.rs
+++ b/rust/cymbal/src/symbol_store/apple.rs
@@ -1,47 +1,16 @@
-use std::collections::HashMap;
use std::fmt::Display;
-use std::io::{Cursor, Read};
use async_trait::async_trait;
use bytes::Bytes;
-use serde::Deserialize;
-use symbolic::debuginfo::Archive;
-use symbolic::demangle::{Demangle, DemangleOptions};
-use symbolic::symcache::{SymCache, SymCacheConverter};
-use zip::ZipArchive;
use posthog_symbol_data::{read_symbol_data_with_byte_count, AppleDsym};
use crate::{
error::{AppleError, ResolveError, UnhandledError},
metric_consts::SYMBOL_SET_DECOMPRESSED_BYTES,
- symbol_store::{caching::Countable, Fetcher, Parser},
+ symbol_store::{native::ParsedNativeSymbols, Fetcher, Parser},
};
-/// Manifest format for source files bundled in the dSYM ZIP under `__source/`
-#[derive(Deserialize)]
-struct SourceManifest {
- #[allow(dead_code)]
- version: u32,
- /// Maps absolute DWARF source path → ZIP-relative path
- files: HashMap<String, String>,
-}
-
-pub struct ParsedAppleSymbols {
- symcache_data: Vec<u8>,
- /// Source file contents indexed by DWARF absolute path.
- /// None if the bundle doesn't contain source files.
- sources: Option<HashMap<String, String>>,
- /// Decompressed byte count from the symbol_data container, used for cache memory accounting.
- decompressed_bytes: usize,
-}
-
-impl Countable for ParsedAppleSymbols {
- fn byte_count(&self) -> usize {
- self.decompressed_bytes
- }
-}
-
pub struct AppleProvider {}
#[derive(Debug, Clone)]
@@ -61,14 +30,14 @@ impl Fetcher for AppleProvider {
#[async_trait]
impl Parser for AppleProvider {
type Source = Bytes;
- type Set = ParsedAppleSymbols;
+ type Set = ParsedNativeSymbols;
type Err = ResolveError;
- async fn parse(&self, source: Self::Source) -> Result<ParsedAppleSymbols, ResolveError> {
+ async fn parse(&self, source: Self::Source) -> Result<ParsedNativeSymbols, ResolveError> {
// dSYM parsing is the heaviest CPU work in the system: zstd decompress, ZIP
// expansion, DWARF parse, and symcache conversion. Always offload from the tokio
// runtime.
- tokio::task::spawn_blocking(move || -> Result<ParsedAppleSymbols, ResolveError> {
+ tokio::task::spawn_blocking(move || -> Result<ParsedNativeSymbols, ResolveError> {
// Try to unwrap symbol_data container first (new format),
// fall back to raw ZIP for backward compatibility with existing uploads.
// TODO(2026-09-24): Remove raw ZIP fallback once all old uploads have expired.
@@ -82,248 +51,16 @@ impl Parser for AppleProvider {
};
metrics::histogram!(SYMBOL_SET_DECOMPRESSED_BYTES, "kind" => "apple")
.record(decompressed_bytes as f64);
- ParsedAppleSymbols::from_dsym_zip(zip_data, decompressed_bytes)
+ // Map shared native parse errors onto AppleError so stored failure
+ // reasons for apple symbol sets keep their existing shape.
+ ParsedNativeSymbols::from_zip_data(zip_data, decompressed_bytes)
+ .map_err(|e| AppleError::from(e).into())
})
.await
.map_err(|e| UnhandledError::Other(format!("apple dSYM parse task failed: {e}")))?
}
}
-impl ParsedAppleSymbols {
- pub fn from_dsym_zip(
- zip_data: Vec<u8>,
- decompressed_bytes: usize,
- ) -> Result<Self, ResolveError> {
- let cursor = Cursor::new(zip_data);
- let mut archive =
- ZipArchive::new(cursor).map_err(|e| AppleError::ParseError(e.to_string()))?;
-
- let dwarf_data = Self::extract_dwarf_from_zip(&mut archive)?;
-
- let symcache_data = Self::convert_to_symcache(&dwarf_data)?;
-
- // Try to load source files from the bundle (graceful — old bundles without source still work)
- let sources = Self::extract_sources_from_zip(&mut archive);
-
- Ok(Self {
- symcache_data,
- sources,
- decompressed_bytes,
- })
- }
-
- /// Extract source files from a dSYM ZIP that contains a `__source/manifest.json`.
- /// Returns None if no source manifest is found (backward compatible).
- fn extract_sources_from_zip(
- archive: &mut ZipArchive<Cursor<Vec<u8>>>,
- ) -> Option<HashMap<String, String>> {
- // Read and parse manifest
- let manifest: SourceManifest = {
- let mut manifest_file = archive.by_name("__source/manifest.json").ok()?;
- let mut manifest_data = Vec::new();
- manifest_file.read_to_end(&mut manifest_data).ok()?;
- serde_json::from_slice(&manifest_data).ok()?
- };
-
- let mut sources = HashMap::new();
-
- for (dwarf_path, zip_path) in &manifest.files {
- if let Ok(mut file) = archive.by_name(zip_path) {
- let mut content = String::new();
- if file.read_to_string(&mut content).is_ok() {
- sources.insert(dwarf_path.clone(), content);
- }
- }
- }
-
- if sources.is_empty() {
- None
- } else {
- Some(sources)
- }
- }
-
- /// Get the source content for a given DWARF absolute path.
- ///
- /// Uses a two-stage lookup to handle inlined cross-file frames under Swift WMO:
- ///
- /// 1. **Exact match** – fast path, works for physical-function frames where the
- /// CU's own path matches the manifest key verbatim.
- ///
- /// 2. **Basename fallback** – when the embedding CU's line table records a
- /// relative `include_directories` entry (e.g. `comp_dir="/"`,
- /// `dir="PostHogExample"`) symcache resolves `full_path` as
- /// `"/PostHogExample/Foo.swift"`, but the CLI built the manifest from the
- /// callee CU's absolute path `"/Users/…/PostHogExample/Foo.swift"`.
- /// The basename fallback matches by filename and is only applied when
- /// there is exactly one candidate (no ambiguity).
- pub fn get_source(&self, dwarf_path: &str) -> Option<&str> {
- let sources = self.sources.as_ref()?;
-
- // 1. Exact match (fast path, works for physical-function frames)
- if let Some(text) = sources.get(dwarf_path) {
- return Some(text.as_str());
- }
-
- // 2. Basename fallback for inlined cross-file frames where the embedding
- // CU's line table records a relative path but the manifest was built
- // from the callee CU's absolute path (Swift WMO common case).
- let basename = std::path::Path::new(dwarf_path).file_name()?.to_str()?;
- let mut candidates = sources.iter().filter(|(k, _)| k.ends_with(basename));
- let first = candidates.next();
- // Only use the fallback if there is exactly one candidate (no ambiguity).
- if first.is_some() && candidates.next().is_none() {
- return first.map(|(_, v)| v.as_str());
- }
-
- None
- }
-
- fn extract_dwarf_from_zip(
- archive: &mut ZipArchive<Cursor<Vec<u8>>>,
- ) -> Result<Vec<u8>, ResolveError> {
- // New format: single DWARF binary stored as "dwarf" at root level
- if let Ok(mut file) = archive.by_name("dwarf") {
- let mut data = Vec::new();
- file.read_to_end(&mut data)
- .map_err(|e| AppleError::ParseError(e.to_string()))?;
- return Ok(data);
- }
-
- // Old format: full dSYM bundle with Contents/Resources/DWARF/<name>
- // TODO(2026-09-24): Remove this fallback once all old uploads have expired.
- for i in 0..archive.len() {
- let mut file = archive
- .by_index(i)
- .map_err(|e| AppleError::ParseError(e.to_string()))?;
-
- let name = file.name().to_string();
-
- if name.contains("/Contents/Resources/DWARF/") && !name.ends_with('/') {
- let mut data = Vec::new();
- file.read_to_end(&mut data)
- .map_err(|e| AppleError::ParseError(e.to_string()))?;
- return Ok(data);
- }
- }
-
- Err(AppleError::ParseError("No DWARF file found in dSYM bundle".to_string()).into())
- }
-
- fn convert_to_symcache(dwarf_data: &[u8]) -> Result<Vec<u8>, ResolveError> {
- let archive =
- Archive::parse(dwarf_data).map_err(|e| AppleError::ParseError(e.to_string()))?;
-
- // For fat (universal) Mach-O binaries the archive contains multiple slices.
- // Crash reports from iOS/iPadOS devices are always arm64, so prefer that
- // architecture when building the symcache. Falling back to the first slice
- // (the old behaviour) could pick x86_64 — the simulator architecture that
- // comes first in fat binaries built by Xcode — producing completely wrong
- // symbol names and line numbers for device crashes.
- let obj = {
- let mut preferred: Option<_> = None;
- let mut fallback: Option<_> = None;
- for result in archive.objects() {
- match result {
- Ok(o) => {
- let arch_name = o.arch().name();
- tracing::debug!("[symcache] candidate arch: {}", arch_name);
- if arch_name.starts_with("arm64") {
- preferred = Some(Ok(o));
- break; // arm64 found — no need to look further
- } else if fallback.is_none() {
- fallback = Some(Ok(o));
- }
- }
- Err(e) => {
- if fallback.is_none() {
- fallback = Some(Err(e));
- }
- }
- }
- }
- preferred
- .or(fallback)
- .ok_or_else(|| AppleError::ParseError("No objects in archive".to_string()))?
- .map_err(|e| AppleError::ParseError(e.to_string()))?
- };
-
- let mut converter = SymCacheConverter::new();
- converter
- .process_object(&obj)
- .map_err(|e| AppleError::ParseError(e.to_string()))?;
-
- let mut buffer = Vec::new();
- converter
- .serialize(&mut Cursor::new(&mut buffer))
- .map_err(|e| AppleError::ParseError(e.to_string()))?;
-
- Ok(buffer)
- }
-
- /// Look up all logical frames for an address, including inlined frames.
- ///
- /// The symcache iterator returns frames innermost-first:
- /// - index 0 is the deepest inlined function (the actual code running at `addr`)
- /// - last index is the outermost physical function that contains the address
- ///
- /// Returns an empty `Vec` when the address is not found in the symcache.
- pub fn lookup(&self, addr: u64) -> Result<Vec<SymbolInfo>, ResolveError> {
- let symcache = SymCache::parse(&self.symcache_data)
- .map_err(|e| AppleError::ParseError(e.to_string()))?;
-
- let results = symcache
- .lookup(addr)
- .map(|result| {
- let raw_name = result.function().name_for_demangling();
-
- // Short name (no params/return type) for display as resolved_name
- let display_name = raw_name
- .demangle(DemangleOptions::name_only())
- .unwrap_or_else(|| raw_name.to_string());
-
- // Full demangled name for mangled_name (includes params and return type)
- let full_name = raw_name
- .demangle(DemangleOptions::complete())
- .unwrap_or_else(|| raw_name.to_string());
-
- let full_path = result.file().map(|f| f.full_path());
- let filename = full_path.as_ref().and_then(|path| extract_filename(path));
-
- SymbolInfo {
- display_name,
- full_name,
- filename,
- full_path,
- line: result.line(),
- }
- })
- .collect();
-
- Ok(results)
- }
-}
-
-fn extract_filename(full_path: &str) -> Option<String> {
- use std::path::Path;
- Path::new(full_path)
- .file_name()
- .and_then(|s| s.to_str())
- .map(|s| s.to_string())
-}
-
-#[derive(Debug, Clone)]
-pub struct SymbolInfo {
- /// Short demangled name (no params/return type) for display
- pub display_name: String,
- /// Full demangled name (with params and return type)
- pub full_name: String,
- pub filename: Option<String>,
- /// The full absolute path from DWARF debug info, used for source lookup
- pub full_path: Option<String>,
- pub line: u32,
-}
-
impl Display for AppleRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "AppleRef")
diff --git a/rust/cymbal/src/symbol_store/mod.rs b/rust/cymbal/src/symbol_store/mod.rs
index a24a85d6b80f..8280be7bdadf 100644
--- a/rust/cymbal/src/symbol_store/mod.rs
+++ b/rust/cymbal/src/symbol_store/mod.rs
@@ -10,8 +10,9 @@ use crate::{
error::ResolveError,
langs::hermes::HermesRef,
symbol_store::{
- apple::{AppleRef, ParsedAppleSymbols},
+ apple::AppleRef,
hermesmap::ParsedHermesMap,
+ native::ParsedNativeSymbols,
proguard::{FetchedMapping, ProguardRef},
},
};
@@ -22,6 +23,7 @@ pub mod chunk_id;
pub mod concurrency;
pub mod dart_minified_names;
pub mod hermesmap;
+pub mod native;
pub mod proguard;
pub mod saving;
pub mod sourcemap;
@@ -76,7 +78,7 @@ pub struct Catalog {
Box<dyn Provider<Ref = OrChunkId<ProguardRef>, Set = FetchedMapping, Err = ResolveError>>,
// Apple dSYM provider
pub apple:
- Box<dyn Provider<Ref = OrChunkId<AppleRef>, Set = ParsedAppleSymbols, Err = ResolveError>>,
+ Box<dyn Provider<Ref = OrChunkId<AppleRef>, Set = ParsedNativeSymbols, Err = ResolveError>>,
}
impl Catalog {
@@ -84,7 +86,7 @@ impl Catalog {
smp: impl Provider<Ref = OrChunkId<Url>, Set = OwnedSourceMapCache, Err = ResolveError>,
hmp: impl Provider<Ref = OrChunkId<HermesRef>, Set = ParsedHermesMap, Err = ResolveError>,
pg: impl Provider<Ref = OrChunkId<ProguardRef>, Set = FetchedMapping, Err = ResolveError>,
- apple: impl Provider<Ref = OrChunkId<AppleRef>, Set = ParsedAppleSymbols, Err = ResolveError>,
+ apple: impl Provider<Ref = OrChunkId<AppleRef>, Set = ParsedNativeSymbols, Err = ResolveError>,
) -> Self {
Self {
smp: Box::new(smp),
@@ -137,12 +139,12 @@ impl SymbolCatalog<OrChunkId<ProguardRef>, FetchedMapping> for Catalog {
}
#[async_trait]
-impl SymbolCatalog<OrChunkId<AppleRef>, ParsedAppleSymbols> for Catalog {
+impl SymbolCatalog<OrChunkId<AppleRef>, ParsedNativeSymbols> for Catalog {
async fn lookup(
&self,
team_id: i32,
r: OrChunkId<AppleRef>,
- ) -> Result<Arc<ParsedAppleSymbols>, ResolveError> {
+ ) -> Result<Arc<ParsedNativeSymbols>, ResolveError> {
self.apple.lookup(team_id, r).await
}
}
diff --git a/rust/cymbal/src/symbol_store/native.rs b/rust/cymbal/src/symbol_store/native.rs
new file mode 100644
index 000000000000..7dffbafd6f78
--- /dev/null
+++ b/rust/cymbal/src/symbol_store/native.rs
@@ -0,0 +1,275 @@
+use std::collections::HashMap;
+use std::io::{Cursor, Read};
+
+use serde::Deserialize;
+use symbolic::debuginfo::Archive;
+use symbolic::demangle::{Demangle, DemangleOptions};
+use symbolic::symcache::{SymCache, SymCacheConverter};
+use zip::ZipArchive;
+
+use crate::{error::NativeError, symbol_store::caching::Countable};
+
+/// Manifest format for source files bundled in the symbol ZIP under `__source/`
+#[derive(Deserialize)]
+struct SourceManifest {
+ #[allow(dead_code)]
+ version: u32,
+ /// Maps absolute DWARF source path → ZIP-relative path
+ files: HashMap<String, String>,
+}
+
+/// Symbols parsed from an uploaded native debug-info bundle (dSYM, ELF, ...),
+/// converted to a symcache for address lookup. The wire format is a ZIP with
+/// the DWARF-bearing binary at the root plus an optional `__source/` bundle.
+pub struct ParsedNativeSymbols {
+ symcache_data: Vec<u8>,
+ /// Source file contents indexed by DWARF absolute path.
+ /// None if the bundle doesn't contain source files.
+ sources: Option<HashMap<String, String>>,
+ /// Decompressed byte count from the symbol_data container, used for cache memory accounting.
+ decompressed_bytes: usize,
+}
+
+impl Countable for ParsedNativeSymbols {
+ fn byte_count(&self) -> usize {
+ self.decompressed_bytes
+ }
+}
+
+impl ParsedNativeSymbols {
+ pub fn from_zip_data(
+ zip_data: Vec<u8>,
+ decompressed_bytes: usize,
+ ) -> Result<Self, NativeError> {
+ let cursor = Cursor::new(zip_data);
+ let mut archive =
+ ZipArchive::new(cursor).map_err(|e| NativeError::ParseError(e.to_string()))?;
+
+ let dwarf_data = Self::extract_dwarf_from_zip(&mut archive)?;
+
+ let symcache_data = Self::convert_to_symcache(&dwarf_data)?;
+
+ // Try to load source files from the bundle (graceful — old bundles without source still work)
+ let sources = Self::extract_sources_from_zip(&mut archive);
+
+ Ok(Self {
+ symcache_data,
+ sources,
+ decompressed_bytes,
+ })
+ }
+
+ /// Extract source files from a symbol ZIP that contains a `__source/manifest.json`.
+ /// Returns None if no source manifest is found (backward compatible).
+ fn extract_sources_from_zip(
+ archive: &mut ZipArchive<Cursor<Vec<u8>>>,
+ ) -> Option<HashMap<String, String>> {
+ // Read and parse manifest
+ let manifest: SourceManifest = {
+ let mut manifest_file = archive.by_name("__source/manifest.json").ok()?;
+ let mut manifest_data = Vec::new();
+ manifest_file.read_to_end(&mut manifest_data).ok()?;
+ serde_json::from_slice(&manifest_data).ok()?
+ };
+
+ let mut sources = HashMap::new();
+
+ for (dwarf_path, zip_path) in &manifest.files {
+ if let Ok(mut file) = archive.by_name(zip_path) {
+ let mut content = String::new();
+ if file.read_to_string(&mut content).is_ok() {
+ sources.insert(dwarf_path.clone(), content);
+ }
+ }
+ }
+
+ if sources.is_empty() {
+ None
+ } else {
+ Some(sources)
+ }
+ }
+
+ /// Get the source content for a given DWARF absolute path.
+ ///
+ /// Uses a two-stage lookup to handle inlined cross-file frames under Swift WMO:
+ ///
+ /// 1. **Exact match** – fast path, works for physical-function frames where the
+ /// CU's own path matches the manifest key verbatim.
+ ///
+ /// 2. **Basename fallback** – when the embedding CU's line table records a
+ /// relative `include_directories` entry (e.g. `comp_dir="/"`,
+ /// `dir="PostHogExample"`) symcache resolves `full_path` as
+ /// `"/PostHogExample/Foo.swift"`, but the CLI built the manifest from the
+ /// callee CU's absolute path `"/Users/…/PostHogExample/Foo.swift"`.
+ /// The basename fallback matches by filename and is only applied when
+ /// there is exactly one candidate (no ambiguity).
+ pub fn get_source(&self, dwarf_path: &str) -> Option<&str> {
+ let sources = self.sources.as_ref()?;
+
+ // 1. Exact match (fast path, works for physical-function frames)
+ if let Some(text) = sources.get(dwarf_path) {
+ return Some(text.as_str());
+ }
+
+ // 2. Basename fallback for inlined cross-file frames where the embedding
+ // CU's line table records a relative path but the manifest was built
+ // from the callee CU's absolute path (Swift WMO common case).
+ let basename = std::path::Path::new(dwarf_path).file_name()?.to_str()?;
+ let mut candidates = sources.iter().filter(|(k, _)| k.ends_with(basename));
+ let first = candidates.next();
+ // Only use the fallback if there is exactly one candidate (no ambiguity).
+ if first.is_some() && candidates.next().is_none() {
+ return first.map(|(_, v)| v.as_str());
+ }
+
+ None
+ }
+
+ fn extract_dwarf_from_zip(
+ archive: &mut ZipArchive<Cursor<Vec<u8>>>,
+ ) -> Result<Vec<u8>, NativeError> {
+ // New format: single DWARF binary stored as "dwarf" at root level
+ if let Ok(mut file) = archive.by_name("dwarf") {
+ let mut data = Vec::new();
+ file.read_to_end(&mut data)
+ .map_err(|e| NativeError::ParseError(e.to_string()))?;
+ return Ok(data);
+ }
+
+ // Old format: full dSYM bundle with Contents/Resources/DWARF/<name>
+ // TODO(2026-09-24): Remove this fallback once all old uploads have expired.
+ for i in 0..archive.len() {
+ let mut file = archive
+ .by_index(i)
+ .map_err(|e| NativeError::ParseError(e.to_string()))?;
+
+ let name = file.name().to_string();
+
+ if name.contains("/Contents/Resources/DWARF/") && !name.ends_with('/') {
+ let mut data = Vec::new();
+ file.read_to_end(&mut data)
+ .map_err(|e| NativeError::ParseError(e.to_string()))?;
+ return Ok(data);
+ }
+ }
+
+ Err(NativeError::ParseError(
+ "No DWARF file found in symbol bundle".to_string(),
+ ))
+ }
+
+ fn convert_to_symcache(dwarf_data: &[u8]) -> Result<Vec<u8>, NativeError> {
+ let archive =
+ Archive::parse(dwarf_data).map_err(|e| NativeError::ParseError(e.to_string()))?;
+
+ // For fat (universal) Mach-O binaries the archive contains multiple slices.
+ // Crash reports from iOS/iPadOS devices are always arm64, so prefer that
+ // architecture when building the symcache. Falling back to the first slice
+ // (the old behaviour) could pick x86_64 — the simulator architecture that
+ // comes first in fat binaries built by Xcode — producing completely wrong
+ // symbol names and line numbers for device crashes. ELF and PE archives
+ // contain a single object, so the preference is a no-op for them.
+ let obj = {
+ let mut preferred: Option<_> = None;
+ let mut fallback: Option<_> = None;
+ for result in archive.objects() {
+ match result {
+ Ok(o) => {
+ let arch_name = o.arch().name();
+ tracing::debug!("[symcache] candidate arch: {}", arch_name);
+ if arch_name.starts_with("arm64") {
+ preferred = Some(Ok(o));
+ break; // arm64 found — no need to look further
+ } else if fallback.is_none() {
+ fallback = Some(Ok(o));
+ }
+ }
+ Err(e) => {
+ if fallback.is_none() {
+ fallback = Some(Err(e));
+ }
+ }
+ }
+ }
+ preferred
+ .or(fallback)
+ .ok_or_else(|| NativeError::ParseError("No objects in archive".to_string()))?
+ .map_err(|e| NativeError::ParseError(e.to_string()))?
+ };
+
+ let mut converter = SymCacheConverter::new();
+ converter
+ .process_object(&obj)
+ .map_err(|e| NativeError::ParseError(e.to_string()))?;
+
+ let mut buffer = Vec::new();
+ converter
+ .serialize(&mut Cursor::new(&mut buffer))
+ .map_err(|e| NativeError::ParseError(e.to_string()))?;
+
+ Ok(buffer)
+ }
+
+ /// Look up all logical frames for an address, including inlined frames.
+ ///
+ /// The symcache iterator returns frames innermost-first:
+ /// - index 0 is the deepest inlined function (the actual code running at `addr`)
+ /// - last index is the outermost physical function that contains the address
+ ///
+ /// Returns an empty `Vec` when the address is not found in the symcache.
+ pub fn lookup(&self, addr: u64) -> Result<Vec<SymbolInfo>, NativeError> {
+ let symcache = SymCache::parse(&self.symcache_data)
+ .map_err(|e| NativeError::ParseError(e.to_string()))?;
+
+ let results = symcache
+ .lookup(addr)
+ .map(|result| {
+ let raw_name = result.function().name_for_demangling();
+
+ // Short name (no params/return type) for display as resolved_name
+ let display_name = raw_name
+ .demangle(DemangleOptions::name_only())
+ .unwrap_or_else(|| raw_name.to_string());
+
+ // Full demangled name for mangled_name (includes params and return type)
+ let full_name = raw_name
+ .demangle(DemangleOptions::complete())
+ .unwrap_or_else(|| raw_name.to_string());
+
+ let full_path = result.file().map(|f| f.full_path());
+ let filename = full_path.as_ref().and_then(|path| extract_filename(path));
+
+ SymbolInfo {
+ display_name,
+ full_name,
+ filename,
+ full_path,
+ line: result.line(),
+ }
+ })
+ .collect();
+
+ Ok(results)
+ }
+}
+
+fn extract_filename(full_path: &str) -> Option<String> {
+ use std::path::Path;
+ Path::new(full_path)
+ .file_name()
+ .and_then(|s| s.to_str())
+ .map(|s| s.to_string())
+}
+
+#[derive(Debug, Clone)]
+pub struct SymbolInfo {
+ /// Short demangled name (no params/return type) for display
+ pub display_name: String,
+ /// Full demangled name (with params and return type)
+ pub full_name: String,
+ pub filename: Option<String>,
+ /// The full absolute path from DWARF debug info, used for source lookup
+ pub full_path: Option<String>,
+ pub line: u32,
+}
diff --git a/rust/cymbal/src/types/exception_properties.rs b/rust/cymbal/src/types/exception_properties.rs
index 78e110ac9a0d..ccbf0ec79492 100644
--- a/rust/cymbal/src/types/exception_properties.rs
+++ b/rust/cymbal/src/types/exception_properties.rs
@@ -10,7 +10,7 @@ use crate::{
fingerprinting::FingerprintRecordPart,
frames::releases::ReleaseInfo,
issue_resolution::Issue,
- langs::apple::AppleDebugImage,
+ langs::native::DebugImage,
recursively_sanitize_properties,
types::{event::AnyEvent, ExceptionList, OutputErrProps},
};
@@ -59,7 +59,7 @@ pub struct ExceptionProperties {
default,
skip_serializing_if = "Vec::is_empty"
)]
- pub debug_images: Vec<AppleDebugImage>,
+ pub debug_images: Vec<DebugImage>,
#[serde(flatten)]
pub props: HashMap<String, Value>,
diff --git a/rust/cymbal/src/types/mod.rs b/rust/cymbal/src/types/mod.rs
index 6056dafac5d2..f2d9d1e07ab8 100644
--- a/rust/cymbal/src/types/mod.rs
+++ b/rust/cymbal/src/types/mod.rs
@@ -14,7 +14,7 @@ use crate::fingerprinting::{
use crate::frames::releases::{ReleaseInfo, ReleaseRecord};
use crate::frames::{Frame, RawFrame};
use crate::issue_resolution::Issue;
-use crate::langs::apple::AppleDebugImage;
+use crate::langs::native::DebugImage;
use crate::metric_consts::POSTHOG_SDK_EXCEPTION_RESOLVED;
use crate::tokenizer::CL100K_BPE;
@@ -143,7 +143,7 @@ pub struct RawErrProps {
default,
skip_serializing_if = "Vec::is_empty"
)]
- pub debug_images: Vec<AppleDebugImage>, // Debug images from iOS/macOS crash reports for symbolication
+ pub debug_images: Vec<DebugImage>, // Debug images sent by native SDKs (apple, rust) for symbolication
#[serde(flatten)]
// A catch-all for all the properties we don't "care" about, so when we send back to kafka we don't lose any info
pub other: HashMap<String, Value>,
@@ -498,7 +498,7 @@ impl Stacktrace {
&self,
team_id: i32,
lookup_table: &HashMap<RawFrameId, Vec<Frame>>,
- debug_images: &[AppleDebugImage],
+ debug_images: &[DebugImage],
) -> Option<Self> {
let Stacktrace::Raw { frames: raw_frames } = self else {
return Some(self.clone());
diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rs
index 3440d975bd5f..56334f0b15d9 100644
--- a/rust/cymbal/tests/common/mod.rs
+++ b/rust/cymbal/tests/common/mod.rs
@@ -18,7 +18,7 @@ use std::time::{Duration, Instant};
use async_trait::async_trait;
use cymbal::error::{ResolveError, UnhandledError};
use cymbal::frames::{Frame, RawFrame};
-use cymbal::langs::apple::AppleDebugImage;
+use cymbal::langs::native::DebugImage;
use cymbal::stages::pipeline::ExceptionEventPipelineItem;
use cymbal::stages::resolution::{
remote::{
@@ -412,7 +412,7 @@ impl SymbolResolver for NoopResolver {
&self,
_team_id: TeamId,
_frame: &RawFrame,
- _debug_images: &[AppleDebugImage],
+ _debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
Ok(Vec::new())
}
diff --git a/rust/cymbal/tests/remote_resolution.rs b/rust/cymbal/tests/remote_resolution.rs
index acc6335c20fd..de7904cf672e 100644
--- a/rust/cymbal/tests/remote_resolution.rs
+++ b/rust/cymbal/tests/remote_resolution.rs
@@ -20,7 +20,7 @@ use common::{
use cymbal::error::{ResolveError, UnhandledError};
use cymbal::frames::{Frame, RawFrame};
-use cymbal::langs::apple::AppleDebugImage;
+use cymbal::langs::native::DebugImage;
use cymbal::stages::resolution::symbol::SymbolResolver;
use cymbal::stages::resolution::ResolutionStage;
use cymbal::symbol_store::chunk_id::OrChunkId;
@@ -47,7 +47,7 @@ impl SymbolResolver for CountingResolver {
&self,
_team_id: TeamId,
_frame: &RawFrame,
- _debug_images: &[AppleDebugImage],
+ _debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
self.raw_frame_calls.fetch_add(1, Ordering::SeqCst);
Ok(Vec::new())
@@ -381,7 +381,7 @@ async fn metadata_encodes_apple_debug_images_as_json_field() {
let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
let mut evt = build_event(1);
- evt.debug_images = vec![AppleDebugImage {
+ evt.debug_images = vec![DebugImage {
debug_id: "ABCDEF".to_string(),
image_addr: "0x100000000".to_string(),
image_vmaddr: Some("0x100000000".to_string()),
diff --git a/rust/cymbal/tests/remote_resolution_parity.rs b/rust/cymbal/tests/remote_resolution_parity.rs
index 6959c8c7e9c1..6c893b2430b1 100644
--- a/rust/cymbal/tests/remote_resolution_parity.rs
+++ b/rust/cymbal/tests/remote_resolution_parity.rs
@@ -22,7 +22,7 @@ use async_trait::async_trait;
use common::{build_event, make_ctx};
use cymbal::error::{ResolveError, UnhandledError};
use cymbal::frames::{Frame, RawFrame};
-use cymbal::langs::apple::AppleDebugImage;
+use cymbal::langs::native::DebugImage;
use cymbal::stages::resolution::symbol::SymbolResolver;
use cymbal::stages::resolution::ResolutionStage;
use cymbal::symbol_store::chunk_id::OrChunkId;
@@ -48,7 +48,7 @@ impl SymbolResolver for FakeResolver {
&self,
_team_id: TeamId,
_frame: &RawFrame,
- _debug_images: &[AppleDebugImage],
+ _debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
Ok(Vec::new())
}
diff --git a/rust/cymbal/tests/remote_resolution_subscribe.rs b/rust/cymbal/tests/remote_resolution_subscribe.rs
index 8176588999d8..331d867a2e02 100644
--- a/rust/cymbal/tests/remote_resolution_subscribe.rs
+++ b/rust/cymbal/tests/remote_resolution_subscribe.rs
@@ -17,7 +17,7 @@ use std::time::Duration;
use async_trait::async_trait;
use cymbal::error::{ResolveError, UnhandledError};
use cymbal::frames::{Frame, RawFrame};
-use cymbal::langs::apple::AppleDebugImage;
+use cymbal::langs::native::DebugImage;
use cymbal::stages::resolution::remote::{EndpointPool, RemoteResolutionConfig};
use cymbal::stages::resolution::symbol::SymbolResolver;
use cymbal::symbol_store::chunk_id::OrChunkId;
@@ -37,7 +37,7 @@ impl SymbolResolver for EmptyResolver {
&self,
_team_id: TeamId,
_frame: &RawFrame,
- _debug_images: &[AppleDebugImage],
+ _debug_images: &[DebugImage],
) -> Result<Vec<Frame>, UnhandledError> {
Ok(Vec::new())
}