Skip to content

The only tool you need to know what is happening and how to fix it.

feat: android symbolicator (#225)

narrow-adventure18468be038e6
diff --git a/.github/workflows/benchmark-processor.yml b/.github/workflows/benchmark-processor.yml
index f441775e..bc2e9d3f 100644
--- a/.github/workflows/benchmark-processor.yml
+++ b/.github/workflows/benchmark-processor.yml
@@ -4,7 +4,7 @@ on:
workflow_dispatch:
inputs:
language:
- description: 'Symbolication language: js (5 impls incl. Honeycomb), dart (traceway-dart-mem/disk), ios (honeycomb-ios + traceway-ios-mem/disk), or both (js+dart)'
+ description: 'Symbolication language: js (5 impls incl. Honeycomb), dart (traceway-dart-mem/disk), ios (honeycomb-ios + traceway-ios-mem/disk), android (honeycomb-android + traceway-android-mem/disk), or both (js+dart)'
required: true
default: 'js'
type: choice
@@ -12,6 +12,7 @@ on:
- js
- dart
- ios
+ - android
- both
scenarios:
description: 'Scenarios to run'
@@ -94,7 +95,7 @@ jobs:
./bin/builder --config manifest-traceway.yaml --skip-compilation
cd build-traceway && CGO_ENABLED=1 go build -tags oxc -o otelcol-bench-traceway .
- name: Build honeycomb collector
- if: inputs.language == 'js' || inputs.language == 'both' || inputs.language == 'ios'
+ if: inputs.language == 'js' || inputs.language == 'both' || inputs.language == 'ios' || inputs.language == 'android'
working-directory: benchmarks/processor
run: |
GOBIN=$PWD/bin go install go.opentelemetry.io/collector/cmd/[email protected]
@@ -123,7 +124,7 @@ jobs:
if [ -f build-honeycomb/otelcol-bench-honeycomb ]; then
cp build-honeycomb/otelcol-bench-honeycomb artifacts/
cp "$(find ~/go/pkg/mod/github.com/honeycombio -name 'libsymbolic_cabi.so' -path '*linux_x86_64*' | head -1)" artifacts/
- cp config-honeycomb.yaml config-honeycomb-ios.yaml artifacts/
+ cp config-honeycomb.yaml config-honeycomb-ios.yaml config-honeycomb-android.yaml artifacts/
[ -f ../../testing/symbolication/node-app/dist/app.mjs ] && cp ../../testing/symbolication/node-app/dist/app.mjs ../../testing/symbolication/node-app/dist/app.mjs.map artifacts/ || true
fi
- uses: actions/upload-artifact@v4
@@ -142,6 +143,7 @@ jobs:
js) impls='["honeycomb","traceway-oxc-mem","traceway-oxc-disk","traceway-goja-mem","traceway-goja-disk"]' ;;
dart) impls='["traceway-dart-mem","traceway-dart-disk"]' ;;
ios) impls='["honeycomb-ios","traceway-ios-mem","traceway-ios-disk"]' ;;
+ android) impls='["honeycomb-android","traceway-android-mem","traceway-android-disk"]' ;;
both) impls='["honeycomb","traceway-oxc-mem","traceway-oxc-disk","traceway-goja-mem","traceway-goja-disk","traceway-dart-mem","traceway-dart-disk"]' ;;
*) echo "unknown language ${{ inputs.language }}" >&2; exit 1 ;;
esac
@@ -152,7 +154,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
fail-fast: false
- max-parallel: 1
+ max-parallel: 3
matrix:
impl: ${{ fromJson(needs.setup.outputs.impls) }}
steps:
diff --git a/.gitignore b/.gitignore
index d73d47d5..8af82201 100644
--- a/.gitignore
+++ b/.gitignore
@@ -58,7 +58,7 @@ backend/static/dist/
benchmarks/loadgen/bench-loadgen
# Rust build artifacts (oxc symbolicator shim)
-backend/app/symbolicator/scopes/oxc-shim/target/
+**/oxc-shim/target/
symbolicator-bench.txt
# Benchmark tool binary, built on demand by benchmarks/scripts/cachebench-*.sh
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.go
index 40c64b1e..06a07492 100644
--- a/backend/app/controllers/clientcontrollers/client.controller.go
+++ b/backend/app/controllers/clientcontrollers/client.controller.go
@@ -41,6 +41,7 @@ type ReportRequest struct {
CollectionFrames []*clientmodels.CollectionFrame `json:"collectionFrames"`
AppVersion string `json:"appVersion"`
ServerName string `json:"serverName"`
+ ProguardUuid string `json:"proguardUuid"`
}
func (e clientController) Report(c *gin.Context) {
@@ -136,6 +137,7 @@ func (e clientController) Report(c *gin.Context) {
resolveJs := project != nil && project.SourceMapToken != nil && jsFrameworks[project.Framework]
resolveDart := project != nil && project.SourceMapToken != nil && project.Framework == "flutter"
resolveIos := project != nil && project.SourceMapToken != nil && project.Framework == "ios"
+ resolveAndroid := project != nil && project.SourceMapToken != nil && project.Framework == "android"
resolveSpan := traceway.StartSpan(c, "report.resolve_stack_traces")
for _, cst := range cf.StackTraces {
@@ -146,6 +148,8 @@ func (e clientController) Report(c *gin.Context) {
resolvedStackTrace = services.ResolveDartStackTrace(c, projectId, cst.StackTrace)
} else if resolveIos {
resolvedStackTrace = services.ResolveIOSStackTrace(c, projectId, cst.StackTrace)
+ } else if resolveAndroid {
+ resolvedStackTrace = services.ResolveAndroidStackTrace(c, projectId, cst.StackTrace, request.ProguardUuid)
}
est := cst.ToExceptionStackTrace(ComputeExceptionHash(resolvedStackTrace, cst.IsMessage), request.AppVersion, request.ServerName)
est.StackTrace = resolvedStackTrace
diff --git a/backend/app/controllers/otelcontrollers/android_converter_test.go b/backend/app/controllers/otelcontrollers/android_converter_test.go
new file mode 100644
index 00000000..05573195
--- /dev/null
+++ b/backend/app/controllers/otelcontrollers/android_converter_test.go
@@ -0,0 +1,117 @@
+package otelcontrollers
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/services"
+
+ coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+ resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
+ tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
+
+ "github.com/google/uuid"
+)
+
+func androidConvFixture(t *testing.T, parts ...string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(append([]string{"..", "..", "symbolicator", "android", "fixtures"}, parts...)...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func androidExceptionRequest(stacktrace, proguardUuid string, extraEvent []*commonpb.KeyValue) *coltracepb.ExportTraceServiceRequest {
+ traceId := []byte{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf}
+ spanId := []byte{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7}
+ now := uint64(1_700_000_000_000_000_000)
+
+ eventAttrs := []*commonpb.KeyValue{
+ strKV("exception.type", "a.b"),
+ strKV("exception.message", "card declined for $30.59"),
+ }
+ if stacktrace != "" {
+ eventAttrs = append(eventAttrs, strKV("exception.stacktrace", stacktrace))
+ }
+ eventAttrs = append(eventAttrs, extraEvent...)
+
+ return &coltracepb.ExportTraceServiceRequest{
+ ResourceSpans: []*tracepb.ResourceSpans{{
+ Resource: &resourcepb.Resource{Attributes: []*commonpb.KeyValue{
+ strKV("service.name", "androdemo"),
+ strKV("telemetry.sdk.language", "android"),
+ strKV("app.debug.proguard_uuid", proguardUuid),
+ }},
+ ScopeSpans: []*tracepb.ScopeSpans{{
+ Scope: &commonpb.InstrumentationScope{Name: "io.honeycomb.opentelemetry.android"},
+ Spans: []*tracepb.Span{{
+ TraceId: traceId, SpanId: spanId,
+ Name: "UncaughtException", Kind: tracepb.Span_SPAN_KIND_INTERNAL,
+ StartTimeUnixNano: now, EndTimeUnixNano: now + 1_000_000,
+ Events: []*tracepb.Span_Event{{
+ Name: "exception",
+ TimeUnixNano: now + 500_000,
+ Attributes: eventAttrs,
+ }},
+ }},
+ }},
+ }},
+ }
+}
+
+func TestConvertTraces_AndroidR8Retraces(t *testing.T) {
+ projectId := uuid.MustParse("00000000-0000-0000-0000-0000000000a1")
+ const proguardUuid = "6A8CB813-45F6-3652-AD33-778FD1EAB196"
+
+ setFakeStore(t, map[string][]byte{
+ services.AndroidMappingKey(projectId, proguardUuid): androidConvFixture(t, "r8", "mapping.txt"),
+ })
+
+ req := androidExceptionRequest(string(androidConvFixture(t, "r8", "obfuscated.txt")), proguardUuid, nil)
+ _, _, _, exceptions, _, _ := convertTraces(context.Background(), tokenProject(projectId), projectId, req)
+ if len(exceptions) != 1 {
+ t.Fatalf("expected 1 exception, got %d", len(exceptions))
+ }
+ got := exceptions[0].StackTrace
+ if strings.Contains(got, "a.a.a(") {
+ t.Errorf("trace still obfuscated:\n%s", got)
+ }
+ for _, want := range []string{"com.example.demo.Checkout.chargeCard", "Checkout.java", "PaymentDeclinedException"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %q in retraced OTLP exception:\n%s", want, got)
+ }
+ }
+ if exceptions[0].Attributes["telemetry.sdk.language"] != "android" {
+ t.Errorf("expected stamped telemetry.sdk.language=android, got %q", exceptions[0].Attributes["telemetry.sdk.language"])
+ }
+}
+
+func TestConvertTraces_AndroidStructuredArrays(t *testing.T) {
+ projectId := uuid.MustParse("00000000-0000-0000-0000-0000000000a2")
+ const proguardUuid = "AAA0CB813-45F6-3652-AD33-778FD1EAB196"
+
+ setFakeStore(t, map[string][]byte{
+ services.AndroidMappingKey(projectId, proguardUuid): androidConvFixture(t, "r8", "mapping.txt"),
+ })
+
+ extra := []*commonpb.KeyValue{
+ strArrayKV("exception.structured_stacktrace.classes", "a.a"),
+ strArrayKV("exception.structured_stacktrace.methods", "a"),
+ strArrayKV("exception.structured_stacktrace.source_files", "SourceFile"),
+ intArrayKV("exception.structured_stacktrace.lines", 2),
+ }
+ req := androidExceptionRequest("", proguardUuid, extra)
+ _, _, _, exceptions, _, _ := convertTraces(context.Background(), tokenProject(projectId), projectId, req)
+ if len(exceptions) != 1 {
+ t.Fatalf("expected 1 exception, got %d", len(exceptions))
+ }
+ got := exceptions[0].StackTrace
+ if !strings.Contains(got, "com.example.demo.Checkout.chargeCard") {
+ t.Errorf("structured-array android trace not retraced:\n%s", got)
+ }
+}
diff --git a/backend/app/controllers/otelcontrollers/otel.controller.go b/backend/app/controllers/otelcontrollers/otel.controller.go
index ad10f05e..56d0a6b5 100644
--- a/backend/app/controllers/otelcontrollers/otel.controller.go
+++ b/backend/app/controllers/otelcontrollers/otel.controller.go
@@ -34,6 +34,16 @@ func otelSymbolicateJs(existingProject *models.Project, projectId uuid.UUID, ctx
return services.ResolveStackTrace(ctx, projectId, canonical, nil)
}
+func otelSymbolicateAndroid(existingProject *models.Project, projectId uuid.UUID, ctx context.Context, stackTrace, language, proguardUuid string) string {
+ if !isAndroidLanguage(language) {
+ return stackTrace
+ }
+ if existingProject == nil || existingProject.SourceMapToken == nil {
+ return stackTrace
+ }
+ return services.ResolveAndroidStackTrace(ctx, projectId, stackTrace, proguardUuid)
+}
+
type otelController struct{}
var OtelController = otelController{}
diff --git a/backend/app/controllers/otelcontrollers/trace_converter.go b/backend/app/controllers/otelcontrollers/trace_converter.go
index a78de796..5caf5eb4 100644
--- a/backend/app/controllers/otelcontrollers/trace_converter.go
+++ b/backend/app/controllers/otelcontrollers/trace_converter.go
@@ -57,6 +57,7 @@ func convertTraces(ctx context.Context, existingProject *models.Project, project
serverName := getStringAttribute(resourceAttrs, "service.name")
appVersion := getStringAttribute(resourceAttrs, "service.version")
language := getStringAttribute(resourceAttrs, "telemetry.sdk.language")
+ proguardUuid := getStringAttribute(resourceAttrs, "app.debug.proguard_uuid")
if appVersion == "" {
if scriptVersionId := getStringAttribute(resourceAttrs, "cloudflare.script_version.id"); scriptVersionId != "" {
if idx := strings.LastIndex(scriptVersionId, "-"); idx != -1 {
@@ -281,7 +282,7 @@ func convertTraces(ctx context.Context, existingProject *models.Project, project
hadExceptionEvent = true
exc := buildException(
ctx, existingProject, projectId, ownerId, traceType, event.Attributes, event.TimeUnixNano,
- allAttrs, serverName, appVersion, language, entry.scopeName,
+ allAttrs, serverName, appVersion, language, proguardUuid, entry.scopeName,
)
if owner != nil {
exc.DistributedTraceId = owner.distributedTraceId
@@ -293,7 +294,7 @@ func convertTraces(ctx context.Context, existingProject *models.Project, project
if !hadExceptionEvent && hasExceptionAttributes(span.Attributes) {
exc := buildException(
ctx, existingProject, projectId, ownerId, traceType, span.Attributes, span.StartTimeUnixNano,
- allAttrs, serverName, appVersion, language, entry.scopeName,
+ allAttrs, serverName, appVersion, language, proguardUuid, entry.scopeName,
)
if owner != nil {
exc.DistributedTraceId = owner.distributedTraceId
@@ -481,7 +482,7 @@ func buildException(
excAttrs []*commonpb.KeyValue,
timeUnixNano uint64,
spanAttrs map[string]string,
- serverName, appVersion, language, scopeName string,
+ serverName, appVersion, language, proguardUuid, scopeName string,
) models.ExceptionStackTrace {
excType := getStringAttribute(excAttrs, "exception.type")
excMessage := getStringAttribute(excAttrs, "exception.message")
@@ -489,15 +490,21 @@ func buildException(
stackTrace, ok := buildHoneycombStackTrace(excType, excMessage, excAttrs)
if !ok {
excStacktrace := getStringAttribute(excAttrs, "exception.stacktrace")
+ if excStacktrace == "" {
+ if frames, aok := buildAndroidStructuredStackTrace(excAttrs); aok {
+ excStacktrace = frames
+ }
+ }
stackTrace = formatExceptionStackTrace(excType, excMessage, excStacktrace)
}
stackTrace = otelSymbolicateJs(existingProject, projectId, ctx, stackTrace, language, scopeName)
+ stackTrace = otelSymbolicateAndroid(existingProject, projectId, ctx, stackTrace, language, proguardUuid)
hash := clientcontrollers.ComputeExceptionHash(stackTrace, false)
attrs := spanAttrs
- if isJsLanguage(language) {
+ if isJsLanguage(language) || isAndroidLanguage(language) {
attrs = cloneStringMap(spanAttrs)
attrs["telemetry.sdk.language"] = language
}
@@ -547,6 +554,42 @@ func isJsLanguage(lang string) bool {
return false
}
+func isAndroidLanguage(lang string) bool {
+ switch strings.ToLower(strings.TrimSpace(lang)) {
+ case "android", "java", "kotlin":
+ return true
+ }
+ return false
+}
+
+func buildAndroidStructuredStackTrace(eventAttrs []*commonpb.KeyValue) (string, bool) {
+ classes := getStringArray(eventAttrs, "exception.structured_stacktrace.classes")
+ if len(classes) == 0 {
+ return "", false
+ }
+ methods := getStringArray(eventAttrs, "exception.structured_stacktrace.methods")
+ files := getStringArray(eventAttrs, "exception.structured_stacktrace.source_files")
+ lines := getIntArray(eventAttrs, "exception.structured_stacktrace.lines")
+
+ var b strings.Builder
+ for i := range classes {
+ method := ""
+ if i < len(methods) {
+ method = methods[i]
+ }
+ file := ""
+ if i < len(files) {
+ file = files[i]
+ }
+ loc := file
+ if i < len(lines) && lines[i] > 0 {
+ loc = fmt.Sprintf("%s:%d", file, lines[i])
+ }
+ fmt.Fprintf(&b, "\tat %s.%s(%s)\n", classes[i], method, loc)
+ }
+ return strings.TrimRight(b.String(), "\n"), true
+}
+
// JS instrumentations are also recognizable by their scope name when
// telemetry.sdk.language is absent: npm scoped packages ("@scope/pkg") are
// an npm-only naming convention across OTel SDKs, and Next.js's built-in
diff --git a/backend/app/controllers/symbols.controller.go b/backend/app/controllers/symbols.controller.go
index d9c693d8..4b03be72 100644
--- a/backend/app/controllers/symbols.controller.go
+++ b/backend/app/controllers/symbols.controller.go
@@ -10,6 +10,7 @@ import (
"github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/services"
"github.com/tracewayapp/traceway/backend/app/storage"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/android"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
"github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
@@ -63,6 +64,11 @@ func (s symbolsController) Upload(c *gin.Context) {
return
}
uploaded++
+ case android.LooksLikeR8Mapping(data):
+ if !s.uploadAndroidMapping(c, projectId, fileHeader.Filename, data) {
+ return
+ }
+ uploaded++
case filepath.Ext(fileHeader.Filename) == ".symbols":
if !s.uploadDart(c, projectId, fileHeader.Filename, data) {
return
@@ -74,6 +80,30 @@ func (s symbolsController) Upload(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"uploaded": uploaded})
}
+func (s symbolsController) uploadAndroidMapping(c *gin.Context, projectId uuid.UUID, filename string, data []byte) bool {
+ proguardUuid := c.PostForm("proguard_uuid")
+ if proguardUuid == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("no proguard_uuid for %s; pass a 'proguard_uuid' field (the build UUID)", filename)})
+ return false
+ }
+ if services.NormalizeProguardUUID(proguardUuid) == "" {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("invalid proguard_uuid %q for %s", proguardUuid, filename)})
+ return false
+ }
+ if android.ParseMapping(string(data)).IsEmpty() {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("%s is not a valid R8/ProGuard mapping", filename)})
+ return false
+ }
+
+ key := services.AndroidMappingKey(projectId, proguardUuid)
+ if err := storage.Store.Write(c, key, data); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to write mapping to storage: %w", err))
+ return false
+ }
+ services.InvalidateAndroidMapping(key)
+ return true
+}
+
func (s symbolsController) uploadDart(c *gin.Context, projectId uuid.UUID, filename string, data []byte) bool {
arch := c.PostForm("arch")
if arch == "" {
diff --git a/backend/app/controllers/symbols_test.go b/backend/app/controllers/symbols_test.go
index 480a31c7..2242893b 100644
--- a/backend/app/controllers/symbols_test.go
+++ b/backend/app/controllers/symbols_test.go
@@ -68,6 +68,28 @@ func runSymbolsUpload(t *testing.T, projectId uuid.UUID, filename string, data [
return rec
}
+func runSymbolsUploadWithFields(t *testing.T, projectId uuid.UUID, filename string, data []byte, fields map[string]string) *httptest.ResponseRecorder {
+ t.Helper()
+ var body bytes.Buffer
+ w := multipart.NewWriter(&body)
+ fw, _ := w.CreateFormFile("files", filename)
+ fw.Write(data)
+ for k, v := range fields {
+ _ = w.WriteField(k, v)
+ }
+ w.Close()
+
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/api/symbols/upload", &body)
+ c.Request.Header.Set("Content-Type", w.FormDataContentType())
+ c.Set(middleware.ProjectIdContextKey, projectId)
+
+ SymbolsController.Upload(c)
+ return rec
+}
+
func iosUploadFixture(t *testing.T, name string) []byte {
t.Helper()
b, err := os.ReadFile(filepath.Join("..", "symbolicator", "ios", "fixtures", "sample", name))
@@ -77,6 +99,55 @@ func iosUploadFixture(t *testing.T, name string) []byte {
return b
}
+func androidUploadFixture(t *testing.T, parts ...string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(append([]string{"..", "symbolicator", "android", "fixtures"}, parts...)...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func TestUploadAndroidMapping(t *testing.T) {
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store := newMemStore()
+ storage.Store = store
+
+ projectId := uuid.New()
+ const proguardUuid = "6A8CB813-45F6-3652-AD33-778FD1EAB196"
+ rec := runSymbolsUploadWithFields(t, projectId, "mapping.txt",
+ androidUploadFixture(t, "r8", "mapping.txt"),
+ map[string]string{"proguard_uuid": proguardUuid})
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
+ }
+ if _, ok := store.data[services.AndroidMappingKey(projectId, proguardUuid)]; !ok {
+ t.Errorf("mapping not stored at %s; keys=%v", services.AndroidMappingKey(projectId, proguardUuid), keysOf(store))
+ }
+}
+
+func TestUploadAndroidMappingRequiresUuid(t *testing.T) {
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ storage.Store = newMemStore()
+
+ rec := runSymbolsUpload(t, uuid.New(), "mapping.txt", androidUploadFixture(t, "r8", "mapping.txt"))
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for missing proguard_uuid, got %d: %s", rec.Code, rec.Body.String())
+ }
+}
+
+func keysOf(s *memStore) []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := make([]string, 0, len(s.data))
+ for k := range s.data {
+ out = append(out, k)
+ }
+ return out
+}
+
func TestUploadIOSFatStoresPerSlice(t *testing.T) {
prev := storage.Store
defer func() { storage.Store = prev }()
diff --git a/backend/app/services/android_symbolicator.go b/backend/app/services/android_symbolicator.go
new file mode 100644
index 00000000..ea8c1fe9
--- /dev/null
+++ b/backend/app/services/android_symbolicator.go
@@ -0,0 +1,111 @@
+package services
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/tracewayapp/traceway/backend/app/storage"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/android"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/twcache"
+
+ "github.com/google/uuid"
+ traceway "go.tracewayapp.com"
+)
+
+func loadAndroidMapping(mappingKey string) twcache.LoadFunc[SymbolicationCacheEntry] {
+ return func(ctx context.Context) (SymbolicationCacheEntry, error) {
+ raw, err := readWithTimeout(context.WithoutCancel(ctx), mappingKey)
+ if err != nil {
+ return nil, err
+ }
+ return android.ParseMapping(string(raw)), nil
+ }
+}
+
+func getMapping(ctx context.Context, key string, load twcache.LoadFunc[SymbolicationCacheEntry]) (*android.Mapping, func()) {
+ data, done, err := sharedCache.Get(ctx, key, load)
+ if err != nil {
+ return nil, noop
+ }
+ m, ok := data.(*android.Mapping)
+ if !ok || m == nil {
+ done()
+ return nil, noop
+ }
+ return m, done
+}
+
+func AndroidMappingKey(projectId uuid.UUID, proguardUuid string) string {
+ return fmt.Sprintf("androidmappings/%s/%s.txt", projectId, NormalizeProguardUUID(proguardUuid))
+}
+
+func androidMappingFlatKey(mappingKey string) string {
+ return strings.TrimSuffix(mappingKey, ".txt") + ".tw"
+}
+
+func NormalizeProguardUUID(s string) string { return android.NormalizeProguardUUID(s) }
+
+func ResolveAndroidStackTrace(ctx context.Context, projectId uuid.UUID, rawTrace, proguardUuid string) string {
+ if !android.IsAndroidTrace(rawTrace) {
+ return rawTrace
+ }
+ text := rawTrace
+
+ local := map[string]borrow{}
+ defer releaseBorrows(local)
+
+ if proguardUuid != "" && android.IsR8Trace(text) {
+ mappingKey := AndroidMappingKey(projectId, proguardUuid)
+ if symbolicatorOnDisk() {
+ cacheKey := androidMappingFlatKey(mappingKey)
+ if !sharedCache.IsNegative(cacheKey) {
+ if data := getBlob(ctx, cacheKey, loadAndroidMappingBlob(cacheKey, mappingKey), local); data != nil {
+ text = android.RetraceFlat(data, text)
+ }
+ }
+ } else if !sharedCache.IsNegative(mappingKey) {
+ if m, done := getMapping(ctx, mappingKey, loadAndroidMapping(mappingKey)); m != nil {
+ text = m.Retrace(text)
+ done()
+ }
+ }
+ }
+
+ out := strings.TrimRight(text, "\n")
+ if out == "" || out == strings.TrimRight(rawTrace, "\n") {
+ return rawTrace
+ }
+ return out
+}
+
+func loadAndroidMappingBlob(cacheKey, mappingKey string) twcache.LoadFunc[SymbolicationCacheEntry] {
+ return func(ctx context.Context) (SymbolicationCacheEntry, error) {
+ base := context.WithoutCancel(ctx)
+
+ if tw, err := readWithTimeout(base, cacheKey); err == nil {
+ if android.ValidR8Flat(tw) {
+ return tw, nil
+ }
+ } else if !isStorageNotFound(err) {
+ traceway.CaptureException(fmt.Errorf("failed to read android mapping artifact, rebuilding (key=%s): %w", cacheKey, err))
+ }
+
+ raw, err := readWithTimeout(base, mappingKey)
+ if err != nil {
+ return nil, err
+ }
+ blob := android.BuildR8Flat(string(raw))
+ if werr := storage.Store.Write(base, cacheKey, blob); werr != nil {
+ traceway.CaptureException(fmt.Errorf("failed to persist android mapping artifact (key=%s): %w", cacheKey, werr))
+ }
+ return blob, nil
+ }
+}
+
+func InvalidateAndroidMapping(mappingKey string) {
+ flatKey := androidMappingFlatKey(mappingKey)
+ sharedCache.Invalidate(flatKey)
+ _ = storage.Store.Delete(context.Background(), flatKey)
+ sharedCache.Invalidate(mappingKey)
+}
diff --git a/backend/app/services/android_symbolicator_test.go b/backend/app/services/android_symbolicator_test.go
new file mode 100644
index 00000000..9113654b
--- /dev/null
+++ b/backend/app/services/android_symbolicator_test.go
@@ -0,0 +1,109 @@
+package services
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/storage"
+
+ "github.com/google/uuid"
+)
+
+func androidFixture(t *testing.T, parts ...string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(append([]string{"..", "symbolicator", "android", "fixtures"}, parts...)...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func TestResolveAndroidStackTrace(t *testing.T) {
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store, err := storage.NewLocalStorage(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ storage.Store = store
+
+ ctx := context.Background()
+ projectId := uuid.New()
+ const proguardUuid = "11112222-3333-4444-5555-666677778888"
+
+ mapping := androidFixture(t, "r8", "mapping.txt")
+ if err := store.Write(ctx, AndroidMappingKey(projectId, proguardUuid), mapping); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Run("r8", func(t *testing.T) {
+ obf := string(androidFixture(t, "r8", "obfuscated.txt"))
+ got := ResolveAndroidStackTrace(ctx, projectId, obf, proguardUuid)
+ if strings.Contains(got, "a.a.a(") {
+ t.Errorf("output still obfuscated:\n%s", got)
+ }
+ for _, want := range []string{"com.example.demo.Checkout.chargeCard", "Checkout.java", "com.example.demo.Main.main"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %q in retraced output:\n%s", want, got)
+ }
+ }
+ })
+
+ t.Run("no_uuid_skips_r8", func(t *testing.T) {
+ obf := string(androidFixture(t, "r8", "obfuscated.txt"))
+ got := ResolveAndroidStackTrace(ctx, projectId, obf, "")
+ if !strings.Contains(got, "a.a.a(") {
+ t.Errorf("expected trace to stay obfuscated without a proguard uuid:\n%s", got)
+ }
+ })
+
+ t.Run("non_android_passthrough", func(t *testing.T) {
+ raw := "TypeError: boom\n at foo (app.js:1:2)"
+ if got := ResolveAndroidStackTrace(ctx, projectId, raw, proguardUuid); got != raw {
+ t.Errorf("non-android trace mutated: %q", got)
+ }
+ })
+}
+
+func TestResolveAndroidR8MemoryAndDiskAgree(t *testing.T) {
+ prevStore := storage.Store
+ defer func() { storage.Store = prevStore }()
+ store, err := storage.NewLocalStorage(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ storage.Store = store
+
+ ctx := context.Background()
+ projectId := uuid.New()
+ const proguardUuid = "22223333-4444-5555-6666-777788889999"
+ if err := store.Write(ctx, AndroidMappingKey(projectId, proguardUuid), androidFixture(t, "r8", "mapping.txt")); err != nil {
+ t.Fatal(err)
+ }
+ obf := string(androidFixture(t, "r8", "obfuscated.txt"))
+
+ if symbolicatorOnDisk() {
+ t.Fatal("expected an in-memory shared cache by default")
+ }
+ mem := ResolveAndroidStackTrace(ctx, projectId, obf, proguardUuid)
+ if !strings.Contains(mem, "com.example.demo.Checkout.chargeCard") {
+ t.Fatalf("memory-mode retrace missing expected frame:\n%s", mem)
+ }
+
+ prevCache := sharedCache
+ defer func() { sharedCache = prevCache }()
+ if err := EnableSymbolicatorDiskCache(t.TempDir(), 64<<20); err != nil {
+ t.Fatal(err)
+ }
+ if !symbolicatorOnDisk() {
+ t.Fatal("expected a disk-backed shared cache after EnableSymbolicatorDiskCache")
+ }
+ disk := ResolveAndroidStackTrace(ctx, projectId, obf, proguardUuid)
+
+ if mem != disk {
+ t.Errorf("memory and disk retrace differ:\nmem: %q\ndisk: %q", mem, disk)
+ }
+}
diff --git a/backend/app/services/dart_symbolicator.go b/backend/app/services/dart_symbolicator.go
index e43e6c27..613c49ea 100644
--- a/backend/app/services/dart_symbolicator.go
+++ b/backend/app/services/dart_symbolicator.go
@@ -97,7 +97,12 @@ func loadDartData(ctx context.Context, projectId uuid.UUID, trace dart.StackTrac
if err != nil {
return nil, noop
}
- return data, done
+ b, ok := data.([]byte)
+ if !ok {
+ done()
+ return nil, noop
+ }
+ return b, done
}
func dartFlatKey(symbolsKey string) string {
@@ -112,9 +117,9 @@ func InvalidateDartSymbols(keys ...string) {
}
}
-func loadDartBlob(cacheKey string) twcache.LoadFunc {
+func loadDartBlob(cacheKey string) twcache.LoadFunc[SymbolicationCacheEntry] {
symbolsKey := strings.TrimSuffix(cacheKey, ".tw") + ".symbols"
- return func(ctx context.Context) ([]byte, error) {
+ return func(ctx context.Context) (SymbolicationCacheEntry, error) {
base := context.WithoutCancel(ctx)
if twBytes, err := readWithTimeout(base, cacheKey); err == nil {
diff --git a/backend/app/services/ios_symbolicator.go b/backend/app/services/ios_symbolicator.go
index da185027..3078bb8a 100644
--- a/backend/app/services/ios_symbolicator.go
+++ b/backend/app/services/ios_symbolicator.go
@@ -72,8 +72,8 @@ func iosErrorPreamble(raw string) string {
return strings.TrimRight(strings.Join(lines[:cut], "\n"), "\n")
}
-func loadIOSBlob(cacheKey, symbolsKey, debugID, arch string) twcache.LoadFunc {
- return func(ctx context.Context) ([]byte, error) {
+func loadIOSBlob(cacheKey, symbolsKey, debugID, arch string) twcache.LoadFunc[SymbolicationCacheEntry] {
+ return func(ctx context.Context) (SymbolicationCacheEntry, error) {
base := context.WithoutCancel(ctx)
if tw, err := readWithTimeout(base, cacheKey); err == nil {
diff --git a/backend/app/services/sourcemap_disk_cache_test.go b/backend/app/services/sourcemap_disk_cache_test.go
index 380e8397..79bb043c 100644
--- a/backend/app/services/sourcemap_disk_cache_test.go
+++ b/backend/app/services/sourcemap_disk_cache_test.go
@@ -22,7 +22,7 @@ func useMemCache(t *testing.T) {
t.Cleanup(func() { sharedCache = prev })
}
-func useDiskCache(t *testing.T, dir string, maxBytes int64) *twcache.Cache {
+func useDiskCache(t *testing.T, dir string, maxBytes int64) *twcache.Cache[SymbolicationCacheEntry] {
t.Helper()
prev := sharedCache
if err := EnableSymbolicatorDiskCache(dir, maxBytes); err != nil {
@@ -39,11 +39,12 @@ func resolveSMFrame(t *testing.T, ctx context.Context, mapKey, bundleKey string)
return sourcemap.StackTraceFrame{}, false, err
}
defer done()
- frame, ok := sourcemap.LookupTW(data, 0, 10)
+ b, _ := data.([]byte)
+ frame, ok := sourcemap.LookupTW(b, 0, 10)
return frame, ok, nil
}
-func twPathFor(disk *twcache.Cache, mapKey string) string {
+func twPathFor(disk *twcache.Cache[SymbolicationCacheEntry], mapKey string) string {
return filepath.Join(disk.Dir(), filepath.FromSlash(twKeyFor(mapKey)))
}
diff --git a/backend/app/services/sourcemap_resolver.go b/backend/app/services/sourcemap_resolver.go
index 3ca3d88a..ebceee2d 100644
--- a/backend/app/services/sourcemap_resolver.go
+++ b/backend/app/services/sourcemap_resolver.go
@@ -199,7 +199,7 @@ func frameData(ctx context.Context, prefix, fileName, base string, debugIds map[
return getBlob(ctx, twKey, loadSourceMapBlob(mapKey, prefix+base), local)
}
-func getBlob(ctx context.Context, twKey string, load twcache.LoadFunc, local map[string]borrow) []byte {
+func getBlob(ctx context.Context, twKey string, load twcache.LoadFunc[SymbolicationCacheEntry], local map[string]borrow) []byte {
if br, ok := local[twKey]; ok {
return br.data
}
@@ -208,14 +208,15 @@ func getBlob(ctx context.Context, twKey string, load twcache.LoadFunc, local map
local[twKey] = borrow{}
return nil
}
- local[twKey] = borrow{data: data, done: done}
- return data
+ b, _ := data.([]byte)
+ local[twKey] = borrow{data: b, done: done}
+ return b
}
var smStoreHits, smBuilds atomic.Uint64
-func loadSourceMapBlob(mapKey, bundleKey string) twcache.LoadFunc {
- return func(ctx context.Context) ([]byte, error) {
+func loadSourceMapBlob(mapKey, bundleKey string) twcache.LoadFunc[SymbolicationCacheEntry] {
+ return func(ctx context.Context) (SymbolicationCacheEntry, error) {
base := context.WithoutCancel(ctx)
twKey := twKeyFor(mapKey)
diff --git a/backend/app/services/symbolicator_cache.go b/backend/app/services/symbolicator_cache.go
index 6ed39ce5..b8da69df 100644
--- a/backend/app/services/symbolicator_cache.go
+++ b/backend/app/services/symbolicator_cache.go
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/tracewayapp/traceway/backend/app/storage"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/android"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
"github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
"github.com/tracewayapp/traceway/backend/app/symbolicator/sourcemap"
@@ -14,16 +15,38 @@ import (
traceway "go.tracewayapp.com"
)
-func validArtifact(b []byte) bool {
- return sourcemap.ValidTW(b) || dart.ValidFlat(b) || ios.ValidFlat(b)
+type SymbolicationCacheEntry = any
+
+func validArtifact(v SymbolicationCacheEntry) bool {
+ switch t := v.(type) {
+ case []byte:
+ return sourcemap.ValidTW(t) || dart.ValidFlat(t) || ios.ValidFlat(t) || android.ValidR8Flat(t)
+ case *android.Mapping:
+ return t != nil
+ default:
+ return false
+ }
+}
+
+func weighEntry(v SymbolicationCacheEntry) int64 {
+ switch t := v.(type) {
+ case []byte:
+ return int64(len(t))
+ case *android.Mapping:
+ return t.ApproxSize()
+ default:
+ return 0
+ }
}
var sharedCache = newSymbolicatorCache()
+func symbolicatorOnDisk() bool { return sharedCache.Dir() != "" }
+
func isStorageNotFound(err error) bool { return errors.Is(err, storage.ErrNotFound) }
-func newSymbolicatorCache() *twcache.Cache {
- c := twcache.NewMem(200, 500<<20)
+func newSymbolicatorCache() *twcache.Cache[SymbolicationCacheEntry] {
+ c := twcache.NewMemFunc(200, 500<<20, weighEntry)
c.NotFound = isStorageNotFound
c.Validate = validArtifact
c.SetWarn(func(err error) { traceway.CaptureException(err) })
@@ -31,7 +54,7 @@ func newSymbolicatorCache() *twcache.Cache {
}
func EnableSymbolicatorDiskCache(dir string, maxBytes int64) error {
- c, err := twcache.NewDisk(dir, maxBytes, func(err error) { traceway.CaptureException(err) })
+ c, err := twcache.NewDiskAny(dir, maxBytes, func(err error) { traceway.CaptureException(err) })
if err != nil {
return fmt.Errorf("symbolicator disk cache: %w", err)
}
diff --git a/backend/app/symbolicator/android/android_test.go b/backend/app/symbolicator/android/android_test.go
new file mode 100644
index 00000000..89fb8e7c
--- /dev/null
+++ b/backend/app/symbolicator/android/android_test.go
@@ -0,0 +1,125 @@
+package android
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestR8Retrace(t *testing.T) {
+ dirs, _ := filepath.Glob(filepath.Join("fixtures", "r8*"))
+ if len(dirs) == 0 {
+ t.Fatal("no r8 fixtures found")
+ }
+ for _, dir := range dirs {
+ if info, err := os.Stat(dir); err != nil || !info.IsDir() {
+ continue
+ }
+ t.Run(filepath.Base(dir), func(t *testing.T) {
+ mapping := mustRead(t, filepath.Join(dir, "mapping.txt"))
+ obf := mustRead(t, filepath.Join(dir, "obfuscated.txt"))
+ want := nonEmptyLines(mustRead(t, filepath.Join(dir, "expected.txt")))
+ got := nonEmptyLines(ParseMapping(mapping).Retrace(obf))
+ compareLines(t, got, want)
+ })
+ }
+}
+
+func TestR8FlatMatchesInMemory(t *testing.T) {
+ dirs, _ := filepath.Glob(filepath.Join("fixtures", "r8*"))
+ if len(dirs) == 0 {
+ t.Fatal("no r8 fixtures found")
+ }
+ for _, dir := range dirs {
+ if info, err := os.Stat(dir); err != nil || !info.IsDir() {
+ continue
+ }
+ t.Run(filepath.Base(dir), func(t *testing.T) {
+ mapping := mustRead(t, filepath.Join(dir, "mapping.txt"))
+ obf := mustRead(t, filepath.Join(dir, "obfuscated.txt"))
+ want := nonEmptyLines(mustRead(t, filepath.Join(dir, "expected.txt")))
+
+ flat := BuildR8Flat(mapping)
+ if !ValidR8Flat(flat) {
+ t.Fatal("BuildR8Flat produced data that fails ValidR8Flat")
+ }
+
+ got := nonEmptyLines(RetraceFlat(flat, obf))
+ compareLines(t, got, want)
+
+ if RetraceFlat(flat, obf) != ParseMapping(mapping).Retrace(obf) {
+ t.Errorf("flat retrace differs from in-memory retrace for %s", filepath.Base(dir))
+ }
+ })
+ }
+}
+
+func TestValidR8FlatRejectsGarbage(t *testing.T) {
+ if ValidR8Flat([]byte("not a flat mapping")) {
+ t.Error("ValidR8Flat accepted garbage")
+ }
+ if ValidR8Flat(nil) {
+ t.Error("ValidR8Flat accepted nil")
+ }
+}
+
+func TestLooksLikeR8Mapping(t *testing.T) {
+ mapping := mustReadBytes(t, filepath.Join("fixtures", "r8", "mapping.txt"))
+ if !LooksLikeR8Mapping(mapping) {
+ t.Error("mapping.txt not detected as R8 mapping")
+ }
+ if LooksLikeR8Mapping([]byte("just some text\nwith no mapping\n")) {
+ t.Error("plain text wrongly detected as R8 mapping")
+ }
+}
+
+func TestTraceDetection(t *testing.T) {
+ r8 := mustRead(t, filepath.Join("fixtures", "r8", "obfuscated.txt"))
+ if !IsR8Trace(r8) || !IsAndroidTrace(r8) {
+ t.Error("R8 trace not detected")
+ }
+}
+
+func compareLines(t *testing.T, got, want []string) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Errorf("frame count: got %d, want %d", len(got), len(want))
+ }
+ n := min(len(got), len(want))
+ for i := 0; i < n; i++ {
+ if got[i] != want[i] {
+ t.Errorf("line %d:\n got: %s\n want: %s", i, got[i], want[i])
+ }
+ }
+ for i := n; i < len(got); i++ {
+ t.Errorf("extra got line %d: %s", i, got[i])
+ }
+ for i := n; i < len(want); i++ {
+ t.Errorf("missing want line %d: %s", i, want[i])
+ }
+}
+
+func nonEmptyLines(s string) []string {
+ var out []string
+ for _, line := range strings.Split(s, "\n") {
+ if strings.TrimSpace(line) != "" {
+ out = append(out, strings.TrimSpace(line))
+ }
+ }
+ return out
+}
+
+func mustRead(t *testing.T, path string) string {
+ t.Helper()
+ return string(mustReadBytes(t, path))
+}
+
+func mustReadBytes(t *testing.T, path string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
diff --git a/backend/app/symbolicator/android/fixtures/r8-app/expected.txt b/backend/app/symbolicator/android/fixtures/r8-app/expected.txt
new file mode 100644
index 00000000..e2250be8
--- /dev/null
+++ b/backend/app/symbolicator/android/fixtures/r8-app/expected.txt
@@ -0,0 +1,8 @@
+com.example.androdemo.PaymentDeclinedException: card declined for $30.59
+ at com.example.androdemo.Checkout.chargeCard(Checkout.kt:5)
+ at com.example.androdemo.Checkout.applyTax(Checkout.kt:10)
+ at com.example.androdemo.Checkout.checkout(Checkout.kt:18)
+ at com.example.androdemo.MainActivity.crashKotlin(MainActivity.kt:33)
+ at com.example.androdemo.MainActivity.onCreate$lambda$4$lambda$3(MainActivity.kt:22)
+ at android.view.View.performClick(View.java:7659)
+ at android.app.Activity.dispatchTouchEvent(Activity.java:4204)
diff --git a/backend/app/symbolicator/android/fixtures/r8-app/mapping.txt b/backend/app/symbolicator/android/fixtures/r8-app/mapping.txt
new file mode 100644
index 00000000..89beaf60
--- /dev/null
+++ b/backend/app/symbolicator/android/fixtures/r8-app/mapping.txt
@@ -0,0 +1,174 @@
+# compiler: R8
+# compiler_version: 8.7.18
+# min_api: 24
+# common_typos_disable
+# {"id":"com.android.tools.r8.mapping","version":"2.2"}
+# pg_map_id: 224618e
+# pg_map_hash: SHA-256 224618e8d10251e01f614fb1be0047f9d1b57e5efad071b0a17e917c1e76ef3d
+com.example.androdemo.Checkout -> R8$$REMOVED$$CLASS$$0:
+# {"id":"sourceFile","fileName":"Checkout.kt"}
+com.example.androdemo.MainActivity -> com.example.androdemo.MainActivity:
+# {"id":"sourceFile","fileName":"MainActivity.kt"}
+ int $r8$clinit -> a
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void <init>():8:8 -> <init>
+ 1:1:void crashKotlin():33:33 -> a
+ 2:2:double com.example.androdemo.Checkout.checkout(double[]):15:15 -> a
+ 2:2:void crashKotlin():33 -> a
+ 3:3:double com.example.androdemo.Checkout.chargeCard(double):5:5 -> a
+ 3:3:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 3:3:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 3:3:void crashKotlin():33 -> a
+ 4:4:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140:140 -> a
+ 4:4:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 4:4:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 4:4:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 4:4:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 4:4:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 4:4:void crashKotlin():33 -> a
+ 5:5:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):144:144 -> a
+ 5:5:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 5:5:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 5:5:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 5:5:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 5:5:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 5:5:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 5:5:void crashKotlin():33 -> a
+ 6:6:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):146:146 -> a
+ 6:6:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 6:6:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 6:6:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 6:6:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 6:6:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 6:6:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 6:6:void crashKotlin():33 -> a
+ 7:7:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):149:149 -> a
+ 7:7:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 7:7:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 7:7:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 7:7:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 7:7:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 7:7:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 7:7:void crashKotlin():33 -> a
+ 8:8:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):151:151 -> a
+ 8:8:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 8:8:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 8:8:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 8:8:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 8:8:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 8:8:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 8:8:void crashKotlin():33 -> a
+ 9:11:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):153:155 -> a
+ 9:11:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 9:11:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 9:11:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 9:11:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 9:11:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 9:11:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 9:11:void crashKotlin():33 -> a
+ 12:12:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):157:157 -> a
+ 12:12:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 12:12:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 12:12:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 12:12:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 12:12:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 12:12:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 12:12:void crashKotlin():33 -> a
+ 13:13:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140:140 -> a
+ 13:13:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 13:13:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 13:13:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 13:13:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 13:13:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 13:13:void crashKotlin():33 -> a
+ 14:14:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253:253 -> a
+ 14:14:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 14:14:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 14:14:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 14:14:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 14:14:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 14:14:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 14:14:void crashKotlin():33 -> a
+ 15:16:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable,java.lang.String):257:258 -> a
+ 15:16:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253 -> a
+ 15:16:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 15:16:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 15:16:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 15:16:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 15:16:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 15:16:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 15:16:void crashKotlin():33 -> a
+ 17:17:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable,java.lang.String):262:262 -> a
+ 17:17:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253 -> a
+ 17:17:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 17:17:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 17:17:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 17:17:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 17:17:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 17:17:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 17:17:void crashKotlin():33 -> a
+ 18:19:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable,java.lang.String):267:268 -> a
+ 18:19:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253 -> a
+ 18:19:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 18:19:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 18:19:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 18:19:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 18:19:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 18:19:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 18:19:void crashKotlin():33 -> a
+ 20:20:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140:140 -> a
+ 20:20:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 20:20:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 20:20:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 20:20:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 20:20:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 20:20:void crashKotlin():33 -> a
+ 21:21:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):3:3 -> a
+ 21:21:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 21:21:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 21:21:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 21:21:void crashKotlin():33 -> a
+ 22:22:double com.example.androdemo.Checkout.chargeCard(double):5:5 -> a
+ 22:22:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 22:22:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 22:22:void crashKotlin():33 -> a
+ 1:1:void onCreate(android.os.Bundle):10:10 -> onCreate
+ 2:4:void onCreate(android.os.Bundle):12:14 -> onCreate
+ 5:7:void onCreate(android.os.Bundle):16:18 -> onCreate
+ 8:8:void onCreate(android.os.Bundle):16:16 -> onCreate
+ 9:11:void onCreate(android.os.Bundle):20:22 -> onCreate
+ 12:12:void onCreate(android.os.Bundle):20:20 -> onCreate
+ 13:13:void onCreate(android.os.Bundle):24:24 -> onCreate
+ 14:14:void onCreate(android.os.Bundle):26:26 -> onCreate
+ 15:15:void crashNative():37:37 -> onCreate
+ 15:15:void onCreate(android.os.Bundle):28 -> onCreate
+ 16:17:void onCreate(android.os.Bundle):26:27 -> onCreate
+com.example.androdemo.MainActivity$$ExternalSyntheticLambda0 -> a.a:
+# {"id":"sourceFile","fileName":"R8$$SyntheticClass"}
+# {"id":"com.android.tools.r8.synthesized"}
+ int a.MainActivity$$ExternalSyntheticLambda0.$r8$classId -> a
+ # {"id":"com.android.tools.r8.synthesized"}
+ com.example.androdemo.MainActivity com.example.androdemo.MainActivity$$InternalSyntheticLambda$1$fd788ef1c9019be65d0bc8853139bec490236ec6d1e2a1f187ca4d1845e5f895$0.f$0 -> b
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void a.MainActivity$$ExternalSyntheticLambda0.<init>(com.example.androdemo.MainActivity,int):0:0 -> <init>
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void com.example.androdemo.MainActivity.onCreate$lambda$4$lambda$3(com.example.androdemo.MainActivity,android.view.View):22:22 -> onClick
+ 1:1:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+ # {"id":"com.android.tools.r8.synthesized"}
+ 2:2:void com.example.androdemo.MainActivity.crashNative():37:37 -> onClick
+ 2:2:void com.example.androdemo.MainActivity.onCreate$lambda$4$lambda$3(com.example.androdemo.MainActivity,android.view.View):22 -> onClick
+ 2:2:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+ 3:3:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0:0 -> onClick
+ 4:4:void com.example.androdemo.MainActivity.onCreate$lambda$2$lambda$1(com.example.androdemo.MainActivity,android.view.View):18:18 -> onClick
+ 4:4:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+com.example.androdemo.NativeBridge -> com.example.androdemo.NativeBridge:
+# {"id":"sourceFile","fileName":"NativeBridge.kt"}
+ com.example.androdemo.NativeBridge INSTANCE -> a
+ 1:1:void <init>():3:3 -> <clinit>
+ 1:1:void <clinit>():0 -> <clinit>
+ 2:2:void <clinit>():0:0 -> <clinit>
+ 3:3:void <clinit>():5:5 -> <clinit>
+com.example.androdemo.PaymentDeclinedException -> a.b:
+# {"id":"sourceFile","fileName":"PaymentDeclinedException.kt"}
+kotlin.jvm.internal.Intrinsics -> b.a:
+# {"id":"sourceFile","fileName":"Intrinsics.java"}
diff --git a/backend/app/symbolicator/android/fixtures/r8-app/obfuscated.txt b/backend/app/symbolicator/android/fixtures/r8-app/obfuscated.txt
new file mode 100644
index 00000000..9802994c
--- /dev/null
+++ b/backend/app/symbolicator/android/fixtures/r8-app/obfuscated.txt
@@ -0,0 +1,5 @@
+a.b: card declined for $30.59
+ at com.example.androdemo.MainActivity.a(SourceFile:3)
+ at a.a.onClick(SourceFile:1)
+ at android.view.View.performClick(View.java:7659)
+ at android.app.Activity.dispatchTouchEvent(Activity.java:4204)
diff --git a/backend/app/symbolicator/android/fixtures/r8/expected.txt b/backend/app/symbolicator/android/fixtures/r8/expected.txt
new file mode 100644
index 00000000..3700ea22
--- /dev/null
+++ b/backend/app/symbolicator/android/fixtures/r8/expected.txt
@@ -0,0 +1,5 @@
+Exception in thread "main" com.example.demo.PaymentDeclinedException: card declined for $30.59
+ at com.example.demo.Checkout.chargeCard(Checkout.java:6)
+ at com.example.demo.Checkout.applyTax(Checkout.java:11)
+ at com.example.demo.Checkout.checkout(Checkout.java:19)
+ at com.example.demo.Main.main(Main.java:6)
diff --git a/backend/app/symbolicator/android/fixtures/r8/mapping.txt b/backend/app/symbolicator/android/fixtures/r8/mapping.txt
new file mode 100644
index 00000000..24d60508
--- /dev/null
+++ b/backend/app/symbolicator/android/fixtures/r8/mapping.txt
@@ -0,0 +1,21 @@
+# compiler: R8
+# compiler_version: 8.9.27
+# common_typos_disable
+# {"id":"com.android.tools.r8.mapping","version":"2.2"}
+# pg_map_id: e5f09de
+# pg_map_hash: SHA-256 e5f09de2797207316d0ebad5e82d1a6772e8c593fff6a0c7ffd62d6830c02c05
+com.example.demo.Checkout -> a.a:
+# {"id":"sourceFile","fileName":"Checkout.java"}
+ 1:2:double chargeCard(double):5:6 -> a
+ # {"id":"com.android.tools.r8.residualsignature","signature":"(D)V"}
+com.example.demo.Main -> com.example.demo.Main:
+# {"id":"sourceFile","fileName":"Main.java"}
+ 1:1:void main(java.lang.String[]):5:5 -> main
+ 2:2:double com.example.demo.Checkout.checkout(double[]):16:16 -> main
+ 2:2:void main(java.lang.String[]):6 -> main
+ 3:3:double com.example.demo.Checkout.applyTax(double):11:11 -> main
+ 3:3:double com.example.demo.Checkout.checkout(double[]):19 -> main
+ 3:3:void main(java.lang.String[]):6 -> main
+com.example.demo.PaymentDeclinedException -> a.b:
+# {"id":"sourceFile","fileName":"PaymentDeclinedException.java"}
+ 1:1:void <init>(java.lang.String):5:5 -> <init>
diff --git a/backend/app/symbolicator/android/fixtures/r8/obfuscated.txt b/backend/app/symbolicator/android/fixtures/r8/obfuscated.txt
new file mode 100644
index 00000000..caad649f
--- /dev/null
+++ b/backend/app/symbolicator/android/fixtures/r8/obfuscated.txt
@@ -0,0 +1,3 @@
+Exception in thread "main" a.b: card declined for $30.59
+ at a.a.a(SourceFile:2)
+ at com.example.demo.Main.main(SourceFile:3)
diff --git a/backend/app/symbolicator/android/normalize.go b/backend/app/symbolicator/android/normalize.go
new file mode 100644
index 00000000..d2fa1ebe
--- /dev/null
+++ b/backend/app/symbolicator/android/normalize.go
@@ -0,0 +1,14 @@
+package android
+
+import "strings"
+
+func NormalizeProguardUUID(s string) string {
+ var b strings.Builder
+ for _, r := range strings.TrimSpace(s) {
+ switch {
+ case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F', r == '-':
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
diff --git a/backend/app/symbolicator/android/parser_diff_test.go b/backend/app/symbolicator/android/parser_diff_test.go
new file mode 100644
index 00000000..4c3e1904
--- /dev/null
+++ b/backend/app/symbolicator/android/parser_diff_test.go
@@ -0,0 +1,223 @@
+package android
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+var (
+ oClassLineRe = regexp.MustCompile(`^(\S+) -> (\S+):$`)
+ oSourceFileRe = regexp.MustCompile(`"id":"sourceFile","fileName":"([^"]+)"`)
+ oMethodLineRe = regexp.MustCompile(`^\s+(?:(\d+):(\d+):)?[^ ]+ ([^ (]+)\([^)]*\)(?::(\d+)(?::(\d+))?)? -> (\S+)$`)
+ oAtFrameRe = regexp.MustCompile(`^(\s*)at\s+(.+)\((.*)\)\s*$`)
+ oClassTokenRe = regexp.MustCompile(`[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*`)
+)
+
+func parseMappingRegex(text string) *Mapping {
+ m := &Mapping{
+ classOrig: map[string]string{},
+ classFile: map[string]string{},
+ methods: map[string]map[string][]methodMapping{},
+ }
+ var curObf, curOrig, lastMethod string
+ for _, line := range strings.Split(text, "\n") {
+ if line == "" {
+ continue
+ }
+ if strings.HasPrefix(strings.TrimSpace(line), "#") {
+ if curOrig != "" {
+ if sm := oSourceFileRe.FindStringSubmatch(line); sm != nil {
+ m.classFile[curOrig] = sm[1]
+ }
+ }
+ if strings.Contains(line, "com.android.tools.r8.synthesized") && lastMethod != "" {
+ if s := m.methods[curObf][lastMethod]; len(s) > 0 {
+ s[len(s)-1].synthesized = true
+ }
+ }
+ continue
+ }
+ if cm := oClassLineRe.FindStringSubmatch(line); cm != nil {
+ curOrig, curObf, lastMethod = cm[1], cm[2], ""
+ m.classOrig[curObf] = curOrig
+ if m.methods[curObf] == nil {
+ m.methods[curObf] = map[string][]methodMapping{}
+ }
+ continue
+ }
+ mm := oMethodLineRe.FindStringSubmatch(line)
+ if mm == nil || curObf == "" {
+ lastMethod = ""
+ continue
+ }
+ entry := methodMapping{}
+ if mm[1] != "" {
+ entry.hasObf = true
+ entry.obfStart, _ = strconv.Atoi(mm[1])
+ entry.obfEnd, _ = strconv.Atoi(mm[2])
+ }
+ qn := mm[3]
+ if i := strings.LastIndex(qn, "."); i >= 0 {
+ entry.origClass = qn[:i]
+ entry.method = qn[i+1:]
+ } else {
+ entry.origClass = curOrig
+ entry.method = qn
+ }
+ if mm[4] != "" {
+ entry.hasOrig = true
+ entry.origStart, _ = strconv.Atoi(mm[4])
+ if mm[5] != "" {
+ entry.origEnd, _ = strconv.Atoi(mm[5])
+ } else {
+ entry.origEnd = entry.origStart
+ }
+ }
+ m.methods[curObf][mm[6]] = append(m.methods[curObf][mm[6]], entry)
+ lastMethod = mm[6]
+ }
+
+ size := int64(len(m.classOrig)) * 96
+ for _, byMethod := range m.methods {
+ for _, entries := range byMethod {
+ size += int64(len(entries))*96 + 64
+ }
+ }
+ m.approxSize = size + 1
+
+ return m
+}
+
+func retraceRegex(src r8Source, text string) string {
+ var b strings.Builder
+ emitted := 0
+ for _, line := range strings.Split(strings.TrimRight(text, "\n"), "\n") {
+ if fm := oAtFrameRe.FindStringSubmatch(line); fm != nil && emitted < maxFrames {
+ if out, n, ok := retraceFrameWith(src, fm[1], fm[2], fm[3]); ok {
+ b.WriteString(out)
+ emitted += n
+ continue
+ }
+ }
+ b.WriteString(replaceClassesRegex(src, line))
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+
+func replaceClassesRegex(src r8Source, line string) string {
+ return oClassTokenRe.ReplaceAllStringFunc(line, func(tok string) string {
+ if orig, _, ok := src.classInfo(tok); ok {
+ return orig
+ }
+ return tok
+ })
+}
+
+const edgeCaseMapping = `# compiler: R8
+# pg_map_id: deadbeef
+com.example.Foo -> a.a:
+# {"id":"sourceFile","fileName":"Foo.kt"}
+ int $r8$clinit -> a
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void <init>():8:8 -> <init>
+ 1:1:void crashKotlin():33:33 -> a
+ 2:2:double com.example.Bar.checkout(double[]):15:15 -> a
+ 3:3:double com.example.Bar.applyTax(double):10 -> a
+ void render() -> b
+ com.example.Foo INSTANCE -> c
+com.example.Removed -> R8$$REMOVED$$CLASS$$0:
+# {"id":"sourceFile","fileName":"Removed.kt"}
+ 1:1:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void onCreate$lambda$4$lambda$3():22:22 -> onClick
+ 1:1:void onClick(android.view.View):0 -> onClick
+ # {"id":"com.android.tools.r8.synthesized"}
+
+orphan.method():1 -> x
+ not a real line here
+`
+
+func bigMapping(tb testing.TB) string {
+ tb.Helper()
+ base, err := os.ReadFile(filepath.Join("fixtures", "r8-app", "mapping.txt"))
+ if err != nil {
+ tb.Fatal(err)
+ }
+ var b strings.Builder
+ b.Write(base)
+ if len(base) > 0 && base[len(base)-1] != '\n' {
+ b.WriteByte('\n')
+ }
+ for i := 0; b.Len() < 1<<20; i++ {
+ fmt.Fprintf(&b, "benchpad.S%dClass%d -> twbp_%d:\n", i, i, i)
+ b.WriteString(" 1:1:void run():1:1 -> a\n")
+ b.WriteString(" 2:2:int compute(int):2:2 -> b\n")
+ }
+ return b.String()
+}
+
+func TestParseMappingMatchesRegex(t *testing.T) {
+ inputs := map[string]string{
+ "r8": mustRead(t, filepath.Join("fixtures", "r8", "mapping.txt")),
+ "r8-app": mustRead(t, filepath.Join("fixtures", "r8-app", "mapping.txt")),
+ "big": bigMapping(t),
+ "edges": edgeCaseMapping,
+ }
+ for name, in := range inputs {
+ t.Run(name, func(t *testing.T) {
+ if !reflect.DeepEqual(ParseMapping(in), parseMappingRegex(in)) {
+ t.Errorf("manual ParseMapping differs from the regex oracle for %s", name)
+ }
+ })
+ }
+}
+
+func TestRetraceMatchesRegex(t *testing.T) {
+ for _, dir := range []string{"r8", "r8-app"} {
+ mapping := mustRead(t, filepath.Join("fixtures", dir, "mapping.txt"))
+ obf := mustRead(t, filepath.Join("fixtures", dir, "obfuscated.txt"))
+ m := parseMappingRegex(mapping)
+ if got, want := m.Retrace(obf), retraceRegex(m, obf); got != want {
+ t.Errorf("%s: manual retrace differs from regex retrace\n got: %q\nwant: %q", dir, got, want)
+ }
+ }
+}
+
+func FuzzParseMapping(f *testing.F) {
+ for _, dir := range []string{"r8", "r8-app"} {
+ if b, err := os.ReadFile(filepath.Join("fixtures", dir, "mapping.txt")); err == nil {
+ f.Add(string(b))
+ }
+ }
+ f.Add(edgeCaseMapping)
+ f.Fuzz(func(t *testing.T, data string) {
+ if !reflect.DeepEqual(ParseMapping(data), parseMappingRegex(data)) {
+ t.Fatalf("manual and regex parsers diverge for input %q", data)
+ }
+ })
+}
+
+func BenchmarkParseMapping(b *testing.B) {
+ in := bigMapping(b)
+ b.Run("regex", func(b *testing.B) {
+ b.SetBytes(int64(len(in)))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ _ = parseMappingRegex(in)
+ }
+ })
+ b.Run("manual", func(b *testing.B) {
+ b.SetBytes(int64(len(in)))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ _ = ParseMapping(in)
+ }
+ })
+}
diff --git a/backend/app/symbolicator/android/r8flat.go b/backend/app/symbolicator/android/r8flat.go
new file mode 100644
index 00000000..6097c75d
--- /dev/null
+++ b/backend/app/symbolicator/android/r8flat.go
@@ -0,0 +1,359 @@
+package android
+
+import (
+ "encoding/binary"
+ "sort"
+ "strings"
+)
+
+var r8Magic = [4]byte{'T', 'W', 'R', '8'}
+
+const (
+ r8Version = 1
+ r8HeaderSize = 20
+ r8ClassSize = 20
+ r8MemberSize = 36
+
+ r8FlagHasObf = 1 << 0
+ r8FlagHasOrig = 1 << 1
+ r8FlagSynthesized = 1 << 2
+)
+
+func BuildR8Flat(mappingText string) []byte {
+ return ParseMapping(mappingText).marshalR8()
+}
+
+type r8ClassRec struct {
+ obfIdx, origIdx, fileIdx int32
+ memberStart, memberCount uint32
+}
+
+type r8MemberRec struct {
+ obfMethodIdx, origIdx, methodIdx, fileIdx int32
+ obfStart, obfEnd, origStart, origEnd int32
+ flags uint32
+}
+
+func (m *Mapping) marshalR8() []byte {
+ strs := newInterner()
+ var classes []r8ClassRec
+ var members []r8MemberRec
+
+ obfNames := make([]string, 0, len(m.classOrig))
+ for obf := range m.classOrig {
+ obfNames = append(obfNames, obf)
+ }
+ sort.Strings(obfNames)
+
+ for _, obf := range obfNames {
+ orig := m.classOrig[obf]
+
+ type flatMember struct {
+ obfMethod string
+ e methodMapping
+ }
+ var flat []flatMember
+ for obfMethod, entries := range m.methods[obf] {
+ for _, e := range entries {
+ flat = append(flat, flatMember{obfMethod, e})
+ }
+ }
+ sort.SliceStable(flat, func(i, j int) bool { return flat[i].obfMethod < flat[j].obfMethod })
+
+ start := uint32(len(members))
+ for _, fm := range flat {
+ e := fm.e
+ var flags uint32
+ if e.hasObf {
+ flags |= r8FlagHasObf
+ }
+ if e.hasOrig {
+ flags |= r8FlagHasOrig
+ }
+ if e.synthesized {
+ flags |= r8FlagSynthesized
+ }
+ members = append(members, r8MemberRec{
+ obfMethodIdx: strs.intern(fm.obfMethod),
+ origIdx: strs.intern(e.origClass),
+ methodIdx: strs.intern(e.method),
+ fileIdx: strs.intern(m.fileFor(e.origClass, "")),
+ obfStart: int32(e.obfStart),
+ obfEnd: int32(e.obfEnd),
+ origStart: int32(e.origStart),
+ origEnd: int32(e.origEnd),
+ flags: flags,
+ })
+ }
+ classes = append(classes, r8ClassRec{
+ obfIdx: strs.intern(obf),
+ origIdx: strs.intern(orig),
+ fileIdx: strs.intern(m.fileFor(orig, "")),
+ memberStart: start,
+ memberCount: uint32(len(members)) - start,
+ })
+ }
+
+ le := binary.LittleEndian
+ strOffsets, strBlob := encodeStringTable(strs.list)
+
+ size := r8HeaderSize + len(classes)*r8ClassSize + len(members)*r8MemberSize + len(strOffsets)*4 + len(strBlob)
+ out := make([]byte, 0, size)
+ out = append(out, r8Magic[:]...)
+ out = le.AppendUint32(out, r8Version)
+ out = le.AppendUint32(out, uint32(len(classes)))
+ out = le.AppendUint32(out, uint32(len(members)))
+ out = le.AppendUint32(out, uint32(len(strs.list)))
+ for _, c := range classes {
+ out = le.AppendUint32(out, uint32(c.obfIdx))
+ out = le.AppendUint32(out, uint32(c.origIdx))
+ out = le.AppendUint32(out, uint32(c.fileIdx))
+ out = le.AppendUint32(out, c.memberStart)
+ out = le.AppendUint32(out, c.memberCount)
+ }
+ for _, mr := range members {
+ out = le.AppendUint32(out, uint32(mr.obfMethodIdx))
+ out = le.AppendUint32(out, uint32(mr.origIdx))
+ out = le.AppendUint32(out, uint32(mr.methodIdx))
+ out = le.AppendUint32(out, uint32(mr.fileIdx))
+ out = le.AppendUint32(out, uint32(mr.obfStart))
+ out = le.AppendUint32(out, uint32(mr.obfEnd))
+ out = le.AppendUint32(out, uint32(mr.origStart))
+ out = le.AppendUint32(out, uint32(mr.origEnd))
+ out = le.AppendUint32(out, mr.flags)
+ }
+ for _, off := range strOffsets {
+ out = le.AppendUint32(out, off)
+ }
+ out = append(out, strBlob...)
+ return out
+}
+
+type r8Layout struct {
+ classCount int
+ memberOff int
+ memberCount int
+ strTableOff int
+ strCount int
+}
+
+func readR8Layout(data []byte) (r8Layout, bool) {
+ var l r8Layout
+ if len(data) < r8HeaderSize {
+ return l, false
+ }
+ le := binary.LittleEndian
+ if data[0] != r8Magic[0] || data[1] != r8Magic[1] || data[2] != r8Magic[2] || data[3] != r8Magic[3] {
+ return l, false
+ }
+ if le.Uint32(data[4:]) != r8Version {
+ return l, false
+ }
+ classCount := int64(le.Uint32(data[8:]))
+ memberCount := int64(le.Uint32(data[12:]))
+ strCount := int64(le.Uint32(data[16:]))
+ n := int64(len(data))
+
+ classOff := int64(r8HeaderSize)
+ memberOff := classOff + classCount*r8ClassSize
+ strTableOff := memberOff + memberCount*r8MemberSize
+ if classCount < 0 || memberCount < 0 || strCount < 0 || memberOff < classOff || strTableOff < memberOff {
+ return l, false
+ }
+ strBlobOff := strTableOff + (strCount+1)*4
+ if strBlobOff > n {
+ return l, false
+ }
+ blobLen := int64(le.Uint32(data[strTableOff+strCount*4:]))
+ if strBlobOff+blobLen > n {
+ return l, false
+ }
+
+ l.classCount = int(classCount)
+ l.memberOff = int(memberOff)
+ l.memberCount = int(memberCount)
+ l.strTableOff = int(strTableOff)
+ l.strCount = int(strCount)
+ return l, true
+}
+
+func ValidR8Flat(data []byte) bool {
+ _, ok := readR8Layout(data)
+ return ok
+}
+
+func RetraceFlat(data []byte, text string) string {
+ r, ok := newR8Reader(data)
+ if !ok {
+ return text
+ }
+ return retraceWith(r, text)
+}
+
+type r8Reader struct {
+ data []byte
+ l r8Layout
+}
+
+func newR8Reader(data []byte) (*r8Reader, bool) {
+ l, ok := readR8Layout(data)
+ if !ok {
+ return nil, false
+ }
+ return &r8Reader{data: data, l: l}, true
+}
+
+func (r *r8Reader) str(idx int32) string {
+ s, _ := stringAt(r.data, r.l.strTableOff, r.l.strCount, idx)
+ return s
+}
+
+func (r *r8Reader) classObfIdx(i int) int32 {
+ return int32(binary.LittleEndian.Uint32(r.data[r8HeaderSize+i*r8ClassSize:]))
+}
+
+func (r *r8Reader) classRec(i int) (origIdx, fileIdx int32, memberStart, memberCount uint32) {
+ rec := r.data[r8HeaderSize+i*r8ClassSize:]
+ le := binary.LittleEndian
+ return int32(le.Uint32(rec[4:])), int32(le.Uint32(rec[8:])), le.Uint32(rec[12:]), le.Uint32(rec[16:])
+}
+
+func (r *r8Reader) findClass(obf string) (int, bool) {
+ lo, hi := 0, r.l.classCount
+ for lo < hi {
+ mid := (lo + hi) / 2
+ switch strings.Compare(obf, r.str(r.classObfIdx(mid))) {
+ case 0:
+ return mid, true
+ case -1:
+ hi = mid
+ default:
+ lo = mid + 1
+ }
+ }
+ return 0, false
+}
+
+func (r *r8Reader) classInfo(obfClass string) (string, string, bool) {
+ i, ok := r.findClass(obfClass)
+ if !ok {
+ return "", "", false
+ }
+ origIdx, fileIdx, _, _ := r.classRec(i)
+ return r.str(origIdx), r.str(fileIdx), true
+}
+
+func (r *r8Reader) memberObfMethodIdx(i int) int32 {
+ return int32(binary.LittleEndian.Uint32(r.data[r.l.memberOff+i*r8MemberSize:]))
+}
+
+func (r *r8Reader) memberRec(i int) r8MemberRec {
+ rec := r.data[r.l.memberOff+i*r8MemberSize:]
+ le := binary.LittleEndian
+ return r8MemberRec{
+ obfMethodIdx: int32(le.Uint32(rec)),
+ origIdx: int32(le.Uint32(rec[4:])),
+ methodIdx: int32(le.Uint32(rec[8:])),
+ fileIdx: int32(le.Uint32(rec[12:])),
+ obfStart: int32(le.Uint32(rec[16:])),
+ obfEnd: int32(le.Uint32(rec[20:])),
+ origStart: int32(le.Uint32(rec[24:])),
+ origEnd: int32(le.Uint32(rec[28:])),
+ flags: le.Uint32(rec[32:]),
+ }
+}
+
+func (r *r8Reader) matched(obfClass, obfMethod string, obfLine int) []memberFrame {
+ ci, ok := r.findClass(obfClass)
+ if !ok {
+ return nil
+ }
+ _, _, memberStart, memberCount := r.classRec(ci)
+ start, end := int(memberStart), int(memberStart)+int(memberCount)
+ if end > r.l.memberCount {
+ return nil
+ }
+
+ lo, hi := start, end
+ for lo < hi {
+ mid := (lo + hi) / 2
+ if strings.Compare(r.str(r.memberObfMethodIdx(mid)), obfMethod) < 0 {
+ lo = mid + 1
+ } else {
+ hi = mid
+ }
+ }
+
+ var out []memberFrame
+ for i := lo; i < end; i++ {
+ mr := r.memberRec(i)
+ if r.str(mr.obfMethodIdx) != obfMethod {
+ break
+ }
+ if mr.flags&r8FlagSynthesized != 0 {
+ continue
+ }
+ if mr.flags&r8FlagHasObf != 0 && !(obfLine >= int(mr.obfStart) && obfLine <= int(mr.obfEnd)) {
+ continue
+ }
+ out = append(out, memberFrame{
+ cls: r.str(mr.origIdx),
+ method: r.str(mr.methodIdx),
+ file: r.str(mr.fileIdx),
+ line: computeLineFlat(mr, obfLine),
+ })
+ }
+ return out
+}
+
+func computeLineFlat(mr r8MemberRec, obfLine int) int {
+ if mr.flags&r8FlagHasOrig == 0 {
+ return obfLine
+ }
+ if mr.flags&r8FlagHasObf != 0 && mr.obfEnd > mr.obfStart && mr.origEnd > mr.origStart {
+ return int(mr.origStart) + (obfLine - int(mr.obfStart))
+ }
+ return int(mr.origStart)
+}
+
+type interner struct {
+ list []string
+ idx map[string]int32
+}
+
+func newInterner() *interner { return &interner{idx: make(map[string]int32)} }
+
+func (in *interner) intern(s string) int32 {
+ if i, ok := in.idx[s]; ok {
+ return i
+ }
+ i := int32(len(in.list))
+ in.list = append(in.list, s)
+ in.idx[s] = i
+ return i
+}
+
+func encodeStringTable(strs []string) ([]uint32, []byte) {
+ offsets := make([]uint32, len(strs)+1)
+ var blob []byte
+ for i, s := range strs {
+ offsets[i] = uint32(len(blob))
+ blob = append(blob, s...)
+ }
+ offsets[len(strs)] = uint32(len(blob))
+ return offsets, blob
+}
+
+func stringAt(data []byte, tableOff, count int, idx int32) (string, bool) {
+ if idx < 0 || int(idx) >= count {
+ return "", false
+ }
+ le := binary.LittleEndian
+ blobStart := tableOff + (count+1)*4
+ o0 := int(le.Uint32(data[tableOff+int(idx)*4:]))
+ o1 := int(le.Uint32(data[tableOff+(int(idx)+1)*4:]))
+ if o0 > o1 || blobStart+o1 > len(data) {
+ return "", false
+ }
+ return string(data[blobStart+o0 : blobStart+o1]), true
+}
diff --git a/backend/app/symbolicator/android/retrace.go b/backend/app/symbolicator/android/retrace.go
new file mode 100644
index 00000000..1fd519e1
--- /dev/null
+++ b/backend/app/symbolicator/android/retrace.go
@@ -0,0 +1,452 @@
+package android
+
+import (
+ "strconv"
+ "strings"
+)
+
+const maxFrames = 50
+
+type methodMapping struct {
+ hasObf bool
+ obfStart int
+ obfEnd int
+ origClass string
+ method string
+ hasOrig bool
+ origStart int
+ origEnd int
+ synthesized bool
+}
+
+type Mapping struct {
+ classOrig map[string]string
+ classFile map[string]string
+ methods map[string]map[string][]methodMapping
+ approxSize int64
+}
+
+func (m *Mapping) ApproxSize() int64 { return m.approxSize }
+
+func isWS(b byte) bool { return b == ' ' || b == '\t' || b == '\n' || b == '\f' || b == '\r' }
+
+func isDigit(b byte) bool { return b >= '0' && b <= '9' }
+
+func isIdentStart(b byte) bool {
+ return b == '_' || b == '$' || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z')
+}
+
+func isIdentPart(b byte) bool { return isIdentStart(b) || isDigit(b) }
+
+func hasWS(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if isWS(s[i]) {
+ return true
+ }
+ }
+ return false
+}
+
+func scanUint(s string, i int) (val, next int, ok bool) {
+ j := i
+ for j < len(s) && isDigit(s[j]) {
+ val = val*10 + int(s[j]-'0')
+ j++
+ }
+ return val, j, j > i
+}
+
+const sourceFileMarker = `"id":"sourceFile","fileName":"`
+
+func sourceFileFrom(line string) (string, bool) {
+ s := line
+ for {
+ idx := strings.Index(s, sourceFileMarker)
+ if idx < 0 {
+ return "", false
+ }
+ start := idx + len(sourceFileMarker)
+ if end := strings.IndexByte(s[start:], '"'); end > 0 {
+ return s[start : start+end], true
+ }
+ s = s[idx+1:]
+ }
+}
+
+func parseClassLine(line string) (orig, obf string, ok bool) {
+ idx := strings.Index(line, " -> ")
+ if idx <= 0 {
+ return "", "", false
+ }
+ orig = line[:idx]
+ rest := line[idx+4:]
+ if rest == "" || rest[len(rest)-1] != ':' {
+ return "", "", false
+ }
+ obf = rest[:len(rest)-1]
+ if obf == "" || hasWS(orig) || hasWS(obf) {
+ return "", "", false
+ }
+ return orig, obf, true
+}
+
+func parseMethodLine(line, curOrig string) (methodMapping, string, bool) {
+ i := 0
+ for i < len(line) && isWS(line[i]) {
+ i++
+ }
+ if i == 0 || i >= len(line) {
+ return methodMapping{}, "", false
+ }
+
+ // The obfStart:obfEnd: prefix is an optional regex group; the engine tries it
+ // present first, then backtracks to absent if the rest fails to parse.
+ if v1, j, ok1 := scanUint(line, i); ok1 && j < len(line) && line[j] == ':' {
+ if v2, k, ok2 := scanUint(line, j+1); ok2 && k < len(line) && line[k] == ':' {
+ e := methodMapping{hasObf: true, obfStart: v1, obfEnd: v2}
+ if om, ok := parseMethodRest(line, k+1, curOrig, &e); ok {
+ return e, om, true
+ }
+ }
+ }
+ var e methodMapping
+ if om, ok := parseMethodRest(line, i, curOrig, &e); ok {
+ return e, om, true
+ }
+ return methodMapping{}, "", false
+}
+
+func parseMethodRest(line string, i int, curOrig string, entry *methodMapping) (string, bool) {
+ sp := strings.IndexByte(line[i:], ' ')
+ if sp <= 0 {
+ return "", false
+ }
+ i += sp + 1
+
+ ms := i
+ for i < len(line) && line[i] != ' ' && line[i] != '(' {
+ i++
+ }
+ if i == ms || i >= len(line) || line[i] != '(' {
+ return "", false
+ }
+ method := line[ms:i]
+
+ cp := strings.IndexByte(line[i+1:], ')')
+ if cp < 0 {
+ return "", false
+ }
+ i = i + 1 + cp + 1
+
+ if i < len(line) && line[i] == ':' {
+ v1, j, ok1 := scanUint(line, i+1)
+ if !ok1 {
+ return "", false
+ }
+ entry.hasOrig = true
+ entry.origStart = v1
+ entry.origEnd = v1
+ i = j
+ if i < len(line) && line[i] == ':' {
+ v2, k, ok2 := scanUint(line, i+1)
+ if !ok2 {
+ return "", false
+ }
+ entry.origEnd = v2
+ i = k
+ }
+ }
+
+ if i+4 > len(line) || line[i:i+4] != " -> " {
+ return "", false
+ }
+ i += 4
+ obfMethod := line[i:]
+ if obfMethod == "" || hasWS(obfMethod) {
+ return "", false
+ }
+
+ if dot := strings.LastIndex(method, "."); dot >= 0 {
+ entry.origClass = method[:dot]
+ entry.method = method[dot+1:]
+ } else {
+ entry.origClass = curOrig
+ entry.method = method
+ }
+ return obfMethod, true
+}
+
+func LooksLikeR8Mapping(data []byte) bool {
+ text := string(data)
+ if len(text) > 1<<16 {
+ text = text[:1<<16]
+ }
+ n := 0
+ for _, line := range strings.Split(text, "\n") {
+ if strings.HasPrefix(line, "# compiler: R8") {
+ return true
+ }
+ if _, _, ok := parseClassLine(line); ok {
+ return true
+ }
+ if n++; n > 400 {
+ break
+ }
+ }
+ return false
+}
+
+func (m *Mapping) IsEmpty() bool { return len(m.classOrig) == 0 }
+
+func ParseMapping(text string) *Mapping {
+ m := &Mapping{
+ classOrig: map[string]string{},
+ classFile: map[string]string{},
+ methods: map[string]map[string][]methodMapping{},
+ }
+ var curObf, curOrig, lastMethod string
+ rest := text
+ for len(rest) > 0 {
+ var line string
+ if nl := strings.IndexByte(rest, '\n'); nl >= 0 {
+ line, rest = rest[:nl], rest[nl+1:]
+ } else {
+ line, rest = rest, ""
+ }
+ if line == "" {
+ continue
+ }
+ if strings.HasPrefix(strings.TrimSpace(line), "#") {
+ if curOrig != "" {
+ if fn, ok := sourceFileFrom(line); ok {
+ m.classFile[curOrig] = fn
+ }
+ }
+ if lastMethod != "" && strings.Contains(line, "com.android.tools.r8.synthesized") {
+ if s := m.methods[curObf][lastMethod]; len(s) > 0 {
+ s[len(s)-1].synthesized = true
+ }
+ }
+ continue
+ }
+ if !isWS(line[0]) {
+ if orig, obf, ok := parseClassLine(line); ok {
+ curOrig, curObf, lastMethod = orig, obf, ""
+ m.classOrig[curObf] = curOrig
+ if m.methods[curObf] == nil {
+ m.methods[curObf] = map[string][]methodMapping{}
+ }
+ } else {
+ lastMethod = ""
+ }
+ continue
+ }
+ if curObf == "" {
+ lastMethod = ""
+ continue
+ }
+ entry, obfMethod, ok := parseMethodLine(line, curOrig)
+ if !ok {
+ lastMethod = ""
+ continue
+ }
+ m.methods[curObf][obfMethod] = append(m.methods[curObf][obfMethod], entry)
+ lastMethod = obfMethod
+ }
+
+ size := int64(len(m.classOrig)) * 96
+ for _, byMethod := range m.methods {
+ for _, entries := range byMethod {
+ size += int64(len(entries))*96 + 64
+ }
+ }
+ m.approxSize = size + 1
+
+ return m
+}
+
+type memberFrame struct {
+ cls string
+ method string
+ file string
+ line int
+}
+
+type r8Source interface {
+ classInfo(obfClass string) (orig, file string, ok bool)
+ matched(obfClass, obfMethod string, obfLine int) []memberFrame
+}
+
+func (m *Mapping) Retrace(text string) string { return retraceWith(m, text) }
+
+func retraceWith(src r8Source, text string) string {
+ var b strings.Builder
+ emitted := 0
+ for _, line := range strings.Split(strings.TrimRight(text, "\n"), "\n") {
+ if indent, ref, loc, ok := scanFrame(line); ok && emitted < maxFrames {
+ if out, n, ok := retraceFrameWith(src, indent, ref, loc); ok {
+ b.WriteString(out)
+ emitted += n
+ continue
+ }
+ }
+ b.WriteString(replaceClassesWith(src, line))
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+
+func scanFrame(line string) (indent, ref, loc string, ok bool) {
+ i := 0
+ for i < len(line) && isWS(line[i]) {
+ i++
+ }
+ indent = line[:i]
+ if i+2 > len(line) || line[i] != 'a' || line[i+1] != 't' {
+ return "", "", "", false
+ }
+ j := i + 2
+ k := j
+ for k < len(line) && isWS(line[k]) {
+ k++
+ }
+ if k == j {
+ return "", "", "", false
+ }
+ end := len(line)
+ for end > k && isWS(line[end-1]) {
+ end--
+ }
+ if end <= k || line[end-1] != ')' {
+ return "", "", "", false
+ }
+ content := line[k : end-1]
+ lp := strings.LastIndexByte(content, '(')
+ if lp <= 0 {
+ return "", "", "", false
+ }
+ return indent, content[:lp], content[lp+1:], true
+}
+
+func isAtFrame(line string) bool {
+ _, _, _, ok := scanFrame(line)
+ return ok
+}
+
+func retraceFrameWith(src r8Source, indent, ref, loc string) (string, int, bool) {
+ dot := strings.LastIndex(ref, ".")
+ if dot < 0 {
+ return "", 0, false
+ }
+ obfClass, obfMethod := ref[:dot], ref[dot+1:]
+ origClass, file, ok := src.classInfo(obfClass)
+ if !ok {
+ return "", 0, false
+ }
+ lineStr := ""
+ if c := strings.LastIndex(loc, ":"); c >= 0 {
+ lineStr = loc[c+1:]
+ }
+ obfLine, _ := strconv.Atoi(lineStr)
+
+ members := src.matched(obfClass, obfMethod, obfLine)
+ var b strings.Builder
+ if len(members) == 0 {
+ b.WriteString(indent + "at " + origClass + "." + obfMethod + "(" + file + lineSuffix(obfLine) + ")\n")
+ return b.String(), 1, true
+ }
+ for _, mf := range members {
+ b.WriteString(indent + "at " + mf.cls + "." + mf.method + "(" + mf.file + ":" + strconv.Itoa(mf.line) + ")\n")
+ }
+ return b.String(), len(members), true
+}
+
+func replaceClassesWith(src r8Source, line string) string {
+ var b strings.Builder
+ i := 0
+ for i < len(line) {
+ if !isIdentStart(line[i]) {
+ b.WriteByte(line[i])
+ i++
+ continue
+ }
+ start := i
+ i++
+ for i < len(line) {
+ if isIdentPart(line[i]) {
+ i++
+ } else if line[i] == '.' && i+1 < len(line) && isIdentStart(line[i+1]) {
+ i += 2
+ } else {
+ break
+ }
+ }
+ tok := line[start:i]
+ if orig, _, ok := src.classInfo(tok); ok {
+ b.WriteString(orig)
+ } else {
+ b.WriteString(tok)
+ }
+ }
+ return b.String()
+}
+
+func (m *Mapping) classInfo(obfClass string) (string, string, bool) {
+ orig, ok := m.classOrig[obfClass]
+ if !ok {
+ return "", "", false
+ }
+ return orig, m.fileFor(orig, ""), true
+}
+
+func (m *Mapping) matched(obfClass, obfMethod string, obfLine int) []memberFrame {
+ var out []memberFrame
+ for _, e := range m.methods[obfClass][obfMethod] {
+ if e.synthesized {
+ continue
+ }
+ if !e.hasObf || (obfLine >= e.obfStart && obfLine <= e.obfEnd) {
+ out = append(out, memberFrame{
+ cls: e.origClass,
+ method: e.method,
+ file: m.fileFor(e.origClass, ""),
+ line: computeLine(e, obfLine),
+ })
+ }
+ }
+ return out
+}
+
+func computeLine(e methodMapping, obfLine int) int {
+ if !e.hasOrig {
+ return obfLine
+ }
+ if e.hasObf && e.obfEnd > e.obfStart && e.origEnd > e.origStart {
+ return e.origStart + (obfLine - e.obfStart)
+ }
+ return e.origStart
+}
+
+func (m *Mapping) fileFor(origClass, fallback string) string {
+ if f, ok := m.classFile[origClass]; ok {
+ return f
+ }
+ simple := origClass
+ if i := strings.LastIndex(simple, "."); i >= 0 {
+ simple = simple[i+1:]
+ }
+ if i := strings.Index(simple, "$"); i >= 0 {
+ simple = simple[:i]
+ }
+ if simple != "" {
+ return simple + ".java"
+ }
+ return fallback
+}
+
+func lineSuffix(line int) string {
+ if line > 0 {
+ return ":" + strconv.Itoa(line)
+ }
+ return ""
+}
diff --git a/backend/app/symbolicator/android/testdata/fuzz/FuzzParseMapping/0fd4ed9b6c55573f b/backend/app/symbolicator/android/testdata/fuzz/FuzzParseMapping/0fd4ed9b6c55573f
new file mode 100644
index 00000000..e65c5e15
--- /dev/null
+++ b/backend/app/symbolicator/android/testdata/fuzz/FuzzParseMapping/0fd4ed9b6c55573f
@@ -0,0 +1,2 @@
+go test fuzz v1
+string("0 -> 0:\n 0:0: 0() -> 0")
diff --git a/backend/app/symbolicator/android/testdata/fuzz/FuzzParseMapping/419f08298a45ddb0 b/backend/app/symbolicator/android/testdata/fuzz/FuzzParseMapping/419f08298a45ddb0
new file mode 100644
index 00000000..d83d5f54
--- /dev/null
+++ b/backend/app/symbolicator/android/testdata/fuzz/FuzzParseMapping/419f08298a45ddb0
@@ -0,0 +1,2 @@
+go test fuzz v1
+string("0000000000000000000000000 -> 000:\n#\"id\":\"sourceFile\",\"fileName\":\"\"id\":\"sourceFile\",\"fileName\":\"0\"")
diff --git a/backend/app/symbolicator/android/trace.go b/backend/app/symbolicator/android/trace.go
new file mode 100644
index 00000000..f2c40e98
--- /dev/null
+++ b/backend/app/symbolicator/android/trace.go
@@ -0,0 +1,16 @@
+package android
+
+import "strings"
+
+func IsR8Trace(text string) bool {
+ for _, line := range strings.Split(text, "\n") {
+ if isAtFrame(line) {
+ return true
+ }
+ }
+ return false
+}
+
+func IsAndroidTrace(text string) bool {
+ return IsR8Trace(text)
+}
diff --git a/backend/app/symbolicator/otelprocessor/android_test.go b/backend/app/symbolicator/otelprocessor/android_test.go
new file mode 100644
index 00000000..265d2362
--- /dev/null
+++ b/backend/app/symbolicator/otelprocessor/android_test.go
@@ -0,0 +1,67 @@
+package otelprocessor
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "go.opentelemetry.io/collector/pdata/pcommon"
+)
+
+const androidFixtureDir = "../android/fixtures"
+
+func androidFixture(t *testing.T, parts ...string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(append([]string{androidFixtureDir}, parts...)...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func TestSymbolicateAndroidR8(t *testing.T) {
+ for _, mode := range []string{"memory", "disk"} {
+ t.Run(mode, func(t *testing.T) {
+ const proguardUUID = "6A8CB813-45F6-3652-AD33-778FD1EAB196"
+ store := t.TempDir()
+ if err := os.WriteFile(filepath.Join(store, proguardUUID+".txt"), androidFixture(t, "r8", "mapping.txt"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ if mode == "disk" {
+ c.CacheDir = t.TempDir()
+ c.CacheMaxMB = 64
+ }
+ })
+ if (p.cache.Dir() != "") != (mode == "disk") {
+ t.Fatalf("cache mode mismatch for %q (dir=%q)", mode, p.cache.Dir())
+ }
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, string(androidFixture(t, "r8", "obfuscated.txt")))
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "android")
+ resource.PutStr(p.cfg.ProguardUUIDAttributeKey, proguardUUID)
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ if strings.Contains(got, "a.a.a(") {
+ t.Errorf("trace still obfuscated:\n%s", got)
+ }
+ for _, want := range []string{"com.example.demo.Checkout.chargeCard", "Checkout.java"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("missing %q in retraced output:\n%s", want, got)
+ }
+ }
+ if v, ok := attrs.Get(p.cfg.SymbolicatorFailureAttributeKey); !ok || v.Bool() {
+ t.Errorf("expected symbolicator.failed=false, got %v", v)
+ }
+ })
+ }
+}
diff --git a/backend/app/symbolicator/otelprocessor/cache.go b/backend/app/symbolicator/otelprocessor/cache.go
index 14f04ae0..f53f3ee2 100644
--- a/backend/app/symbolicator/otelprocessor/cache.go
+++ b/backend/app/symbolicator/otelprocessor/cache.go
@@ -7,21 +7,42 @@ import (
"fmt"
"os"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/android"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
"github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
"github.com/tracewayapp/traceway/backend/app/symbolicator/sourcemap"
"github.com/tracewayapp/traceway/backend/app/symbolicator/twcache"
)
-func validArtifact(b []byte) bool {
- return sourcemap.ValidTW(b) || dart.ValidFlat(b) || ios.ValidFlat(b)
+type cacheEntry = any
+
+func validArtifact(v cacheEntry) bool {
+ switch t := v.(type) {
+ case []byte:
+ return sourcemap.ValidTW(t) || dart.ValidFlat(t) || ios.ValidFlat(t) || android.ValidR8Flat(t)
+ case *android.Mapping:
+ return t != nil
+ default:
+ return false
+ }
+}
+
+func weighEntry(v cacheEntry) int64 {
+ switch t := v.(type) {
+ case []byte:
+ return int64(len(t))
+ case *android.Mapping:
+ return t.ApproxSize()
+ default:
+ return 0
+ }
}
func isObjectNotFound(err error) bool { return errors.Is(err, errObjectNotFound) }
-func newCache(cfg *Config) (*twcache.Cache, error) {
+func newCache(cfg *Config) (*twcache.Cache[cacheEntry], error) {
if cfg.CacheDir == "" {
- c := twcache.NewMem(cfg.SourceMapCacheSize, 1<<62)
+ c := twcache.NewMemFunc(cfg.SourceMapCacheSize, 1<<62, weighEntry)
c.Validate = validArtifact
c.NotFound = isObjectNotFound
return c, nil
@@ -43,7 +64,7 @@ func newCache(cfg *Config) (*twcache.Cache, error) {
if maxBytes <= 0 {
return nil, fmt.Errorf("the source map cache requires a positive byte cap (cache_max_mb or cache_max_disk_pct)")
}
- c, err := twcache.NewDisk(cfg.CacheDir, maxBytes, nil)
+ c, err := twcache.NewDiskAny(cfg.CacheDir, maxBytes, nil)
if err != nil {
return nil, err
}
diff --git a/backend/app/symbolicator/otelprocessor/config.go b/backend/app/symbolicator/otelprocessor/config.go
index 7f28a3ea..6ee7bd2f 100644
--- a/backend/app/symbolicator/otelprocessor/config.go
+++ b/backend/app/symbolicator/otelprocessor/config.go
@@ -46,6 +46,8 @@ type Config struct {
IOSBuildUUIDAttributeKey string `mapstructure:"ios_build_uuid_attribute_key"`
AppExecutableAttributeKey string `mapstructure:"app_executable_attribute_key"`
+ ProguardUUIDAttributeKey string `mapstructure:"proguard_uuid_attribute_key"`
+
SourceMapStoreKey string `mapstructure:"source_map_store"`
LocalSourceMaps LocalSourceMapsConfig `mapstructure:"local_source_maps"`
S3SourceMaps S3SourceMapsConfig `mapstructure:"s3_source_maps"`
diff --git a/backend/app/symbolicator/otelprocessor/factory.go b/backend/app/symbolicator/otelprocessor/factory.go
index c646f420..96e579c6 100644
--- a/backend/app/symbolicator/otelprocessor/factory.go
+++ b/backend/app/symbolicator/otelprocessor/factory.go
@@ -52,6 +52,8 @@ func createDefaultConfig() component.Config {
IOSBuildUUIDAttributeKey: "app.debug.build_uuid",
AppExecutableAttributeKey: "app.bundle.executable",
+ ProguardUUIDAttributeKey: "app.debug.proguard_uuid",
+
SourceMapStoreKey: fileStoreKey,
LocalSourceMaps: LocalSourceMapsConfig{Path: "."},
diff --git a/backend/app/symbolicator/otelprocessor/store.go b/backend/app/symbolicator/otelprocessor/store.go
index 55e6185d..5209c015 100644
--- a/backend/app/symbolicator/otelprocessor/store.go
+++ b/backend/app/symbolicator/otelprocessor/store.go
@@ -18,6 +18,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/android"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
"github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
)
@@ -134,6 +135,19 @@ func (a *artifactStore) getIOSDsym(ctx context.Context, uuid string) ([]byte, er
return data, nil
}
+func (a *artifactStore) androidMappingKey(proguardUuid string) string {
+ return a.key("", android.NormalizeProguardUUID(proguardUuid)+".txt")
+}
+
+func (a *artifactStore) getAndroidMapping(ctx context.Context, proguardUuid string) ([]byte, error) {
+ key := a.androidMappingKey(proguardUuid)
+ data, err := a.store.fetch(ctx, key)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find android mapping %q: %w", key, err)
+ }
+ return data, nil
+}
+
func (a *artifactStore) key(buildUUID, base string) string {
parts := make([]string, 0, 3)
if a.prefix != "" {
diff --git a/backend/app/symbolicator/otelprocessor/symbolicate.go b/backend/app/symbolicator/otelprocessor/symbolicate.go
index fe05f2aa..d7ddf1ef 100644
--- a/backend/app/symbolicator/otelprocessor/symbolicate.go
+++ b/backend/app/symbolicator/otelprocessor/symbolicate.go
@@ -7,6 +7,7 @@ import (
"math"
"strings"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/android"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
"github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
"github.com/tracewayapp/traceway/backend/app/symbolicator/sourcemap"
@@ -30,10 +31,36 @@ var errNoIOSSymbols = errors.New("no ios symbols found")
type symbolicatorProcessor struct {
cfg *Config
store *artifactStore
- cache *twcache.Cache
+ cache *twcache.Cache[cacheEntry]
logger *zap.Logger
}
+func (p *symbolicatorProcessor) getBytes(ctx context.Context, key string, load twcache.LoadFunc[cacheEntry]) ([]byte, func(), error) {
+ data, done, err := p.cache.Get(ctx, key, load)
+ if err != nil {
+ return nil, done, err
+ }
+ b, ok := data.([]byte)
+ if !ok {
+ done()
+ return nil, func() {}, fmt.Errorf("cache entry for %q is not bytes", key)
+ }
+ return b, done, nil
+}
+
+func (p *symbolicatorProcessor) getMapping(ctx context.Context, key string, load twcache.LoadFunc[cacheEntry]) (*android.Mapping, func(), error) {
+ data, done, err := p.cache.Get(ctx, key, load)
+ if err != nil {
+ return nil, done, err
+ }
+ m, ok := data.(*android.Mapping)
+ if !ok || m == nil {
+ done()
+ return nil, func() {}, fmt.Errorf("cache entry for %q is not a mapping", key)
+ }
+ return m, done, nil
+}
+
type stackFrame struct {
fn string
url string
@@ -69,6 +96,11 @@ func (p *symbolicatorProcessor) processRecord(ctx context.Context, attrs, resour
return
}
+ if isAndroidLang(lang) {
+ p.symbolicateAndroidTrace(ctx, attrs, resource, originalStack)
+ return
+ }
+
if dart.IsNonSymbolic(originalStack) {
p.symbolicateDartTrace(ctx, attrs, originalStack)
return
@@ -198,7 +230,7 @@ func (p *symbolicatorProcessor) symbolicateDartTrace(ctx context.Context, attrs
return
}
- data, done, err := p.cache.Get(ctx, key, func(ctx context.Context) ([]byte, error) {
+ data, done, err := p.getBytes(ctx, key, func(ctx context.Context) (cacheEntry, error) {
fetchCtx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
defer cancel()
elf, err := p.store.getDartSymbols(fetchCtx, trace.BuildID, arch)
@@ -295,7 +327,7 @@ func (p *symbolicatorProcessor) symbolicateIOSTrace(ctx context.Context, attrs,
}
return nil
}
- data, done, err := p.cache.Get(ctx, key, func(ctx context.Context) ([]byte, error) {
+ data, done, err := p.getBytes(ctx, key, func(ctx context.Context) (cacheEntry, error) {
fetchCtx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
defer cancel()
dsym, err := p.store.getIOSDsym(fetchCtx, debugID)
@@ -346,6 +378,96 @@ func (p *symbolicatorProcessor) renderIOSTrace(attrs pcommon.Map, trace ios.Stac
})
}
+func isAndroidLang(lang string) bool {
+ switch strings.ToLower(strings.TrimSpace(lang)) {
+ case "android", "java", "kotlin":
+ return true
+ }
+ return false
+}
+
+func (p *symbolicatorProcessor) symbolicateAndroidTrace(ctx context.Context, attrs, resource pcommon.Map, rawStack string) {
+ attrs.PutStr(p.cfg.SymbolicatorParsingMethodAttributeKey, parsingMethodParsed)
+ if p.cfg.PreserveStackTrace {
+ attrs.PutStr(p.cfg.OriginalStackTraceAttributeKey, rawStack)
+ }
+
+ proguardUUID := strAttr(resource, p.cfg.ProguardUUIDAttributeKey)
+ if proguardUUID == "" {
+ proguardUUID = strAttr(attrs, p.cfg.ProguardUUIDAttributeKey)
+ }
+
+ text := rawStack
+ resolved := false
+ var firstErr error
+
+ var dones []func()
+ defer func() {
+ for _, d := range dones {
+ d()
+ }
+ }()
+
+ if proguardUUID != "" && android.IsR8Trace(text) {
+ if p.cache.Dir() != "" {
+ key := flatCacheKey(p.store.androidMappingKey(proguardUUID))
+ if p.cache.IsNegative(key) {
+ firstErr = fmt.Errorf("no android mapping for %s", proguardUUID)
+ } else {
+ data, done, err := p.getBytes(ctx, key, func(ctx context.Context) (cacheEntry, error) {
+ fetchCtx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
+ defer cancel()
+ raw, err := p.store.getAndroidMapping(fetchCtx, proguardUUID)
+ if err != nil {
+ return nil, err
+ }
+ return android.BuildR8Flat(string(raw)), nil
+ })
+ if err != nil {
+ firstErr = err
+ } else {
+ dones = append(dones, done)
+ text = android.RetraceFlat(data, text)
+ resolved = true
+ }
+ }
+ } else {
+ key := p.store.androidMappingKey(proguardUUID)
+ if p.cache.IsNegative(key) {
+ firstErr = fmt.Errorf("no android mapping for %s", proguardUUID)
+ } else {
+ m, done, err := p.getMapping(ctx, key, func(ctx context.Context) (cacheEntry, error) {
+ fetchCtx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
+ defer cancel()
+ raw, err := p.store.getAndroidMapping(fetchCtx, proguardUUID)
+ if err != nil {
+ return nil, err
+ }
+ return android.ParseMapping(string(raw)), nil
+ })
+ if err != nil {
+ firstErr = err
+ } else if m != nil {
+ dones = append(dones, done)
+ text = m.Retrace(text)
+ resolved = true
+ }
+ }
+ }
+ }
+
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, text)
+ if resolved {
+ attrs.PutBool(p.cfg.SymbolicatorFailureAttributeKey, false)
+ } else {
+ attrs.PutBool(p.cfg.SymbolicatorFailureAttributeKey, true)
+ if firstErr != nil {
+ attrs.PutStr(p.cfg.SymbolicatorErrorAttributeKey, firstErr.Error())
+ }
+ }
+ p.putProcessorMeta(attrs)
+}
+
func (p *symbolicatorProcessor) languageAllowed(attrs, resource pcommon.Map) bool {
if len(p.cfg.AllowedLanguages) == 0 {
return true
@@ -420,7 +542,7 @@ func (p *symbolicatorProcessor) symbolicateFrame(ctx context.Context, f stackFra
if p.cache.IsNegative(key) {
return frameResult{err: fmt.Errorf("no source map for %s", f.url)}
}
- data, done, err := p.cache.Get(ctx, key, func(ctx context.Context) ([]byte, error) {
+ data, done, err := p.getBytes(ctx, key, func(ctx context.Context) (cacheEntry, error) {
fetchCtx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
defer cancel()
source, sourceMap, err := p.store.getSourceAndMap(fetchCtx, f.url, buildUUID)
diff --git a/backend/app/symbolicator/twcache/mem.go b/backend/app/symbolicator/twcache/mem.go
index 0ad7443c..4ffb9e63 100644
--- a/backend/app/symbolicator/twcache/mem.go
+++ b/backend/app/symbolicator/twcache/mem.go
@@ -5,7 +5,7 @@ import (
"sync"
)
-type twcachemem struct {
+type twcachemem[V any] struct {
mu sync.Mutex
items map[string]*list.Element
order *list.List
@@ -13,60 +13,63 @@ type twcachemem struct {
maxBytes int64
curBytes int64
evictions uint64
+ weigh func(V) int64
}
-type memEntry struct {
+type memEntry[V any] struct {
name string
- data []byte
+ data V
size int64
}
-func newMemStore(maxEntries int, maxBytes int64) *twcachemem {
- return &twcachemem{
+func newMemStore[V any](maxEntries int, maxBytes int64, weigh func(V) int64) *twcachemem[V] {
+ return &twcachemem[V]{
items: make(map[string]*list.Element),
order: list.New(),
maxEntries: maxEntries,
maxBytes: maxBytes,
+ weigh: weigh,
}
}
-func (s *twcachemem) get(name string) ([]byte, func(), bool) {
+func (s *twcachemem[V]) get(name string) (V, func(), bool) {
s.mu.Lock()
defer s.mu.Unlock()
el, ok := s.items[name]
if !ok {
- return nil, noop, false
+ var zero V
+ return zero, noop, false
}
s.order.MoveToFront(el)
- return el.Value.(*memEntry).data, noop, true
+ return el.Value.(*memEntry[V]).data, noop, true
}
-func (s *twcachemem) contains(name string) bool {
+func (s *twcachemem[V]) contains(name string) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.items[name]
return ok
}
-func (s *twcachemem) put(name string, data []byte) error {
+func (s *twcachemem[V]) put(name string, data V) error {
s.mu.Lock()
defer s.mu.Unlock()
- size := int64(len(data))
+ size := s.weigh(data)
if el, ok := s.items[name]; ok {
- e := el.Value.(*memEntry)
+ e := el.Value.(*memEntry[V])
s.curBytes += size - e.size
e.data = data
e.size = size
s.order.MoveToFront(el)
} else {
- s.items[name] = s.order.PushFront(&memEntry{name: name, data: data, size: size})
+ s.items[name] = s.order.PushFront(&memEntry[V]{name: name, data: data, size: size})
s.curBytes += size
}
s.evictLocked()
return nil
}
-func (s *twcachemem) remove(name string) {
+func (s *twcachemem[V]) remove(name string) {
s.mu.Lock()
defer s.mu.Unlock()
if el, ok := s.items[name]; ok {
@@ -74,7 +77,7 @@ func (s *twcachemem) remove(name string) {
}
}
-func (s *twcachemem) setLimits(maxEntries int, maxBytes int64) {
+func (s *twcachemem[V]) setLimits(maxEntries int, maxBytes int64) {
s.mu.Lock()
defer s.mu.Unlock()
if maxEntries > 0 {
@@ -86,13 +89,13 @@ func (s *twcachemem) setLimits(maxEntries int, maxBytes int64) {
s.evictLocked()
}
-func (s *twcachemem) dropLocked(el *list.Element) {
- e := s.order.Remove(el).(*memEntry)
+func (s *twcachemem[V]) dropLocked(el *list.Element) {
+ e := s.order.Remove(el).(*memEntry[V])
delete(s.items, e.name)
s.curBytes -= e.size
}
-func (s *twcachemem) evictLocked() {
+func (s *twcachemem[V]) evictLocked() {
for s.order.Len() > s.maxEntries || s.curBytes > s.maxBytes {
back := s.order.Back()
if back == nil {
@@ -103,7 +106,7 @@ func (s *twcachemem) evictLocked() {
}
}
-func (s *twcachemem) stats() storeStats {
+func (s *twcachemem[V]) stats() storeStats {
s.mu.Lock()
defer s.mu.Unlock()
return storeStats{
@@ -116,4 +119,4 @@ func (s *twcachemem) stats() storeStats {
}
}
-func (s *twcachemem) dir() string { return "" }
+func (s *twcachemem[V]) dir() string { return "" }
diff --git a/backend/app/symbolicator/twcache/twcache.go b/backend/app/symbolicator/twcache/twcache.go
index 0b395996..fceda765 100644
--- a/backend/app/symbolicator/twcache/twcache.go
+++ b/backend/app/symbolicator/twcache/twcache.go
@@ -19,13 +19,13 @@ const (
var ErrInvalidName = errors.New("twcache: cache name escapes the cache directory")
-type LoadFunc func(ctx context.Context) ([]byte, error)
+type LoadFunc[V any] func(ctx context.Context) (V, error)
-type store interface {
- get(name string) (data []byte, done func(), ok bool)
+type store[V any] interface {
+ get(name string) (data V, done func(), ok bool)
contains(name string) bool
- put(name string, data []byte) error
+ put(name string, data V) error
remove(name string)
setLimits(maxEntries int, maxBytes int64)
stats() storeStats
@@ -43,17 +43,17 @@ type storeStats struct {
func noop() {}
-type Cache struct {
+type Cache[V any] struct {
name string
- store store
+ store store[V]
warn func(error)
NotFound func(error) bool
- Validate func([]byte) bool
+ Validate func(V) bool
mu sync.Mutex
- loading map[string]*cacheLoad
+ loading map[string]*cacheLoad[V]
negative map[string]*negEntry
negativeHits uint64
lastParseMs float64
@@ -71,26 +71,31 @@ type negEntry struct {
failures uint32
}
-type cacheLoad struct {
+type cacheLoad[V any] struct {
done chan struct{}
err error
+ blob V
}
-func newCache(s store, warn func(error)) *Cache {
- return &Cache{
+func newCache[V any](s store[V], warn func(error)) *Cache[V] {
+ return &Cache[V]{
name: "symbolication artifact",
store: s,
warn: warn,
- loading: make(map[string]*cacheLoad),
+ loading: make(map[string]*cacheLoad[V]),
negative: make(map[string]*negEntry),
}
}
-func NewMem(maxEntries int, maxBytes int64) *Cache {
- return newCache(newMemStore(maxEntries, maxBytes), nil)
+func NewMem(maxEntries int, maxBytes int64) *Cache[[]byte] {
+ return newCache(newMemStore(maxEntries, maxBytes, func(b []byte) int64 { return int64(len(b)) }), nil)
}
-func NewDisk(dir string, maxBytes int64, warn func(error)) (*Cache, error) {
+func NewMemFunc[V any](maxEntries int, maxBytes int64, weigh func(V) int64) *Cache[V] {
+ return newCache(newMemStore(maxEntries, maxBytes, weigh), nil)
+}
+
+func NewDisk(dir string, maxBytes int64, warn func(error)) (*Cache[[]byte], error) {
s, err := newDiskStore(dir, maxBytes, warn)
if err != nil {
return nil, err
@@ -98,15 +103,50 @@ func NewDisk(dir string, maxBytes int64, warn func(error)) (*Cache, error) {
return newCache(s, warn), nil
}
-func (c *Cache) SetWarn(warn func(error)) { c.warn = warn }
+type anyDiskStore struct{ inner *twcachedisk }
+
+func (a anyDiskStore) get(name string) (any, func(), bool) {
+ b, done, ok := a.inner.get(name)
+ if !ok {
+ return nil, noop, false
+ }
+ return b, done, true
+}
+
+func (a anyDiskStore) contains(name string) bool { return a.inner.contains(name) }
-func (c *Cache) SetLimits(maxEntries int, maxBytes int64) {
+func (a anyDiskStore) put(name string, data any) error {
+ b, ok := data.([]byte)
+ if !ok {
+ return nil
+ }
+ return a.inner.put(name, b)
+}
+
+func (a anyDiskStore) remove(name string) { a.inner.remove(name) }
+func (a anyDiskStore) setLimits(maxEntries int, maxBytes int64) {
+ a.inner.setLimits(maxEntries, maxBytes)
+}
+func (a anyDiskStore) stats() storeStats { return a.inner.stats() }
+func (a anyDiskStore) dir() string { return a.inner.dir() }
+
+func NewDiskAny(dir string, maxBytes int64, warn func(error)) (*Cache[any], error) {
+ s, err := newDiskStore(dir, maxBytes, warn)
+ if err != nil {
+ return nil, err
+ }
+ return newCache(anyDiskStore{inner: s}, warn), nil
+}
+
+func (c *Cache[V]) SetWarn(warn func(error)) { c.warn = warn }
+
+func (c *Cache[V]) SetLimits(maxEntries int, maxBytes int64) {
c.store.setLimits(maxEntries, maxBytes)
}
-func (c *Cache) Dir() string { return c.store.dir() }
+func (c *Cache[V]) Dir() string { return c.store.dir() }
-func (c *Cache) Get(ctx context.Context, key string, load LoadFunc) (data []byte, done func(), err error) {
+func (c *Cache[V]) Get(ctx context.Context, key string, load LoadFunc[V]) (V, func(), error) {
if data, done, ok := c.store.get(key); ok {
if c.Validate == nil || c.Validate(data) {
c.hits.Add(1)
@@ -116,33 +156,29 @@ func (c *Cache) Get(ctx context.Context, key string, load LoadFunc) (data []byte
done()
c.store.remove(key)
}
- if err := c.ensureBuilt(ctx, key, load); err != nil {
- return nil, noop, err
- }
- if data, done, ok := c.store.get(key); ok {
- return data, done, nil
- }
- return nil, noop, fmt.Errorf("%s: %q evicted before use", c.name, key)
+ return c.ensureBuilt(ctx, key, load)
}
-func (c *Cache) ensureBuilt(ctx context.Context, key string, load LoadFunc) error {
+func (c *Cache[V]) ensureBuilt(ctx context.Context, key string, load LoadFunc[V]) (V, func(), error) {
+ var zero V
c.mu.Lock()
if l, ok := c.loading[key]; ok {
c.mu.Unlock()
<-l.done
- if l.err == nil {
- c.hits.Add(1)
+ if l.err != nil {
+ return zero, noop, l.err
}
- return l.err
+ c.hits.Add(1)
+ return l.blob, noop, nil
}
- if c.store.contains(key) {
+ if data, done, ok := c.store.get(key); ok {
c.mu.Unlock()
c.hits.Add(1)
- return nil
+ return data, done, nil
}
c.misses.Add(1)
- l := &cacheLoad{done: make(chan struct{})}
+ l := &cacheLoad[V]{done: make(chan struct{})}
c.loading[key] = l
c.mu.Unlock()
@@ -160,6 +196,7 @@ func (c *Cache) ensureBuilt(ctx context.Context, key string, load LoadFunc) erro
l.err = lerr
return
}
+ l.blob = blob
l.err = c.store.put(key, blob)
}()
@@ -174,17 +211,20 @@ func (c *Cache) ensureBuilt(ctx context.Context, key string, load LoadFunc) erro
c.mu.Unlock()
close(l.done)
- if l.err != nil && !c.isNotFound(l.err) {
- c.reportFailure(l.err)
+ if l.err != nil {
+ if !c.isNotFound(l.err) {
+ c.reportFailure(l.err)
+ }
+ return zero, noop, l.err
}
- return l.err
+ return l.blob, noop, nil
}
-func (c *Cache) isNotFound(err error) bool {
+func (c *Cache[V]) isNotFound(err error) bool {
return c.NotFound == nil || c.NotFound(err)
}
-func (c *Cache) IsNegative(key string) bool {
+func (c *Cache[V]) IsNegative(key string) bool {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.negative[key]
@@ -195,14 +235,14 @@ func (c *Cache) IsNegative(key string) bool {
return true
}
-func (c *Cache) Invalidate(key string) {
+func (c *Cache[V]) Invalidate(key string) {
c.mu.Lock()
delete(c.negative, key)
c.mu.Unlock()
c.store.remove(key)
}
-func (c *Cache) markNegativeLocked(key string, loadErr error) {
+func (c *Cache[V]) markNegativeLocked(key string, loadErr error) {
base := transientNegativeTTL
if c.isNotFound(loadErr) {
base = negativeBaseTTL
@@ -223,7 +263,7 @@ func (c *Cache) markNegativeLocked(key string, loadErr error) {
e.expiresAt = time.Now().Add(ttl)
}
-func (c *Cache) pruneNegativeLocked() {
+func (c *Cache[V]) pruneNegativeLocked() {
now := time.Now()
for k, e := range c.negative {
if now.After(e.expiresAt) {
@@ -238,7 +278,7 @@ func (c *Cache) pruneNegativeLocked() {
}
}
-func (c *Cache) reportFailure(err error) {
+func (c *Cache[V]) reportFailure(err error) {
var report uint64
c.mu.Lock()
c.failuresSinceReport++
@@ -269,7 +309,7 @@ type Stats struct {
LastParseMs float64
}
-func (c *Cache) Stats() Stats {
+func (c *Cache[V]) Stats() Stats {
ss := c.store.stats()
c.mu.Lock()
negEntries := len(c.negative)
diff --git a/backend/app/symbolicator/twcache/twcache_test.go b/backend/app/symbolicator/twcache/twcache_test.go
index 9f90f61e..0363edb6 100644
--- a/backend/app/symbolicator/twcache/twcache_test.go
+++ b/backend/app/symbolicator/twcache/twcache_test.go
@@ -3,12 +3,13 @@ package twcache
import (
"context"
"errors"
+ "strconv"
"sync"
"sync/atomic"
"testing"
)
-func blobLoad(data []byte, calls *atomic.Int64) LoadFunc {
+func blobLoad(data []byte, calls *atomic.Int64) LoadFunc[[]byte] {
return func(ctx context.Context) ([]byte, error) {
if calls != nil {
calls.Add(1)
@@ -17,13 +18,13 @@ func blobLoad(data []byte, calls *atomic.Int64) LoadFunc {
}
}
-func caches(t *testing.T) map[string]*Cache {
+func caches(t *testing.T) map[string]*Cache[[]byte] {
t.Helper()
disk, err := NewDisk(t.TempDir(), 64<<20, nil)
if err != nil {
t.Fatal(err)
}
- return map[string]*Cache{
+ return map[string]*Cache[[]byte]{
"mem": NewMem(100, 64<<20),
"disk": disk,
}
@@ -158,3 +159,90 @@ func TestNegativeAndInvalidate(t *testing.T) {
})
}
}
+
+func TestGetSurvivesEvictionRace(t *testing.T) {
+ ctx := context.Background()
+ c := NewMem(1<<20, 48<<10)
+ payload := make([]byte, 4<<10)
+ const goroutines = 32
+ const iters = 3000
+ const keyspace = 64
+ var fails atomic.Int64
+ var wg sync.WaitGroup
+ for g := 0; g < goroutines; g++ {
+ wg.Add(1)
+ go func(g int) {
+ defer wg.Done()
+ for i := 0; i < iters; i++ {
+ key := "k" + strconv.Itoa((g*7+i)%keyspace) + ".tw"
+ _, done, err := c.Get(ctx, key, blobLoad(payload, nil))
+ if err != nil {
+ fails.Add(1)
+ continue
+ }
+ done()
+ }
+ }(g)
+ }
+ wg.Wait()
+ if n := fails.Load(); n != 0 {
+ t.Errorf("%d of %d Gets failed under eviction pressure; the bounded retry should resolve every present key", n, goroutines*iters)
+ }
+}
+
+func TestMemFuncOnePoolAcrossKinds(t *testing.T) {
+ type obj struct{ n int64 }
+ weigh := func(v any) int64 {
+ switch t := v.(type) {
+ case []byte:
+ return int64(len(t))
+ case *obj:
+ return t.n
+ default:
+ return 0
+ }
+ }
+ ctx := context.Background()
+
+ c := NewMemFunc[any](100, 1<<20, weigh)
+ b, doneB, err := c.Get(ctx, "bytes", func(context.Context) (any, error) { return []byte("hello"), nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, ok := b.([]byte); !ok || string(got) != "hello" {
+ t.Fatalf("bytes entry: got %#v", b)
+ }
+ doneB()
+
+ o, doneO, err := c.Get(ctx, "obj", func(context.Context) (any, error) { return &obj{n: 42}, nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, ok := o.(*obj); !ok || got.n != 42 {
+ t.Fatalf("obj entry: got %#v", o)
+ }
+ doneO()
+
+ st := c.Stats()
+ if st.Entries != 2 {
+ t.Errorf("entries: got %d, want 2 (one pool holds both kinds)", st.Entries)
+ }
+ if want := int64(len("hello")) + 42; st.Bytes != want {
+ t.Errorf("bytes: got %d, want %d (budget summed across kinds)", st.Bytes, want)
+ }
+
+ small := NewMemFunc[any](100, 50, weigh)
+ if _, done, err := small.Get(ctx, "b", func(context.Context) (any, error) { return make([]byte, 40), nil }); err != nil {
+ t.Fatal(err)
+ } else {
+ done()
+ }
+ if _, done, err := small.Get(ctx, "o", func(context.Context) (any, error) { return &obj{n: 40}, nil }); err != nil {
+ t.Fatal(err)
+ } else {
+ done()
+ }
+ if s := small.Stats(); s.Entries != 1 || s.Bytes != 40 {
+ t.Errorf("cross-kind eviction: got entries=%d bytes=%d, want entries=1 bytes=40", s.Entries, s.Bytes)
+ }
+}
diff --git a/benchmarks/processor/README.md b/benchmarks/processor/README.md
index cf7d7d8f..ab265a03 100644
--- a/benchmarks/processor/README.md
+++ b/benchmarks/processor/README.md
@@ -40,6 +40,9 @@ stacktraces/sec; the drain's symbolicated percentage is the correctness check.
| `traceway-ios-mem` | otelcol-bench-traceway | DWARF flatten | in-memory `.tw` only |
| `traceway-ios-disk` | otelcol-bench-traceway | DWARF flatten | mmap'd `.tw` disk tier |
| `honeycomb-ios` | otelcol-bench-honeycomb | symbolic (cgo) | RAM LRU, entry-count bound |
+| `traceway-android-mem` | otelcol-bench-traceway | R8 retrace | in-memory mapping only |
+| `traceway-android-disk` | otelcol-bench-traceway | R8 retrace | mmap'd `.tw` disk tier |
+| `honeycomb-android` | otelcol-bench-honeycomb | symbolic (cgo) | RAM LRU, entry-count bound |
One traceway binary (built with `-tags oxc`) serves all variants; language
(JS source maps vs. Dart symbols), parser, and cache mode are runtime config.
@@ -52,7 +55,8 @@ JS-only.
`benchmark-processor` takes a `language` input: `js` (the 5 JS impls incl.
Honeycomb), `dart` (the two `traceway-dart-*` impls), `ios` (the two
-`traceway-ios-*` impls), or `both` (js+dart). Locally, just list the impls in
+`traceway-ios-*` impls), `android` (`honeycomb-android` + the two
+`traceway-android-*` impls), or `both` (js+dart). Locally, just list the impls in
`IMPLS`. The Dart corpus replicates a committed seed
(`seeds/dart/app.debug.elf`, a real pure-Dart AOT `.symbols` ELF + its trace)
under N synthetic build-ids — hardlinked, so N builds cost ~one inode — so the
@@ -78,6 +82,17 @@ that exact Honeycomb frame format too (`ios.ParseHoneycombTrace`, routed for bot
traces and logs), so the same input shape resolves on both engines. Drain markers:
`sample.c` resolved vs. `sample+0x` unresolved.
+The Android impls compare R8/ProGuard retrace head-to-head. A committed
+`mapping.txt` seed (`seeds/android/mapping.txt`, the `r8-app` fixture) is written
+under N synthetic ProGuard UUIDs as `<uuid>.txt`, hardlinked when unpadded so N
+builds cost one inode. Both engines key the mapping by UUID and read the identical
+flat `<STORE_PATH>/<uuid>.txt` store, so a single corpus serves both (no per-engine
+layout split, unlike iOS). Honeycomb's `proguard_symbolicator` is logs-only, so all
+three Android impls send OTLP logs carrying a `app.debug.proguard_uuid` resource
+attribute and an obfuscated `exception.stacktrace`; Traceway's processor
+auto-routes the R8 trace via `telemetry.sdk.language=android`. Drain markers:
+`.kt:` resolved vs. `SourceFile:` unresolved.
+
## Scenarios
- `hot`: one bundle, always cache-warm. Pure resolve throughput ramp.
@@ -103,7 +118,10 @@ small `OOM_CACHE` (128 by default, well under the corpus) under sustained load o
the small SUT. That is where per-dSYM cost shows up. Honeycomb's `symbolic` archive
is heavyweight and its memory grows under sustained eviction (reaching multiple GB
on a long run), so the small SUT eventually tips over; Traceway re-opens its compact
-`.tw` and stays flat. `hot` and `churn` are unchanged across languages.
+`.tw` and stays flat. Android `oom` caps the cache at `OOM_CACHE` (128 by default)
+like iOS, an eviction soak, but pads each `mapping.txt` to MB scale via
+`OOM_MAP_PAD_KB` (the synthetic class blocks never collide with the seed's frames,
+so retrace output is unchanged). `hot` and `churn` are unchanged across languages.
Corpus entries are the real minified node-app bundle padded with `--pad-kb`
of valid JS (default 256 KB) so scope-analysis parse cost is realistic. The
@@ -124,8 +142,13 @@ timeline, not a single number.
IMPLS="traceway-oxc-mem traceway-goja-mem honeycomb" SCENARIOS=churn CONNECTIONS=4,16,64 ./run-local.sh
IMPLS="traceway-dart-mem traceway-dart-disk" SCENARIOS="hot churn" ./run-local.sh # Dart
IMPLS="honeycomb-ios traceway-ios-mem traceway-ios-disk" SCENARIOS="hot churn" ./run-local.sh # iOS head-to-head
+IMPLS="honeycomb-android traceway-android-mem traceway-android-disk" SCENARIOS="hot churn" ./run-local.sh # Android R8 head-to-head
```
+Run one impl at a time locally if you hit `connect: can't assign requested
+address`: a fast Android run can churn enough collector-to-drain connections to
+exhaust the host's ephemeral ports. Hetzner runs (separate boxes) are unaffected.
+
Needs go, cargo, node, jq. Builds both collectors (the Traceway one with
`-tags oxc` after `scripts/build-oxc-shim.sh`), drain, loadgen, corpusgen,
then runs the matrix on localhost and prints a summary table. Results land
@@ -153,7 +176,15 @@ then runs the impls as parallel matrix entries, each on its own Hetzner server
pair. Needs the `HCLOUD_TOKEN` secret. The `language` input selects the matrix:
`js` (the 5 JS impls), `dart` (`traceway-dart-mem`/`-disk`), or `both`. Results
are uploaded as `results-<impl>` artifacts. `ios` runs `honeycomb-ios` alongside
-the two `traceway-ios` impls.
+the two `traceway-ios` impls; `android` runs `honeycomb-android` alongside the two
+`traceway-android` impls.
+
+`max-parallel: 3` caps concurrent matrix entries at 3. Each entry holds one SUT
+(`ccx33`, 8 dedicated vCPUs during `hot`/`churn`) plus one shared-vCPU loadgen
+(`cpx42`), so peak usage is 24 dedicated vCPUs and 6 servers. The Hetzner project
+quota must cover both: a dedicated-vCPU limit < 24 or a server limit < 6 fails the
+extra entries with `resource_limit_exceeded`. Keep the loadgen on a shared-vCPU
+type so it stays off the dedicated-vCPU quota.
## Knobs
@@ -162,7 +193,7 @@ the two `traceway-ios` impls.
| `IMPLS` | `traceway-oxc honeycomb` | run-local.sh only; `traceway-goja` selects the goja parser in the same oxc-built binary |
| `SCENARIOS` | `hot churn` | |
| `CHURN_ENTRIES` | `512` | corpus size for churn |
-| `OOM_CACHE` | corpus size (js/dart), `128` (ios) | resolver cache size for oom; iOS uses a bounded cache so oom is an eviction soak rather than a resident-corpus test |
+| `OOM_CACHE` | corpus size (js/dart), `128` (ios/android) | resolver cache size for oom; iOS and Android use a bounded cache so oom is an eviction soak rather than a resident-corpus test |
| `PAD_KB` | `256` | padding per bundle |
| `CONNECTIONS` | ramp | comma list of concurrency steps |
| `STEP_DURATION` | `30s` local, `60s` hetzner | time per step |
diff --git a/benchmarks/processor/config-honeycomb-android.yaml b/benchmarks/processor/config-honeycomb-android.yaml
new file mode 100644
index 00000000..48fb1def
--- /dev/null
+++ b/benchmarks/processor/config-honeycomb-android.yaml
@@ -0,0 +1,33 @@
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+
+processors:
+ proguard_symbolicator:
+ proguard_store: file_store
+ local_store:
+ path: ${env:STORE_PATH}
+ proguard_cache_size: ${env:CACHE_SIZE:-128}
+ preserve_stack_trace: false
+ allowed_languages: [android]
+
+exporters:
+ otlphttp/drain:
+ endpoint: ${env:DRAIN_ENDPOINT}
+ compression: none
+ sending_queue:
+ enabled: false
+ retry_on_failure:
+ enabled: false
+
+service:
+ telemetry:
+ metrics:
+ level: none
+ pipelines:
+ logs:
+ receivers: [otlp]
+ processors: [proguard_symbolicator]
+ exporters: [otlphttp/drain]
diff --git a/benchmarks/processor/config-traceway.yaml b/benchmarks/processor/config-traceway.yaml
index 7dba1700..70ac90d4 100644
--- a/benchmarks/processor/config-traceway.yaml
+++ b/benchmarks/processor/config-traceway.yaml
@@ -32,3 +32,7 @@ service:
receivers: [otlp]
processors: [source_map_symbolicator]
exporters: [otlphttp/drain]
+ logs:
+ receivers: [otlp]
+ processors: [source_map_symbolicator]
+ exporters: [otlphttp/drain]
diff --git a/benchmarks/processor/corpusgen/main.go b/benchmarks/processor/corpusgen/main.go
index 0634ddf4..f12aa1e8 100644
--- a/benchmarks/processor/corpusgen/main.go
+++ b/benchmarks/processor/corpusgen/main.go
@@ -173,7 +173,8 @@ func main() {
symbols := flag.String("symbols", "seeds/dart/app.debug.elf", "dart: seed .symbols/.elf")
dsym := flag.String("dsym", "seeds/ios/app.dsym", "ios: seed dSYM (Mach-O DWARF)")
binary := flag.String("binary", "sample", "honeycomb-ios: Mach-O name inside the .dSYM bundle")
- traceFile := flag.String("trace", "seeds/dart/trace.txt", "dart/ios: seed non-symbolic trace")
+ mapping := flag.String("mapping", "seeds/android/mapping.txt", "android: seed R8 mapping.txt")
+ traceFile := flag.String("trace", "seeds/dart/trace.txt", "dart/ios/android: seed non-symbolic trace")
entries := flag.Int("entries", 1, "")
padKB := flag.Int("pad-kb", 256, "")
mapPadKB := flag.Int("map-pad-kb", 0, "")
@@ -196,6 +197,10 @@ func main() {
generateHoneycombIOS(*out, *dsym, *traceFile, *binary, *entries)
return
}
+ if *language == "android" {
+ generateAndroid(*out, *mapping, *traceFile, *mapPadKB, *entries)
+ return
+ }
bundleBytes, err := os.ReadFile(*bundle)
if err != nil {
@@ -328,6 +333,58 @@ func substituteIOSUUID(trace, uuid string) string {
return iosFrameUUIDRe.ReplaceAllString(trace, "${1}"+uuid+"${2}")
}
+func generateAndroid(out, mappingPath, tracePath string, mapPadKB, entries int) {
+ base, err := os.ReadFile(mappingPath)
+ if err != nil {
+ panic(fmt.Errorf("reading android seed mapping %q: %w", mappingPath, err))
+ }
+ trace, err := os.ReadFile(tracePath)
+ if err != nil {
+ panic(fmt.Errorf("reading android seed trace %q: %w", tracePath, err))
+ }
+ absSeed, err := filepath.Abs(mappingPath)
+ if err != nil {
+ panic(err)
+ }
+
+ c := dartCorpus{Language: "android"}
+ for n := 0; n < entries; n++ {
+ uuid := fmt.Sprintf("%032x", n)
+ dest := filepath.Join(out, uuid+".txt")
+ _ = os.Remove(dest)
+ if mapPadKB > 0 {
+ if err := os.WriteFile(dest, padMapping(base, mapPadKB, n), 0o644); err != nil {
+ panic(err)
+ }
+ } else if err := os.Link(absSeed, dest); err != nil {
+ if werr := os.WriteFile(dest, base, 0o644); werr != nil {
+ panic(werr)
+ }
+ }
+ c.Builds = append(c.Builds, dartBuild{BuildID: uuid, Trace: string(trace)})
+ }
+ data, _ := json.MarshalIndent(c, "", " ")
+ if err := os.WriteFile(filepath.Join(out, "corpus.json"), data, 0o644); err != nil {
+ panic(err)
+ }
+ fmt.Printf("wrote %d android builds (map-pad %d KB, seed %s) to %s\n", entries, mapPadKB, mappingPath, out)
+}
+
+func padMapping(base []byte, kb, seed int) []byte {
+ var b strings.Builder
+ b.Write(base)
+ if len(base) > 0 && base[len(base)-1] != '\n' {
+ b.WriteByte('\n')
+ }
+ target := len(base) + kb*1024
+ for i := 0; b.Len() < target; i++ {
+ fmt.Fprintf(&b, "benchpad.S%dClass%d -> twbp_%d_%d:\n", seed, i, seed, i)
+ b.WriteString(" 1:1:void run():1:1 -> a\n")
+ b.WriteString(" 2:2:int compute(int):2:2 -> b\n")
+ }
+ return []byte(b.String())
+}
+
var twFrameRe = regexp.MustCompile(`^\s*#(\d+)\s+([0-9a-fA-F]{32})\s+0x([0-9a-fA-F]+)\s+(\S+)\s*$`)
func hyphenateUUID(hex32 string) string {
diff --git a/benchmarks/processor/loadgen/main.go b/benchmarks/processor/loadgen/main.go
index 21fc3255..cd5056be 100644
--- a/benchmarks/processor/loadgen/main.go
+++ b/benchmarks/processor/loadgen/main.go
@@ -70,6 +70,28 @@ func buildBodyHoneycombIOSLogs(trace, binaryName, buildUUID string, records int)
return data
}
+func buildBodyAndroidLogs(trace, proguardUUID string, records int) []byte {
+ ld := plog.NewLogs()
+ rl := ld.ResourceLogs().AppendEmpty()
+ res := rl.Resource().Attributes()
+ res.PutStr("service.name", "processor-bench")
+ res.PutStr("telemetry.sdk.language", "android")
+ res.PutStr("app.debug.proguard_uuid", proguardUUID)
+ sl := rl.ScopeLogs().AppendEmpty()
+ for i := 0; i < records; i++ {
+ lr := sl.LogRecords().AppendEmpty()
+ lr.Attributes().PutStr("exception.type", "PaymentDeclinedException")
+ lr.Attributes().PutStr("exception.message", "bench")
+ lr.Attributes().PutStr("exception.stacktrace", trace)
+ }
+ req := plogotlp.NewExportRequestFromLogs(ld)
+ data, err := req.MarshalProto()
+ if err != nil {
+ panic(err)
+ }
+ return data
+}
+
func buildBody(lang, excType, excMsg, stack string, spans int) []byte {
td := ptrace.NewTraces()
rs := td.ResourceSpans().AppendEmpty()
@@ -155,6 +177,11 @@ func main() {
for i, b := range c.Builds {
bodies[i] = buildBodyHoneycombIOSLogs(b.Trace, c.BinaryName, b.BuildID, *spansPerReq)
}
+ case "android":
+ bodies = make([][]byte, len(c.Builds))
+ for i, b := range c.Builds {
+ bodies[i] = buildBodyAndroidLogs(b.Trace, b.BuildID, *spansPerReq)
+ }
default:
bodies = make([][]byte, len(c.Urls))
for i, u := range c.Urls {
diff --git a/benchmarks/processor/manifest-honeycomb.yaml b/benchmarks/processor/manifest-honeycomb.yaml
index 1f7c0862..e15d1831 100644
--- a/benchmarks/processor/manifest-honeycomb.yaml
+++ b/benchmarks/processor/manifest-honeycomb.yaml
@@ -11,6 +11,7 @@ processors:
- gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.143.0
- gomod: github.com/honeycombio/opentelemetry-collector-symbolicator/sourcemapprocessor v1.0.3
- gomod: github.com/honeycombio/opentelemetry-collector-symbolicator/dsymprocessor v1.0.2
+ - gomod: github.com/honeycombio/opentelemetry-collector-symbolicator/proguardprocessor v1.0.1
exporters:
- gomod: go.opentelemetry.io/collector/exporter/otlphttpexporter v0.143.0
diff --git a/benchmarks/processor/run-hetzner.sh b/benchmarks/processor/run-hetzner.sh
index afd1eccf..1da85bbe 100755
--- a/benchmarks/processor/run-hetzner.sh
+++ b/benchmarks/processor/run-hetzner.sh
@@ -3,7 +3,7 @@ set -euo pipefail
cd "$(dirname "$0")"
-IMPL="${1:?usage: run-hetzner.sh <impl> (honeycomb, traceway-oxc-mem/-disk, traceway-goja-mem/-disk, traceway-dart-mem/-disk, traceway-ios-mem/-disk, honeycomb-ios)}"
+IMPL="${1:?usage: run-hetzner.sh <impl> (honeycomb, traceway-oxc-mem/-disk, traceway-goja-mem/-disk, traceway-dart-mem/-disk, traceway-ios-mem/-disk, honeycomb-ios, traceway-android-mem/-disk, honeycomb-android)}"
SCENARIOS="${SCENARIOS:-hot churn oom}"
CHURN_ENTRIES="${CHURN_ENTRIES:-512}"
PAD_KB="${PAD_KB:-256}"
@@ -38,18 +38,22 @@ case "$IMPL" in
traceway-ios-mem) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=; LANG=ios ;;
traceway-ios-disk) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=1; LANG=ios ;;
honeycomb-ios) COL_BIN=otelcol-bench-honeycomb; COL_CFG=config-honeycomb-ios.yaml; PARSER=goja; DISK=; LANG=honeycomb-ios; SIGNAL=logs ;;
+ traceway-android-mem) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=; LANG=android; SIGNAL=logs ;;
+ traceway-android-disk) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=1; LANG=android; SIGNAL=logs ;;
+ honeycomb-android) COL_BIN=otelcol-bench-honeycomb; COL_CFG=config-honeycomb-android.yaml; PARSER=goja; DISK=; LANG=android; SIGNAL=logs ;;
*) echo "unknown impl $IMPL" >&2; exit 1 ;;
esac
case "$LANG" in
dart) OK_MARKER=crash.dart; FAIL_MARKER=_kDartIsolateSnapshotInstructions ;;
ios|honeycomb-ios) OK_MARKER=sample.c; FAIL_MARKER=sample+0x ;;
+ android) OK_MARKER=.kt:; FAIL_MARKER=SourceFile: ;;
*) OK_MARKER=../src/inventory.js; FAIL_MARKER=.mjs:1: ;;
esac
scenario_params() {
local oom_cache="$OOM_ENTRIES"
- case "$LANG" in ios|honeycomb-ios) oom_cache="${OOM_CACHE:-128}" ;; esac
+ case "$LANG" in ios|honeycomb-ios|android) oom_cache="${OOM_CACHE:-128}" ;; esac
case "$1" in
hot) echo "1 $PAD_KB 0:0 128 $CONNECTIONS $STEP_DURATION $SUT_TYPE" ;;
churn) echo "$CHURN_ENTRIES $PAD_KB 0:0 128 $CONNECTIONS $STEP_DURATION $SUT_TYPE" ;;
@@ -117,6 +121,7 @@ for scenario in $SCENARIOS; do
dart) corpusgen_cmd="./corpusgen --language dart --symbols seeds/dart/app.debug.elf --trace seeds/dart/trace.txt --entries $entries --out corpus-$scenario" ;;
ios) corpusgen_cmd="./corpusgen --language ios --dsym seeds/ios/app.dsym --trace seeds/ios/trace.txt --entries $entries --out corpus-$scenario" ;;
honeycomb-ios) corpusgen_cmd="./corpusgen --language honeycomb-ios --dsym seeds/ios/app.dsym --trace seeds/ios/trace.txt --binary sample --entries $entries --out corpus-$scenario" ;;
+ android) corpusgen_cmd="./corpusgen --language android --mapping seeds/android/mapping.txt --trace seeds/android/obfuscated.txt --map-pad-kb ${mappad%%:*} --entries $entries --out corpus-$scenario" ;;
*) corpusgen_cmd="./corpusgen --bundle app.mjs --map app.mjs.map --entries $entries --pad-kb $pad --map-pad-kb ${mappad%%:*} --mappings-pad-kb ${mappad##*:} --out corpus-$scenario" ;;
esac
for ip in "$SUT_IP" "$LDG_IP"; do
diff --git a/benchmarks/processor/run-local.sh b/benchmarks/processor/run-local.sh
index 3e4161bb..ac4527b6 100755
--- a/benchmarks/processor/run-local.sh
+++ b/benchmarks/processor/run-local.sh
@@ -47,7 +47,7 @@ build_all() {
scenario_params() {
local oom_cache="$OOM_ENTRIES"
- case "$2" in ios|honeycomb-ios) oom_cache="${OOM_CACHE:-128}" ;; esac
+ case "$2" in ios|honeycomb-ios|android) oom_cache="${OOM_CACHE:-128}" ;; esac
case "$1" in
hot) echo "1 $PAD_KB 0:0 128 $CONNECTIONS $STEP_DURATION" ;;
churn) echo "$CHURN_ENTRIES $PAD_KB 0:0 128 $CONNECTIONS $STEP_DURATION" ;;
@@ -65,6 +65,8 @@ gen_corpus() {
./corpusgen/corpusgen --language ios --entries "$entries" --dsym seeds/ios/app.dsym --trace seeds/ios/trace.txt --out "$dir" >&2
elif [ "$lang" = honeycomb-ios ]; then
./corpusgen/corpusgen --language honeycomb-ios --entries "$entries" --dsym seeds/ios/app.dsym --trace seeds/ios/trace.txt --binary sample --out "$dir" >&2
+ elif [ "$lang" = android ]; then
+ ./corpusgen/corpusgen --language android --entries "$entries" --mapping seeds/android/mapping.txt --trace seeds/android/obfuscated.txt --map-pad-kb "${mappad%%:*}" --out "$dir" >&2
else
./corpusgen/corpusgen --entries "$entries" --pad-kb "$pad" --map-pad-kb "${mappad%%:*}" --mappings-pad-kb "${mappad##*:}" --out "$dir" >&2
fi
@@ -84,6 +86,9 @@ impl_env() {
traceway-ios-mem) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER= DISK= LANG=ios" ;;
traceway-ios-disk) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER= DISK=1 LANG=ios" ;;
honeycomb-ios) echo "BIN=./build-honeycomb/otelcol-bench-honeycomb CFG=config-honeycomb-ios.yaml PARSER= DISK= LANG=honeycomb-ios SIGNAL=logs" ;;
+ traceway-android-mem) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER= DISK= LANG=android SIGNAL=logs" ;;
+ traceway-android-disk) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER= DISK=1 LANG=android SIGNAL=logs" ;;
+ honeycomb-android) echo "BIN=./build-honeycomb/otelcol-bench-honeycomb CFG=config-honeycomb-android.yaml PARSER= DISK= LANG=android SIGNAL=logs" ;;
*) echo "unknown impl $1" >&2; return 1 ;;
esac
}
@@ -92,6 +97,7 @@ drain_markers() {
case "$1" in
dart) echo "OK_MARKER=crash.dart FAIL_MARKER=_kDartIsolateSnapshotInstructions" ;;
ios|honeycomb-ios) echo "OK_MARKER=sample.c FAIL_MARKER=sample+0x" ;;
+ android) echo "OK_MARKER=.kt: FAIL_MARKER=SourceFile:" ;;
*) echo "OK_MARKER=../src/inventory.js FAIL_MARKER=.mjs:1:" ;;
esac
}
diff --git a/benchmarks/processor/seeds/android/mapping.txt b/benchmarks/processor/seeds/android/mapping.txt
new file mode 100644
index 00000000..89beaf60
--- /dev/null
+++ b/benchmarks/processor/seeds/android/mapping.txt
@@ -0,0 +1,174 @@
+# compiler: R8
+# compiler_version: 8.7.18
+# min_api: 24
+# common_typos_disable
+# {"id":"com.android.tools.r8.mapping","version":"2.2"}
+# pg_map_id: 224618e
+# pg_map_hash: SHA-256 224618e8d10251e01f614fb1be0047f9d1b57e5efad071b0a17e917c1e76ef3d
+com.example.androdemo.Checkout -> R8$$REMOVED$$CLASS$$0:
+# {"id":"sourceFile","fileName":"Checkout.kt"}
+com.example.androdemo.MainActivity -> com.example.androdemo.MainActivity:
+# {"id":"sourceFile","fileName":"MainActivity.kt"}
+ int $r8$clinit -> a
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void <init>():8:8 -> <init>
+ 1:1:void crashKotlin():33:33 -> a
+ 2:2:double com.example.androdemo.Checkout.checkout(double[]):15:15 -> a
+ 2:2:void crashKotlin():33 -> a
+ 3:3:double com.example.androdemo.Checkout.chargeCard(double):5:5 -> a
+ 3:3:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 3:3:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 3:3:void crashKotlin():33 -> a
+ 4:4:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140:140 -> a
+ 4:4:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 4:4:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 4:4:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 4:4:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 4:4:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 4:4:void crashKotlin():33 -> a
+ 5:5:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):144:144 -> a
+ 5:5:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 5:5:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 5:5:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 5:5:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 5:5:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 5:5:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 5:5:void crashKotlin():33 -> a
+ 6:6:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):146:146 -> a
+ 6:6:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 6:6:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 6:6:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 6:6:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 6:6:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 6:6:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 6:6:void crashKotlin():33 -> a
+ 7:7:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):149:149 -> a
+ 7:7:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 7:7:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 7:7:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 7:7:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 7:7:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 7:7:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 7:7:void crashKotlin():33 -> a
+ 8:8:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):151:151 -> a
+ 8:8:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 8:8:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 8:8:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 8:8:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 8:8:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 8:8:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 8:8:void crashKotlin():33 -> a
+ 9:11:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):153:155 -> a
+ 9:11:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 9:11:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 9:11:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 9:11:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 9:11:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 9:11:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 9:11:void crashKotlin():33 -> a
+ 12:12:java.lang.String kotlin.jvm.internal.Intrinsics.createParameterIsNullExceptionMessage(java.lang.String):157:157 -> a
+ 12:12:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 12:12:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 12:12:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 12:12:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 12:12:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 12:12:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 12:12:void crashKotlin():33 -> a
+ 13:13:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140:140 -> a
+ 13:13:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 13:13:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 13:13:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 13:13:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 13:13:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 13:13:void crashKotlin():33 -> a
+ 14:14:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253:253 -> a
+ 14:14:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 14:14:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 14:14:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 14:14:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 14:14:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 14:14:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 14:14:void crashKotlin():33 -> a
+ 15:16:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable,java.lang.String):257:258 -> a
+ 15:16:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253 -> a
+ 15:16:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 15:16:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 15:16:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 15:16:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 15:16:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 15:16:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 15:16:void crashKotlin():33 -> a
+ 17:17:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable,java.lang.String):262:262 -> a
+ 17:17:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253 -> a
+ 17:17:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 17:17:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 17:17:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 17:17:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 17:17:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 17:17:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 17:17:void crashKotlin():33 -> a
+ 18:19:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable,java.lang.String):267:268 -> a
+ 18:19:java.lang.Throwable kotlin.jvm.internal.Intrinsics.sanitizeStackTrace(java.lang.Throwable):253 -> a
+ 18:19:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140 -> a
+ 18:19:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 18:19:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 18:19:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 18:19:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 18:19:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 18:19:void crashKotlin():33 -> a
+ 20:20:void kotlin.jvm.internal.Intrinsics.throwParameterIsNullNPE(java.lang.String):140:140 -> a
+ 20:20:void kotlin.jvm.internal.Intrinsics.checkNotNullParameter(java.lang.Object,java.lang.String):131 -> a
+ 20:20:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):0 -> a
+ 20:20:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 20:20:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 20:20:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 20:20:void crashKotlin():33 -> a
+ 21:21:void com.example.androdemo.PaymentDeclinedException.<init>(java.lang.String):3:3 -> a
+ 21:21:double com.example.androdemo.Checkout.chargeCard(double):5 -> a
+ 21:21:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 21:21:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 21:21:void crashKotlin():33 -> a
+ 22:22:double com.example.androdemo.Checkout.chargeCard(double):5:5 -> a
+ 22:22:double com.example.androdemo.Checkout.applyTax(double):10 -> a
+ 22:22:double com.example.androdemo.Checkout.checkout(double[]):18 -> a
+ 22:22:void crashKotlin():33 -> a
+ 1:1:void onCreate(android.os.Bundle):10:10 -> onCreate
+ 2:4:void onCreate(android.os.Bundle):12:14 -> onCreate
+ 5:7:void onCreate(android.os.Bundle):16:18 -> onCreate
+ 8:8:void onCreate(android.os.Bundle):16:16 -> onCreate
+ 9:11:void onCreate(android.os.Bundle):20:22 -> onCreate
+ 12:12:void onCreate(android.os.Bundle):20:20 -> onCreate
+ 13:13:void onCreate(android.os.Bundle):24:24 -> onCreate
+ 14:14:void onCreate(android.os.Bundle):26:26 -> onCreate
+ 15:15:void crashNative():37:37 -> onCreate
+ 15:15:void onCreate(android.os.Bundle):28 -> onCreate
+ 16:17:void onCreate(android.os.Bundle):26:27 -> onCreate
+com.example.androdemo.MainActivity$$ExternalSyntheticLambda0 -> a.a:
+# {"id":"sourceFile","fileName":"R8$$SyntheticClass"}
+# {"id":"com.android.tools.r8.synthesized"}
+ int a.MainActivity$$ExternalSyntheticLambda0.$r8$classId -> a
+ # {"id":"com.android.tools.r8.synthesized"}
+ com.example.androdemo.MainActivity com.example.androdemo.MainActivity$$InternalSyntheticLambda$1$fd788ef1c9019be65d0bc8853139bec490236ec6d1e2a1f187ca4d1845e5f895$0.f$0 -> b
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void a.MainActivity$$ExternalSyntheticLambda0.<init>(com.example.androdemo.MainActivity,int):0:0 -> <init>
+ # {"id":"com.android.tools.r8.synthesized"}
+ 1:1:void com.example.androdemo.MainActivity.onCreate$lambda$4$lambda$3(com.example.androdemo.MainActivity,android.view.View):22:22 -> onClick
+ 1:1:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+ # {"id":"com.android.tools.r8.synthesized"}
+ 2:2:void com.example.androdemo.MainActivity.crashNative():37:37 -> onClick
+ 2:2:void com.example.androdemo.MainActivity.onCreate$lambda$4$lambda$3(com.example.androdemo.MainActivity,android.view.View):22 -> onClick
+ 2:2:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+ 3:3:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0:0 -> onClick
+ 4:4:void com.example.androdemo.MainActivity.onCreate$lambda$2$lambda$1(com.example.androdemo.MainActivity,android.view.View):18:18 -> onClick
+ 4:4:void a.MainActivity$$ExternalSyntheticLambda0.onClick(android.view.View):0 -> onClick
+com.example.androdemo.NativeBridge -> com.example.androdemo.NativeBridge:
+# {"id":"sourceFile","fileName":"NativeBridge.kt"}
+ com.example.androdemo.NativeBridge INSTANCE -> a
+ 1:1:void <init>():3:3 -> <clinit>
+ 1:1:void <clinit>():0 -> <clinit>
+ 2:2:void <clinit>():0:0 -> <clinit>
+ 3:3:void <clinit>():5:5 -> <clinit>
+com.example.androdemo.PaymentDeclinedException -> a.b:
+# {"id":"sourceFile","fileName":"PaymentDeclinedException.kt"}
+kotlin.jvm.internal.Intrinsics -> b.a:
+# {"id":"sourceFile","fileName":"Intrinsics.java"}
diff --git a/benchmarks/processor/seeds/android/obfuscated.txt b/benchmarks/processor/seeds/android/obfuscated.txt
new file mode 100644
index 00000000..9802994c
--- /dev/null
+++ b/benchmarks/processor/seeds/android/obfuscated.txt
@@ -0,0 +1,5 @@
+a.b: card declined for $30.59
+ at com.example.androdemo.MainActivity.a(SourceFile:3)
+ at a.a.onClick(SourceFile:1)
+ at android.view.View.performClick(View.java:7659)
+ at android.app.Activity.dispatchTouchEvent(Activity.java:4204)
diff --git a/docs/pages/client/android/index.mdx b/docs/pages/client/android/index.mdx
index 1b2cf4fe..2492855b 100644
--- a/docs/pages/client/android/index.mdx
+++ b/docs/pages/client/android/index.mdx
@@ -12,11 +12,11 @@ dependencies {
}
```
-Maven Central is enabled by default in modern Android projects — no extra `repositories { ... }` entry is required.
+Maven Central is enabled by default in modern Android projects, so no extra `repositories { ... }` entry is required.
## Setup
-Initialize the SDK from your `Application.onCreate()`. This wraps the whole process — every uncaught exception, on every thread, is captured automatically:
+Initialize the SDK from your `Application.onCreate()`. This wraps the whole process. Every uncaught exception, on every thread, is captured automatically:
```kotlin
import android.app.Application
@@ -74,6 +74,7 @@ Traceway.flush()
| `sampleRate` | `Double` | `1.0` | Event sampling rate (0.0 to 1.0) |
| `debug` | `Boolean` | `false` | Print debug info to logcat |
| `version` | `String` | `""` | App version string |
+| `proguardUuid` | `String?` | `null` | R8/ProGuard build UUID for deobfuscating release crashes; set to `BuildConfig.TRACEWAY_PROGUARD_UUID` from the [symbols plugin](/symbolicator/android) |
| `debounceMs` | `Long` | `1500` | Milliseconds before sending batched events |
| `retryDelayMs` | `Long` | `10000` | Retry delay in ms on failed uploads |
| `maxPendingExceptions` | `Int` | `5` | Max exceptions held in memory before oldest is dropped |
@@ -85,7 +86,7 @@ Traceway.flush()
| `captureNavigation` | `Boolean` | `true` | Record activity push / pop transitions |
| `eventsWindowMs` | `Long` | `10000` | Rolling window kept in the log/action buffers (ms) |
| `eventsMaxCount` | `Int` | `200` | Hard cap applied independently to logs and actions |
-| `screenCapture` | `Boolean` | `false` | **No effect on Android** — accepted for API parity |
+| `screenCapture` | `Boolean` | `false` | **No effect on Android**, accepted for API parity |
| `capturePixelRatio` | `Double` | `0.75` | **No effect on Android** |
| `maxBufferFrames` | `Int` | `150` | **No effect on Android** |
| `fps` | `Int` | `15` | **No effect on Android** |
@@ -107,7 +108,7 @@ Traceway.init(
## Logs & Actions
-Every captured exception ships with the last ~10 seconds of session context, attached to a `sessionRecordings` entry on the wire — the same shape the Flutter SDK uses (minus the video chunks). Two independent rolling buffers — **logs** and **actions** — are kept in memory, each capped at 200 entries by default.
+Every captured exception ships with the last ~10 seconds of session context, attached to a `sessionRecordings` entry on the wire, the same shape the Flutter SDK uses (minus the video chunks). Two independent rolling buffers, **logs** and **actions**, are kept in memory, each capped at 200 entries by default.
### Logs
@@ -130,7 +131,7 @@ Timber.plant(object : Timber.Tree() {
Three kinds of actions are collected:
-- **Network** — every HTTP request routed through an OkHttp client with `TracewayOkHttpInterceptor` installed (method, URL, status, duration, request/response byte counts). Catches Retrofit, Coil, Glide-via-OkHttp, and your own usage:
+- **Network**: every HTTP request routed through an OkHttp client with `TracewayOkHttpInterceptor` installed (method, URL, status, duration, request/response byte counts). Catches Retrofit, Coil, Glide-via-OkHttp, and your own usage:
```kotlin
val client = OkHttpClient.Builder()
@@ -146,9 +147,9 @@ Three kinds of actions are collected:
)
```
-- **Navigation** — activity `push` / `pop` transitions, recorded automatically once `Traceway.init(...)` runs (the SDK registers an `Application.ActivityLifecycleCallbacks` for you). No wiring needed on your side.
+- **Navigation**: activity `push` / `pop` transitions, recorded automatically once `Traceway.init(...)` runs (the SDK registers an `Application.ActivityLifecycleCallbacks` for you). No wiring needed on your side.
-- **Custom** — anything your app records explicitly:
+- **Custom**: anything your app records explicitly:
```kotlin
Traceway.recordAction(
@@ -160,7 +161,7 @@ Three kinds of actions are collected:
### Wire shape
-Logs and actions are sent to the backend inside the same `sessionRecordings` entry that the Flutter SDK uses for video — they're stored under separate `logs` and `actions` arrays. Each recording carries `startedAt` and `endedAt` ISO 8601 timestamps so the backend can align events on a timeline (`offsetIntoVideoMs = event.timestamp − recording.startedAt`):
+Logs and actions are sent to the backend inside the same `sessionRecordings` entry that the Flutter SDK uses for video. They're stored under separate `logs` and `actions` arrays. Each recording carries `startedAt` and `endedAt` ISO 8601 timestamps so the backend can align events on a timeline (`offsetIntoVideoMs = event.timestamp − recording.startedAt`):
```json
{
@@ -205,10 +206,27 @@ Traceway.init(
`Traceway.init(...)` sets up capture for the following sources with no additional configuration:
- **Uncaught Java/Kotlin exceptions** on every thread, via `Thread.setDefaultUncaughtExceptionHandler`
-- **View click handler throws** — uncaught exceptions inside `View.OnClickListener`, `AlertDialog` button handlers, and similar UI callbacks
-- **Background thread throws** — anything that escapes a `Thread`'s `run()` body
-- **Main `Handler.post` throws** — async exceptions on the main looper, caught by the default uncaught-exception handler
-- **Activity lifecycle transitions** — `push` / `pop` recorded as navigation actions
+- **View click handler throws**: uncaught exceptions inside `View.OnClickListener`, `AlertDialog` button handlers, and similar UI callbacks
+- **Background thread throws**: anything that escapes a `Thread`'s `run()` body
+- **Main `Handler.post` throws**: async exceptions on the main looper, caught by the default uncaught-exception handler
+- **Activity lifecycle transitions**: `push` / `pop` recorded as navigation actions
+
+## Deobfuscate Release Crashes
+
+Release builds run R8, so crash traces arrive with renamed classes and rewritten line numbers. To get readable traces, apply the [`com.tracewayapp.symbols`](/symbolicator/android) Gradle plugin. It injects a per-build UUID into `BuildConfig.TRACEWAY_PROGUARD_UUID` and uploads the build's `mapping.txt` to your Traceway instance. Pass the injected UUID to the SDK so each report can be matched to its mapping:
+
+```kotlin
+Traceway.init(
+ application = this,
+ connectionString = BuildConfig.TRACEWAY_DSN,
+ options = TracewayOptions(
+ version = "1.0.0",
+ proguardUuid = BuildConfig.TRACEWAY_PROGUARD_UUID,
+ ),
+)
+```
+
+See the [Android symbolicator docs](/symbolicator/android) for the full plugin configuration, the upload token, and the manual upload path.
## Test Your Integration
@@ -231,4 +249,4 @@ Tap the button and check your Traceway dashboard to verify the error appears wit
|----------|----------------|------------------|
| Android (API 21+) | Yes | No |
-For Flutter apps that need cross-platform error tracking (and screen recording on iOS / Android / macOS), use the [Flutter SDK](/client/flutter) instead — it ships the same wire format so a single Traceway backend handles both.
+For Flutter apps that need cross-platform error tracking (and screen recording on iOS / Android / macOS), use the [Flutter SDK](/client/flutter) instead. It ships the same wire format, so a single Traceway backend handles both.
diff --git a/docs/pages/symbolicator/_meta.json b/docs/pages/symbolicator/_meta.json
index f966c717..c8ee1dd7 100644
--- a/docs/pages/symbolicator/_meta.json
+++ b/docs/pages/symbolicator/_meta.json
@@ -3,6 +3,7 @@
"javascript": "JavaScript",
"dart": "Dart",
"ios": "iOS",
+ "android": "Android",
"performance": "Performance",
"opentelemetry": "OpenTelemetry",
"library": "Library"
diff --git a/docs/pages/symbolicator/android.mdx b/docs/pages/symbolicator/android.mdx
new file mode 100644
index 00000000..9421347b
--- /dev/null
+++ b/docs/pages/symbolicator/android.mdx
@@ -0,0 +1,130 @@
+# Android
+
+A release build of an Android app runs R8, which minifies and obfuscates the bytecode. When a Kotlin or Java exception is thrown out of that code, every class and method has been renamed and the line tables rewritten, so the trace arrives obfuscated:
+
+```
+a.b: card declined for $30.59
+ at a.a.a(SourceFile:2)
+ at com.example.app.MainActivity.a(SourceFile:3)
+```
+
+The trace is reversed with the build's `mapping.txt`. With it uploaded, the trace above resolves to source:
+
+```
+com.example.app.PaymentDeclinedException: card declined for $30.59
+ at com.example.app.Checkout.chargeCard(Checkout.kt:5)
+ at com.example.app.Checkout.applyTax(Checkout.kt:10)
+ at com.example.app.Checkout.checkout(Checkout.kt:18)
+ at com.example.app.MainActivity.crashKotlin(MainActivity.kt:33)
+```
+
+This page covers how to upload `mapping.txt` with the Gradle plugin, the upload API, how a trace is recognized and resolved, and how to migrate an app off Honeycomb. For when symbolication runs, the cache, and the `.tw` format, see [Architecture](/symbolicator).
+
+## R8: what `mapping.txt` says
+
+A release build with `minifyEnabled true` runs R8, which shrinks, optimizes, and obfuscates the bytecode. It renames classes and methods to short tokens, inlines small methods into their callers, and rewrites the line-number table. The reverse map is the `mapping.txt` written to `app/build/outputs/mapping/<variant>/mapping.txt`.
+
+Retracing reads three things from it: a class line maps the original fully qualified name to the obfuscated one; a `sourceFile` comment records the original file; and member lines map each method with line ranges on both sides. Because R8 inlines, one obfuscated frame can expand to several source frames, listed innermost first. The grouping hash is therefore computed **after** retrace, so inline expansion does not split one error into many issues.
+
+## Uploading symbols with the Gradle plugin
+
+The Traceway symbols Gradle plugin finds the `mapping.txt` and posts it. It's published to Maven Central, so add `mavenCentral()` to your `pluginManagement` repositories in `settings.gradle.kts`:
+
+```kotlin
+pluginManagement {
+ repositories {
+ gradlePluginPortal()
+ mavenCentral() // resolves com.tracewayapp.symbols
+ }
+}
+```
+
+Then apply it to your app module:
+
+```kotlin
+plugins {
+ id("com.tracewayapp.symbols") version "0.0.1"
+}
+
+android {
+ buildFeatures { buildConfig = true } // required for the injected UUID field
+ buildTypes {
+ release { isMinifyEnabled = true }
+ }
+}
+
+traceway {
+ uploadToken = "<your project upload token>"
+ url = "https://your-traceway-host" // instance base URL
+ autoUpload = true // run after assembleRelease; default false
+ // proguardUuid = "..." // optional: pin the build UUID yourself
+}
+```
+
+`uploadToken` is your project's **upload token** from the dashboard, the same one used for JavaScript source maps and iOS dSYMs. It is **not** the runtime token in your SDK connection string. Using the connection-string token here is rejected with a 401.
+
+With `autoUpload = true` the upload runs automatically after `assembleRelease`. The default is `false` (so a release build never depends on backend availability); upload explicitly instead, which is the better fit for CI:
+
+```bash
+./gradlew assembleRelease uploadReleaseTracewaySymbols
+```
+
+The plugin embeds a ProGuard UUID into `BuildConfig.TRACEWAY_PROGUARD_UUID` and names the uploaded mapping `<uuid>.txt`. The UUID is derived from the module path, variant, and app version (`versionName` + `versionCode`), so each released version gets its own mapping. **Bump the version each release** so a new upload doesn't overwrite a previous release's mapping (or set `proguardUuid` explicitly for full control). Pass that value to the SDK so reported crashes carry the matching UUID:
+
+```kotlin
+Traceway.init(
+ application = this,
+ connectionString = BuildConfig.TRACEWAY_DSN,
+ options = TracewayOptions(
+ version = "1.0.0",
+ proguardUuid = BuildConfig.TRACEWAY_PROGUARD_UUID,
+ ),
+)
+```
+
+## The upload API
+
+The plugin posts to the shared symbols endpoint:
+
+```
+POST /api/symbols/upload
+Authorization: Bearer <upload token>
+Content-Type: multipart/form-data
+```
+
+| Field | Required | Notes |
+|---|---|---|
+| `files` | yes | The `mapping.txt` file. 200 MB per file. |
+| `proguard_uuid` | yes | The build UUID. The mapping is stored as `<uuid>.txt`. |
+
+The backend recognizes an R8 mapping by its header and class lines. The stored key is:
+
+```
+androidmappings/{projectId}/{proguardUuid}.txt # R8 mapping, by build UUID
+```
+
+## How a trace is recognized and resolved
+
+- A `at pkg.Class.method(File:line)` frame is retraced through the build's mapping, expanding inlined frames.
+- Any other line passes through; obfuscated class tokens in the exception header and `Caused by:` lines are deobfuscated too.
+
+A maximum of 50 frames are emitted, inline expansions included. A frame with no match keeps its raw form, so a trace is never worse than it arrived.
+
+## Migrating from Honeycomb
+
+Honeycomb symbolicates Android in its OpenTelemetry Collector, keying ProGuard mappings by the `app.debug.proguard_uuid` resource attribute and storing them as `<uuid>.txt`. Traceway reads that **same** attribute and `<uuid>.txt` naming on the OTLP path, so a migrating app does not change its instrumentation.
+
+To move an app from Honeycomb to Traceway:
+
+1. Point the OpenTelemetry Android SDK's OTLP exporter at Traceway's endpoint (`/api/otel/v1/traces`) with a Bearer project token.
+2. Keep your existing `proguard-uuid` Gradle plugin, which sets `app.debug.proguard_uuid`.
+3. Upload your `<uuid>.txt` mappings to Traceway (via the Gradle plugin above, or any POST to `/api/symbols/upload` with a `proguard_uuid` field).
+
+Symbolication then happens in Traceway, in the collector processor or in the backend, with no Honeycomb collector in the path.
+
+## Related pages
+
+- [Architecture](/symbolicator): when symbolication runs, the cache tiers, and the `.tw` format
+- [iOS](/symbolicator/ios) and [Dart](/symbolicator/dart): the flat-DWARF approach for native symbols
+- [Performance](/symbolicator/performance): cache sizing and failure handling
+```
diff --git a/examples/devtesting-embedded/main.go b/examples/devtesting-embedded/main.go
index 54760d5a..eea6ed7c 100644
--- a/examples/devtesting-embedded/main.go
+++ b/examples/devtesting-embedded/main.go
@@ -46,6 +46,8 @@ const (
flutterUploadToken = "flutter-upload-token"
iosToken = "ios-dev-token"
iosUploadToken = "ios-upload-token"
+ androidToken = "android-dev-token"
+ androidUploadToken = "android-upload-token"
backendServiceName = "backend-service"
workerServiceName = "worker-service"
@@ -141,6 +143,8 @@ func main() {
tracewaybackend.WithDefaultProjectSourceMapToken("Flutter App", flutterUploadToken),
tracewaybackend.WithDefaultProject("iOS App", "ios", iosToken),
tracewaybackend.WithDefaultProjectSourceMapToken("iOS App", iosUploadToken),
+ tracewaybackend.WithDefaultProject("Android App", "android", androidToken),
+ tracewaybackend.WithDefaultProjectSourceMapToken("Android App", androidUploadToken),
tracewaybackend.WithMonitoringURL(monitoringToken+"@http://localhost:8082/api/report"),
)
diff --git a/frontend/src/lib/components/issues/stack-trace-card.svelte b/frontend/src/lib/components/issues/stack-trace-card.svelte
index a8a8d11e..a84aafcd 100644
--- a/frontend/src/lib/components/issues/stack-trace-card.svelte
+++ b/frontend/src/lib/components/issues/stack-trace-card.svelte
@@ -1,10 +1,16 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card';
+ import * as Tabs from '$lib/components/ui/tabs';
import { formatDateTime } from '$lib/utils/formatters';
import { getTimezone } from '$lib/state/timezone.svelte';
import Button from '../ui/button/button.svelte';
import { Archive, ChevronRight, ChevronDown } from 'lucide-svelte';
- import { parseStackTrace, type StackFrame } from '$lib/utils/stack-trace-parser';
+ import {
+ parseStackTrace,
+ looksLikeJava,
+ looksLikeGo,
+ type StackFrame
+ } from '$lib/utils/stack-trace-parser';
interface Props {
stackTrace: string;
@@ -36,10 +42,15 @@
const tz = $derived(timezone ?? getTimezone());
const showStats = $derived(firstSeen && lastSeen && totalCount !== undefined);
- const parsed = $derived(parseStackTrace(stackTrace, { ios: isIOS }));
- const usePretty = $derived((isJavaScript || isFlutter || isIOS) && parsed.groups.length > 0);
- const groupNoun = $derived(isIOS ? 'system' : 'library');
+ const isJava = $derived(looksLikeJava(stackTrace));
+ const isGo = $derived(looksLikeGo(stackTrace));
+ const parsed = $derived(parseStackTrace(stackTrace, { ios: isIOS, java: isJava, go: isGo }));
+ const usePretty = $derived(
+ (isJavaScript || isFlutter || isIOS || isJava || isGo) && parsed.groups.length > 0
+ );
+ const groupNoun = $derived(isIOS || isJava ? 'system' : 'library');
+ let viewMode = $state<'formatted' | 'raw'>('formatted');
let expandedGroups = $state<Set<number>>(new Set());
function toggleGroup(index: number) {
@@ -54,17 +65,19 @@
function formatFrame(frame: StackFrame) {
const fn = (frame.functionName ?? '').replace(/\(\)\s*$/, '').trim();
- const m = frame.location.match(/^(.*):(\d+):(\d+)$/);
+ const withCol = frame.location.match(/^(.*):(\d+):(\d+)$/);
+ const m = withCol ?? frame.location.match(/^(.*):(\d+)$/);
if (!m) {
return { fn, dir: '', file: frame.location, lineCol: '', raw: frame.location };
}
- const [, path, line, col] = m;
+ const path = m[1];
+ const lineCol = withCol ? `${m[2]}:${m[3]}` : m[2];
const slash = path.lastIndexOf('/');
return {
fn,
dir: slash >= 0 ? path.slice(0, slash + 1) : '',
file: slash >= 0 ? path.slice(slash + 1) : path,
- lineCol: `${line}:${col}`,
+ lineCol,
raw: frame.location
};
}
@@ -108,93 +121,109 @@
<Card.Content class="pb-2">
{#if usePretty}
<div class="overflow-hidden rounded-md border">
- {#if parsed.errorMessage}
- <div class="border-b bg-muted/50 px-4 py-3">
+ <div class="flex items-center justify-between gap-3 border-b bg-muted/50 px-4 py-2.5">
+ {#if viewMode === 'formatted' && parsed.errorMessage}
<p
- class="font-mono text-sm font-medium break-words whitespace-pre-wrap text-foreground"
+ class="min-w-0 flex-1 font-mono text-sm font-medium break-words whitespace-pre-wrap text-foreground"
>
{parsed.errorMessage}
</p>
+ {:else}
+ <div class="flex-1"></div>
+ {/if}
+ <div class="shrink-0">
+ <Tabs.Root bind:value={viewMode}>
+ <Tabs.List>
+ <Tabs.Trigger value="formatted">Formatted</Tabs.Trigger>
+ <Tabs.Trigger value="raw">Raw</Tabs.Trigger>
+ </Tabs.List>
+ </Tabs.Root>
</div>
- {/if}
-
- <ol role="list" class="divide-y divide-border/60">
- {#each parsed.groups as group, i}
- {#if group.type === 'app'}
- {@const f = formatFrame(group.frame)}
- <li
- class="flex flex-wrap items-baseline gap-x-1.5 px-4 py-2 font-mono text-sm tabular-nums"
- title={f.raw}
- >
- <span class="min-w-0 break-all text-muted-foreground"
- >{f.dir}<span class="font-medium text-foreground">{f.file}</span></span
- >
- {#if f.fn}
- <span class="text-muted-foreground/70">in</span>
- <span class="min-w-0 font-medium break-all text-foreground">{f.fn}</span>
- {/if}
- {#if f.lineCol}
- <span class="text-muted-foreground/70">at line</span>
- <span class="text-foreground">{f.lineCol}</span>
- {/if}
- </li>
- {:else}
- <li>
- <button
- type="button"
- class="flex w-full items-center gap-1.5 bg-muted/25 px-4 py-2 text-left text-xs text-muted-foreground hover:bg-muted/70"
- onclick={() => toggleGroup(i)}
+ </div>
+ {#if viewMode === 'formatted'}
+ <ol role="list" class="divide-y divide-border/60">
+ {#each parsed.groups as group, i}
+ {#if group.type === 'app'}
+ {@const f = formatFrame(group.frame)}
+ <li
+ class="flex flex-wrap items-baseline gap-x-1.5 px-4 py-2 font-mono text-sm tabular-nums"
+ title={f.raw}
>
- {#if expandedGroups.has(i)}
- <ChevronDown class="size-3.5 shrink-0" />
- {:else}
- <ChevronRight class="size-3.5 shrink-0" />
- {/if}
- <span class="tabular-nums"
- >{group.frames.length} {groupNoun} {group.frames.length === 1
- ? 'frame'
- : 'frames'}</span
- >
- <span
- class="rounded-md border bg-background px-1.5 py-0.5 font-mono text-foreground/70"
- >{group.packageName}</span
+ <span class="min-w-0 break-all text-muted-foreground"
+ >{f.dir}<span class="font-medium text-foreground">{f.file}</span></span
>
- </button>
- {#if expandedGroups.has(i)}
- <ol
- role="list"
- class="divide-y divide-border/40 border-t border-border/40 bg-muted/30"
+ {#if f.fn}
+ <span class="text-muted-foreground/70">in</span>
+ <span class="min-w-0 font-medium break-all text-foreground">{f.fn}</span>
+ {/if}
+ {#if f.lineCol}
+ <span class="text-muted-foreground/70">at line</span>
+ <span class="text-foreground">{f.lineCol}</span>
+ {/if}
+ </li>
+ {:else}
+ <li>
+ <button
+ type="button"
+ class="flex w-full items-center gap-1.5 bg-muted/25 px-4 py-2 text-left text-xs text-muted-foreground hover:bg-muted/70"
+ onclick={() => toggleGroup(i)}
>
- {#each group.frames as frame}
- {@const f = formatFrame(frame)}
- <li
- class="flex flex-wrap items-baseline gap-x-1.5 py-2 pr-4 pl-9 font-mono text-sm text-muted-foreground tabular-nums"
- title={f.raw}
- >
- <span class="min-w-0 break-all"
- >{f.dir}<span class="text-foreground/70">{f.file}</span></span
+ {#if expandedGroups.has(i)}
+ <ChevronDown class="size-3.5 shrink-0" />
+ {:else}
+ <ChevronRight class="size-3.5 shrink-0" />
+ {/if}
+ <span class="tabular-nums"
+ >{group.frames.length}
+ {groupNoun}
+ {group.frames.length === 1 ? 'frame' : 'frames'}</span
+ >
+ <span
+ class="rounded-md border bg-background px-1.5 py-0.5 font-mono text-foreground/70"
+ >{group.packageName}</span
+ >
+ </button>
+ {#if expandedGroups.has(i)}
+ <ol
+ role="list"
+ class="divide-y divide-border/40 border-t border-border/40 bg-muted/30"
+ >
+ {#each group.frames as frame}
+ {@const f = formatFrame(frame)}
+ <li
+ class="flex flex-wrap items-baseline gap-x-1.5 py-2 pr-4 pl-9 font-mono text-sm text-muted-foreground tabular-nums"
+ title={f.raw}
>
- {#if f.fn}
- <span class="text-muted-foreground/60">in</span>
- <span class="min-w-0 break-all text-foreground/70">{f.fn}</span>
- {/if}
- {#if f.lineCol}
- <span class="text-muted-foreground/60">at line</span>
- <span>{f.lineCol}</span>
- {/if}
- </li>
- {/each}
- </ol>
- {/if}
- </li>
- {/if}
- {/each}
- </ol>
+ <span class="min-w-0 break-all"
+ >{f.dir}<span class="text-foreground/70">{f.file}</span></span
+ >
+ {#if f.fn}
+ <span class="text-muted-foreground/60">in</span>
+ <span class="min-w-0 break-all text-foreground/70">{f.fn}</span>
+ {/if}
+ {#if f.lineCol}
+ <span class="text-muted-foreground/60">at line</span>
+ <span>{f.lineCol}</span>
+ {/if}
+ </li>
+ {/each}
+ </ol>
+ {/if}
+ </li>
+ {/if}
+ {/each}
+ </ol>
+ {:else}
+ <div class="overflow-x-auto bg-muted/40">
+ <pre
+ class="w-fit min-w-full p-4 font-mono text-sm whitespace-pre text-foreground">{stackTrace}</pre>
+ </div>
+ {/if}
</div>
{:else}
- <div class="overflow-x-auto rounded-lg border bg-muted/40 p-4">
+ <div class="overflow-x-auto rounded-lg border bg-muted/40">
<pre
- class="font-mono text-sm break-words whitespace-pre-wrap text-foreground">{stackTrace}</pre>
+ class="w-fit min-w-full p-4 font-mono text-sm whitespace-pre text-foreground">{stackTrace}</pre>
</div>
{/if}
</Card.Content>
diff --git a/frontend/src/lib/components/source-map-setup.svelte b/frontend/src/lib/components/source-map-setup.svelte
index 469608e6..872db339 100644
--- a/frontend/src/lib/components/source-map-setup.svelte
+++ b/frontend/src/lib/components/source-map-setup.svelte
@@ -80,6 +80,8 @@ module.exports = {
let copiedFlutterUpload = $state(false);
let copiedIosBuild = $state(false);
let copiedIosUpload = $state(false);
+ let copiedAndroidSetup = $state(false);
+ let copiedAndroidUpload = $state(false);
const pluginInstallCommand = 'npm install -D @tracewayapp/bundler-plugin';
@@ -91,7 +93,8 @@ module.exports = {
const isFlutter = $derived(project?.framework === 'flutter');
const isIOS = $derived(project?.framework === 'ios');
- const artifactLabel = $derived(isFlutter || isIOS ? 'debug symbols' : 'source maps');
+ const isAndroid = $derived(project?.framework === 'android');
+ const artifactLabel = $derived(isFlutter || isIOS || isAndroid ? 'debug symbols' : 'source maps');
const showBundlerSetup = $derived(project?.framework !== 'react-native');
@@ -126,6 +129,27 @@ module.exports = {
: ''
);
+ const androidSetupSnippet = $derived(
+ project && sourceMapToken
+ ? `plugins {
+ id("com.tracewayapp.symbols")
+}
+
+android {
+ buildTypes {
+ release { isMinifyEnabled = true }
+ }
+}
+
+traceway {
+ token = "${sourceMapToken}"
+ url = "${project.backendUrl}"
+}`
+ : ''
+ );
+
+ const androidUploadCommand = './gradlew assembleRelease uploadReleaseTracewaySymbols';
+
let regenerateDialogOpen = $state(false);
async function generateToken() {
@@ -196,6 +220,18 @@ module.exports = {
copiedIosUpload = true;
setTimeout(() => (copiedIosUpload = false), 2000);
}
+
+ async function copyAndroidSetup() {
+ await navigator.clipboard.writeText(androidSetupSnippet);
+ copiedAndroidSetup = true;
+ setTimeout(() => (copiedAndroidSetup = false), 2000);
+ }
+
+ async function copyAndroidUpload() {
+ await navigator.clipboard.writeText(androidUploadCommand);
+ copiedAndroidUpload = true;
+ setTimeout(() => (copiedAndroidUpload = false), 2000);
+ }
</script>
{#if sourceMapToken}
@@ -335,6 +371,64 @@ module.exports = {
re-upload on each release.
</p>
</div>
+ {:else if isAndroid}
+ <div>
+ <p class="mb-2 text-sm font-medium">Step 1: Apply the Traceway symbols Gradle plugin</p>
+ <div class="relative">
+ <div class="absolute top-2 right-2 z-10">
+ <Button variant="outline" size="sm" onclick={copyAndroidSetup}>
+ {#if copiedAndroidSetup}
+ <Check class="mr-2 h-4 w-4 text-green-500" />
+ Copied!
+ {:else}
+ <Copy class="mr-2 h-4 w-4" />
+ Copy
+ {/if}
+ </Button>
+ </div>
+ <div
+ class="overflow-x-auto rounded-lg text-sm {themeState.isDark
+ ? 'dark-code'
+ : 'light-code'}"
+ >
+ <Highlight language={javascript} code={androidSetupSnippet} />
+ </div>
+ </div>
+ <p class="mt-2 text-xs text-muted-foreground">
+ Add to your app module's <code class="font-mono">build.gradle.kts</code>. The plugin embeds a
+ ProGuard UUID into BuildConfig (matching Honeycomb's
+ <code class="font-mono">app.debug.proguard_uuid</code>) and names the uploaded mapping
+ <code class="font-mono">&lt;uuid&gt;.txt</code>.
+ </p>
+ </div>
+ <div>
+ <p class="mb-2 text-sm font-medium">Step 2: Build and upload after each release</p>
+ <div class="relative">
+ <div class="absolute top-2 right-2 z-10">
+ <Button variant="outline" size="sm" onclick={copyAndroidUpload}>
+ {#if copiedAndroidUpload}
+ <Check class="mr-2 h-4 w-4 text-green-500" />
+ Copied!
+ {:else}
+ <Copy class="mr-2 h-4 w-4" />
+ Copy
+ {/if}
+ </Button>
+ </div>
+ <div
+ class="overflow-x-auto rounded-lg text-sm {themeState.isDark
+ ? 'dark-code'
+ : 'light-code'}"
+ >
+ <Highlight language={bash} code={androidUploadCommand} />
+ </div>
+ </div>
+ <p class="mt-2 text-xs text-muted-foreground">
+ Uploads the R8 <code class="font-mono">mapping.txt</code> and the unstripped native
+ <code class="font-mono">.so</code> libraries. Native symbols are keyed by GNU build-id, so
+ re-upload on each release.
+ </p>
+ </div>
{:else}
{#if showBundlerSetup}
<div>
@@ -462,6 +556,19 @@ module.exports = {
class="underline hover:text-foreground">iOS docs</a
>
</p>
+ {:else if isAndroid}
+ <p class="text-sm text-muted-foreground">
+ Release builds obfuscate Kotlin/Java with R8 and strip native code. Generate a token, then
+ upload your <code class="rounded bg-muted px-1 py-0.5 font-mono text-xs">mapping.txt</code> and
+ native <code class="rounded bg-muted px-1 py-0.5 font-mono text-xs">.so</code> libraries after each
+ release to resolve their stack traces.
+ <a
+ href="https://docs.tracewayapp.com/symbolicator/android"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="underline hover:text-foreground">Android docs</a
+ >
+ </p>
{:else}
<p class="text-sm text-muted-foreground">
Generate an upload token to start uploading {artifactLabel} as part of your build process.
diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.ts
index 9266e70d..00d5ca0c 100644
--- a/frontend/src/lib/state/projects.svelte.ts
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -52,7 +52,7 @@ export function isJsFramework(fw: Framework): boolean {
}
export function supportsSymbolUpload(fw: Framework): boolean {
- return isJsFramework(fw) || fw === 'flutter' || fw === 'ios';
+ return isJsFramework(fw) || fw === 'flutter' || fw === 'ios' || fw === 'android';
}
export const JS_LANGUAGES = ['webjs', 'nodejs', 'javascript', 'typescript'];
diff --git a/frontend/src/lib/utils/stack-trace-parser.ts b/frontend/src/lib/utils/stack-trace-parser.ts
index 3f00a960..feb9bbd2 100644
--- a/frontend/src/lib/utils/stack-trace-parser.ts
+++ b/frontend/src/lib/utils/stack-trace-parser.ts
@@ -2,16 +2,19 @@ export type StackFrame = {
functionName: string | null;
location: string;
isLibrary: boolean;
+ packageHint?: string;
};
-export type FrameGroup = {
- type: 'app';
- frame: StackFrame;
-} | {
- type: 'library';
- frames: StackFrame[];
- packageName: string;
-};
+export type FrameGroup =
+ | {
+ type: 'app';
+ frame: StackFrame;
+ }
+ | {
+ type: 'library';
+ frames: StackFrame[];
+ packageName: string;
+ };
export type ParsedStackTrace = {
errorMessage: string;
@@ -30,11 +33,155 @@ function isLibraryLocation(location: string): boolean {
);
}
+const javaFramePattern = /^\s*at\s+([\w$.<>]+)\(([^)]*)\)\s*$/;
+
+const JAVA_SYSTEM_RE =
+ /^(java\.|javax\.|jakarta\.|jdk\.|sun\.|com\.sun\.|kotlin\.|kotlinx\.|android\.|androidx\.|com\.android\.|com\.google\.android\.|dalvik\.|libcore\.|org\.json\.)/;
+
+export function looksLikeJava(raw: string): boolean {
+ let count = 0;
+ for (const line of raw.split('\n')) {
+ const m = line.match(javaFramePattern);
+ if (m && !m[2].includes('/')) {
+ if (++count >= 2) return true;
+ }
+ }
+ return false;
+}
+
+function isJavaSystemClass(fqn: string): boolean {
+ return JAVA_SYSTEM_RE.test(fqn);
+}
+
+function javaPackageLabel(fqn: string): string {
+ const segs = fqn.split('.');
+ if ((segs[0] === 'com' || segs[0] === 'org' || segs[0] === 'io') && segs.length > 1) {
+ return `${segs[0]}.${segs[1]}`;
+ }
+ return segs[0] || 'system';
+}
+
+const goLocationPattern = /^[ \t]+(.+\.go):(\d+)(?:\s+\+0x[0-9a-fA-F]+)?\s*$/;
+const goroutineHeaderPattern = /^\s*goroutine\s+\d+\s+\[[^\]]*\]:\s*$/;
+
+export function looksLikeGo(raw: string): boolean {
+ let locations = 0;
+ let goroutine = false;
+ for (const line of raw.split('\n')) {
+ if (goLocationPattern.test(line)) {
+ if (++locations >= 2) return true;
+ } else if (goroutineHeaderPattern.test(line)) {
+ goroutine = true;
+ }
+ }
+ return locations >= 1 && goroutine;
+}
+
+function goFunctionName(rawFn: string): string {
+ return rawFn
+ .replace(/^created by\s+/, '')
+ .replace(/\s+in goroutine\s+\d+\s*$/, '')
+ .replace(/\([^()]*\)\s*$/, '')
+ .trim();
+}
+
+function goFunctionPackage(fn: string): string {
+ const lastSlash = fn.lastIndexOf('/');
+ const dot = fn.indexOf('.', lastSlash + 1);
+ if (dot < 0) return '';
+ const pkg = fn.slice(0, dot);
+ return pkg.startsWith('(') ? '' : pkg;
+}
+
+function isGoStdlibPackage(pkg: string): boolean {
+ if (pkg === '' || pkg === 'main') return false;
+ return !pkg.split('/')[0].includes('.');
+}
+
+function isGoDependencyPath(file: string): boolean {
+ return file.includes('/pkg/mod/') || file.includes('/vendor/') || /@v\d/.test(file);
+}
+
+function isGoStdlibPath(file: string): boolean {
+ if (/(?:^|\/)go\/src\//.test(file)) return true;
+ if (file.startsWith('/')) return false;
+ return !file.split('/')[0].includes('.');
+}
+
+function goDependencyHint(pkg: string, file: string): string {
+ if (pkg.includes('.')) return pkg;
+ const rest = file.match(/\/(?:pkg\/mod|vendor)\/(.+)/);
+ if (rest) {
+ const out: string[] = [];
+ for (const seg of rest[1].split('/')) {
+ const at = seg.indexOf('@');
+ if (at >= 0) {
+ out.push(seg.slice(0, at));
+ break;
+ }
+ out.push(seg);
+ if (out.length >= 3) break;
+ }
+ return out.join('/');
+ }
+ return pkg || 'dependency';
+}
+
+function goStdlibHint(pkg: string, file: string): string {
+ if (pkg) return pkg;
+ const rel = file.match(/\/go\/src\/(.+)/)?.[1] ?? file;
+ const slash = rel.lastIndexOf('/');
+ return slash >= 0 ? rel.slice(0, slash) : 'system';
+}
+
+function classifyGoFrame(fn: string, file: string): { isLibrary: boolean; hint?: string } {
+ const pkg = goFunctionPackage(fn);
+ if (isGoDependencyPath(file)) {
+ return { isLibrary: true, hint: goDependencyHint(pkg, file) };
+ }
+ if (pkg !== 'main' && isGoStdlibPackage(pkg)) {
+ return { isLibrary: true, hint: pkg };
+ }
+ if (isGoStdlibPath(file)) {
+ return { isLibrary: true, hint: goStdlibHint(pkg, file) };
+ }
+ return { isLibrary: false };
+}
+
+function goShortFunction(fn: string): string {
+ const slash = fn.lastIndexOf('/');
+ return slash >= 0 ? fn.slice(slash + 1) : fn;
+}
+
const IOS_SYSTEM_IMAGES = new Set([
- 'CoreFoundation', 'Foundation', 'CFNetwork', 'Security', 'UIKitCore', 'UIKit', 'SwiftUI',
- 'GraphicsServices', 'QuartzCore', 'CoreGraphics', 'CoreText', 'CoreData', 'CoreImage',
- 'CoreAudio', 'CoreVideo', 'CoreServices', 'CoreMotion', 'CoreLocation', 'Metal', 'MetalKit',
- 'ImageIO', 'Combine', 'Network', 'AudioToolbox', 'AVFoundation', 'WebKit', 'JavaScriptCore', 'dyld'
+ 'CoreFoundation',
+ 'Foundation',
+ 'CFNetwork',
+ 'Security',
+ 'UIKitCore',
+ 'UIKit',
+ 'SwiftUI',
+ 'GraphicsServices',
+ 'QuartzCore',
+ 'CoreGraphics',
+ 'CoreText',
+ 'CoreData',
+ 'CoreImage',
+ 'CoreAudio',
+ 'CoreVideo',
+ 'CoreServices',
+ 'CoreMotion',
+ 'CoreLocation',
+ 'Metal',
+ 'MetalKit',
+ 'ImageIO',
+ 'Combine',
+ 'Network',
+ 'AudioToolbox',
+ 'AVFoundation',
+ 'WebKit',
+ 'JavaScriptCore',
+ 'dyld'
]);
function isIOSSystemImage(image: string): boolean {
@@ -76,7 +223,10 @@ function extractPackageName(location: string): string {
return 'library';
}
-export function parseStackTrace(raw: string, opts: { ios?: boolean } = {}): ParsedStackTrace {
+export function parseStackTrace(
+ raw: string,
+ opts: { ios?: boolean; java?: boolean; go?: boolean } = {}
+): ParsedStackTrace {
const lines = raw.split('\n');
const frames: StackFrame[] = [];
let firstFrameIndex = -1;
@@ -120,6 +270,62 @@ export function parseStackTrace(raw: string, opts: { ios?: boolean } = {}): Pars
}
}
+ if (opts.java) {
+ const jm = lines[i].match(javaFramePattern);
+ if (jm && !jm[2].includes('/')) {
+ const fqMethod = jm[1];
+ const source = jm[2].trim();
+ const lastDot = fqMethod.lastIndexOf('.');
+ const method = lastDot >= 0 ? fqMethod.slice(lastDot + 1) : fqMethod;
+ const classFqn = lastDot >= 0 ? fqMethod.slice(0, lastDot) : '';
+ const classSimple = classFqn.includes('.')
+ ? classFqn.slice(classFqn.lastIndexOf('.') + 1)
+ : classFqn;
+ const lib = isJavaSystemClass(fqMethod);
+ if (firstFrameIndex === -1) {
+ firstFrameIndex = i;
+ messageEndIndex = i;
+ }
+ frames.push({
+ functionName: classSimple ? `${classSimple}.${method}` : method,
+ location: source,
+ isLibrary: lib,
+ packageHint: lib ? javaPackageLabel(fqMethod) : undefined
+ });
+ continue;
+ }
+ }
+
+ if (opts.go) {
+ const gm = lines[i].match(goLocationPattern);
+ if (gm) {
+ const location = `${gm[1]}:${gm[2]}`;
+ let funcName: string | null = null;
+ let funcIndex = -1;
+ for (let j = i - 1; j >= 0; j--) {
+ const prev = lines[j].trim();
+ if (prev === '') continue;
+ if (goroutineHeaderPattern.test(lines[j]) || goLocationPattern.test(lines[j])) break;
+ funcName = prev;
+ funcIndex = j;
+ break;
+ }
+ const fullName = funcName ? goFunctionName(funcName) : '';
+ const cls = classifyGoFrame(fullName, gm[1]);
+ if (firstFrameIndex === -1) {
+ firstFrameIndex = i;
+ messageEndIndex = funcIndex !== -1 ? funcIndex : i;
+ }
+ frames.push({
+ functionName: fullName ? goShortFunction(fullName) : null,
+ location,
+ isLibrary: cls.isLibrary,
+ packageHint: cls.isLibrary ? cls.hint : undefined
+ });
+ continue;
+ }
+ }
+
const dartMatch = lines[i].match(dartFramePattern);
if (dartMatch) {
const location = dartMatch[2].trim();
@@ -173,9 +379,14 @@ export function parseStackTrace(raw: string, opts: { ios?: boolean } = {}): Pars
}
}
- const errorMessage = firstFrameIndex === -1
- ? raw.trim()
- : lines.slice(0, messageEndIndex).join('\n').trim();
+ const errorMessage =
+ firstFrameIndex === -1
+ ? raw.trim()
+ : lines
+ .slice(0, messageEndIndex)
+ .filter((l) => !goroutineHeaderPattern.test(l))
+ .join('\n')
+ .trim();
const groups: FrameGroup[] = [];
@@ -193,7 +404,7 @@ export function parseStackTrace(raw: string, opts: { ios?: boolean } = {}): Pars
groups.push({
type: 'library',
frames: libraryFrames,
- packageName: extractPackageName(libraryFrames[0].location)
+ packageName: libraryFrames[0].packageHint ?? extractPackageName(libraryFrames[0].location)
});
}
}
diff --git a/scripts/benchmark-symbolicator.sh b/scripts/benchmark-symbolicator.sh
index 2b969f92..415915a3 100755
--- a/scripts/benchmark-symbolicator.sh
+++ b/scripts/benchmark-symbolicator.sh
@@ -16,7 +16,7 @@ go test -tags oxc ./app/symbolicator/... -count=1
go test -tags oxc ./app/symbolicator/... \
-run '^$' \
- -bench 'BenchmarkBundleParsers|BenchmarkNewResolver|BenchmarkOpenTW' \
+ -bench 'BenchmarkBundleParsers|BenchmarkNewResolver|BenchmarkOpenTW|BenchmarkParseMapping' \
-benchtime "$BENCHTIME" \
-count "$COUNT" \
-timeout 60m \