Skip to content

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

ios-symbolicator (#212)

narrow-adventure840ccc4664e1
diff --git a/.github/workflows/benchmark-processor.yml b/.github/workflows/benchmark-processor.yml
index 641554b2..f441775e 100644
--- a/.github/workflows/benchmark-processor.yml
+++ b/.github/workflows/benchmark-processor.yml
@@ -4,13 +4,14 @@ on:
workflow_dispatch:
inputs:
language:
- description: 'Symbolication language: js (5 impls incl. Honeycomb), dart (traceway-dart-mem/disk), or both'
+ description: 'Symbolication language: js (5 impls incl. Honeycomb), dart (traceway-dart-mem/disk), ios (honeycomb-ios + traceway-ios-mem/disk), or both (js+dart)'
required: true
default: 'js'
type: choice
options:
- js
- dart
+ - ios
- both
scenarios:
description: 'Scenarios to run'
@@ -93,7 +94,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 != 'dart'
+ if: inputs.language == 'js' || inputs.language == 'both' || inputs.language == 'ios'
working-directory: benchmarks/processor
run: |
GOBIN=$PWD/bin go install go.opentelemetry.io/collector/cmd/[email protected]
@@ -107,7 +108,7 @@ jobs:
cd loadgen && go mod tidy && go build -o loadgen . && cd ..
cd corpusgen && go build -o corpusgen .
- name: Build node-app bundle
- if: inputs.language != 'dart'
+ if: inputs.language == 'js' || inputs.language == 'both'
working-directory: testing/symbolication/node-app
run: npm install && npm run build
- name: Assemble artifacts
@@ -122,8 +123,8 @@ 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 artifacts/
- cp ../../testing/symbolication/node-app/dist/app.mjs ../../testing/symbolication/node-app/dist/app.mjs.map artifacts/
+ cp config-honeycomb.yaml config-honeycomb-ios.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
with:
@@ -140,6 +141,7 @@ jobs:
case "${{ inputs.language }}" in
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"]' ;;
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
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.go
index e36a8c8a..4209a6d8 100644
--- a/backend/app/controllers/auth.controller.go
+++ b/backend/app/controllers/auth.controller.go
@@ -165,7 +165,7 @@ func (a authController) Register(c *gin.Context) {
if !validFrameworks[request.Framework] {
traceway.CaptureMessage("Invalid framework received during registration: " + request.Framework)
- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android"})
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android, ios"})
return
}
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.go
index a18620f9..40c64b1e 100644
--- a/backend/app/controllers/clientcontrollers/client.controller.go
+++ b/backend/app/controllers/clientcontrollers/client.controller.go
@@ -135,6 +135,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"
resolveSpan := traceway.StartSpan(c, "report.resolve_stack_traces")
for _, cst := range cf.StackTraces {
@@ -143,6 +144,8 @@ func (e clientController) Report(c *gin.Context) {
resolvedStackTrace = services.ResolveStackTrace(c, projectId, cst.StackTrace, cst.DebugIds)
} else if resolveDart {
resolvedStackTrace = services.ResolveDartStackTrace(c, projectId, cst.StackTrace)
+ } else if resolveIos {
+ resolvedStackTrace = services.ResolveIOSStackTrace(c, projectId, cst.StackTrace)
}
est := cst.ToExceptionStackTrace(ComputeExceptionHash(resolvedStackTrace, cst.IsMessage), request.AppVersion, request.ServerName)
est.StackTrace = resolvedStackTrace
diff --git a/backend/app/controllers/oauth.controller.go b/backend/app/controllers/oauth.controller.go
index e1af91cb..f9c0c230 100644
--- a/backend/app/controllers/oauth.controller.go
+++ b/backend/app/controllers/oauth.controller.go
@@ -212,7 +212,7 @@ func (a oauthController) FinishSetup(c *gin.Context) {
}
if !validFrameworks[request.Framework] {
- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android"})
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android, ios"})
return
}
diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.go
index 8a0b4a5b..c4c8ddef 100644
--- a/backend/app/controllers/project.controller.go
+++ b/backend/app/controllers/project.controller.go
@@ -47,6 +47,7 @@ var validFrameworks = map[string]bool{
// Mobile frameworks
"flutter": true,
"android": true,
+ "ios": true,
}
// Project name validation regex: allows alphanumeric, spaces, hyphens, and underscores
@@ -105,7 +106,7 @@ func (p projectController) CreateProject(c *gin.Context) {
if !validFrameworks[request.Framework] {
traceway.CaptureMessage("Invalid framework received: " + request.Framework)
- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android"})
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android, ios"})
return
}
@@ -152,7 +153,7 @@ func (p projectController) UpdateProject(c *gin.Context) {
return
}
if !validFrameworks[request.Framework] {
- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android"})
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android, ios"})
return
}
diff --git a/backend/app/controllers/symbols.controller.go b/backend/app/controllers/symbols.controller.go
index 75115d05..d9c693d8 100644
--- a/backend/app/controllers/symbols.controller.go
+++ b/backend/app/controllers/symbols.controller.go
@@ -11,8 +11,10 @@ import (
"github.com/tracewayapp/traceway/backend/app/services"
"github.com/tracewayapp/traceway/backend/app/storage"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
"github.com/gin-gonic/gin"
+ "github.com/google/uuid"
traceway "go.tracewayapp.com"
)
@@ -38,9 +40,6 @@ func (s symbolsController) Upload(c *gin.Context) {
uploaded := 0
for _, fileHeader := range files {
- if filepath.Ext(fileHeader.Filename) != ".symbols" {
- continue
- }
if fileHeader.Size > 200<<20 {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("File %s exceeds 200MB limit", fileHeader.Filename)})
return
@@ -58,49 +57,80 @@ func (s symbolsController) Upload(c *gin.Context) {
return
}
- arch := c.PostForm("arch")
- if arch == "" {
- arch = archFromSymbolsFilename(fileHeader.Filename)
- }
- if arch == "" {
- c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("cannot determine arch for %s; pass an 'arch' field", fileHeader.Filename)})
- return
- }
- if !dart.IsValidArch(arch) {
- c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid arch %q for %s; expected an architecture token like arm64, x64, arm, or ia32", arch, fileHeader.Filename)})
- return
- }
-
- buildID, err := dart.ReadBuildID(data)
- if err != nil {
- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("%s is not a valid Dart symbols file: %v", fileHeader.Filename, err)})
- return
- }
-
- debugId := services.NormalizeDartDebugId(c.PostForm("debug_id"))
- if note := services.NormalizeDartDebugId(buildID); note != "" {
- if debugId != "" && debugId != note {
- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("debug_id %s does not match the build-id note %s in %s", debugId, note, fileHeader.Filename)})
+ switch {
+ case ios.IsMachO(data):
+ if !s.uploadIOS(c, projectId, fileHeader.Filename, data) {
+ return
+ }
+ uploaded++
+ case filepath.Ext(fileHeader.Filename) == ".symbols":
+ if !s.uploadDart(c, projectId, fileHeader.Filename, data) {
return
}
- debugId = note
+ uploaded++
}
- if debugId == "" {
- c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("no debug_id for %s; the file has no build-id note, so pass a 'debug_id' field (the Mach-O UUID)", fileHeader.Filename)})
- return
+ }
+
+ c.JSON(http.StatusOK, gin.H{"uploaded": uploaded})
+}
+
+func (s symbolsController) uploadDart(c *gin.Context, projectId uuid.UUID, filename string, data []byte) bool {
+ arch := c.PostForm("arch")
+ if arch == "" {
+ arch = archFromSymbolsFilename(filename)
+ }
+ if arch == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("cannot determine arch for %s; pass an 'arch' field", filename)})
+ return false
+ }
+ if !dart.IsValidArch(arch) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid arch %q for %s; expected an architecture token like arm64, x64, arm, or ia32", arch, filename)})
+ return false
+ }
+
+ buildID, err := dart.ReadBuildID(data)
+ if err != nil {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("%s is not a valid Dart symbols file: %v", filename, err)})
+ return false
+ }
+
+ debugId := services.NormalizeDartDebugId(c.PostForm("debug_id"))
+ if note := services.NormalizeDartDebugId(buildID); note != "" {
+ if debugId != "" && debugId != note {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("debug_id %s does not match the build-id note %s in %s", debugId, note, filename)})
+ return false
}
+ debugId = note
+ }
+ if debugId == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("no debug_id for %s; the file has no build-id note, so pass a 'debug_id' field (the Mach-O UUID)", filename)})
+ return false
+ }
- key := services.DartSymbolsKey(projectId, debugId, arch)
+ key := services.DartSymbolsKey(projectId, debugId, arch)
+ if err := storage.Store.Write(c, key, data); err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to write symbols to storage: %w", err))
+ return false
+ }
+ services.InvalidateDartSymbols(key)
+ return true
+}
+
+func (s symbolsController) uploadIOS(c *gin.Context, projectId uuid.UUID, filename string, data []byte) bool {
+ slices, err := ios.ReadUUIDs(data)
+ if err != nil {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": fmt.Sprintf("%s is not a valid dSYM: %v", filename, err)})
+ return false
+ }
+ for _, sl := range slices {
+ key := services.IOSSymbolsKey(projectId, sl.UUID)
if err := storage.Store.Write(c, key, data); err != nil {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to write symbols to storage: %w", err))
- return
+ return false
}
- services.InvalidateDartSymbols(key)
-
- uploaded++
+ services.InvalidateIOSSymbols(key)
}
-
- c.JSON(http.StatusOK, gin.H{"uploaded": uploaded})
+ return true
}
func archFromSymbolsFilename(name string) string {
diff --git a/backend/app/controllers/symbols_test.go b/backend/app/controllers/symbols_test.go
new file mode 100644
index 00000000..480a31c7
--- /dev/null
+++ b/backend/app/controllers/symbols_test.go
@@ -0,0 +1,111 @@
+package controllers
+
+import (
+ "bytes"
+ "context"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/middleware"
+ "github.com/tracewayapp/traceway/backend/app/services"
+ "github.com/tracewayapp/traceway/backend/app/storage"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+)
+
+type memStore struct {
+ mu sync.Mutex
+ data map[string][]byte
+}
+
+func newMemStore() *memStore { return &memStore{data: map[string][]byte{}} }
+
+func (s *memStore) Write(_ context.Context, k string, d []byte) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.data[k] = d
+ return nil
+}
+
+func (s *memStore) Read(_ context.Context, k string) ([]byte, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if d, ok := s.data[k]; ok {
+ return d, nil
+ }
+ return nil, storage.ErrNotFound
+}
+
+func (s *memStore) Delete(_ context.Context, k string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ delete(s.data, k)
+ return nil
+}
+
+func runSymbolsUpload(t *testing.T, projectId uuid.UUID, filename string, data []byte) *httptest.ResponseRecorder {
+ t.Helper()
+ var body bytes.Buffer
+ w := multipart.NewWriter(&body)
+ fw, _ := w.CreateFormFile("files", filename)
+ fw.Write(data)
+ 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))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func TestUploadIOSFatStoresPerSlice(t *testing.T) {
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store := newMemStore()
+ storage.Store = store
+
+ projectId := uuid.New()
+ rec := runSymbolsUpload(t, projectId, "App", iosUploadFixture(t, "sample_fat.dsym"))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
+ }
+ for _, u := range []string{"3185fc2b69b738638f132803dac76198", "7b1d8aee3ed8339e88b1595d0f815ffe"} {
+ if _, ok := store.data[services.IOSSymbolsKey(projectId, u)]; !ok {
+ t.Errorf("missing stored dSYM for slice %s", u)
+ }
+ }
+}
+
+func TestUploadIOSSkipsNonSymbolFile(t *testing.T) {
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store := newMemStore()
+ storage.Store = store
+
+ rec := runSymbolsUpload(t, uuid.New(), "junk.bin", []byte("not a symbol file"))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
+ }
+ if len(store.data) != 0 {
+ t.Errorf("expected nothing stored for a non-Mach-O/non-.symbols file, got %d keys", len(store.data))
+ }
+}
diff --git a/backend/app/services/ios_symbolicator.go b/backend/app/services/ios_symbolicator.go
new file mode 100644
index 00000000..da185027
--- /dev/null
+++ b/backend/app/services/ios_symbolicator.go
@@ -0,0 +1,108 @@
+package services
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/tracewayapp/traceway/backend/app/storage"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/twcache"
+
+ "github.com/google/uuid"
+ traceway "go.tracewayapp.com"
+)
+
+func IOSSymbolsKey(projectId uuid.UUID, debugId string) string {
+ return fmt.Sprintf("iossymbols/%s/%s.dsym", projectId, ios.NormalizeUUID(debugId))
+}
+
+func iosFlatKey(symbolsKey string) string {
+ return strings.TrimSuffix(symbolsKey, ".dsym") + ".tw"
+}
+
+func ResolveIOSStackTrace(ctx context.Context, projectId uuid.UUID, rawTrace string) string {
+ if !ios.IsIOSTrace(rawTrace) {
+ return rawTrace
+ }
+ trace := ios.ParseTrace(rawTrace)
+ if len(trace.Frames) == 0 {
+ return rawTrace
+ }
+ arch := trace.Arch
+ if arch == "" {
+ arch = "arm64"
+ }
+
+ local := map[string]borrow{}
+ defer releaseBorrows(local)
+
+ lookup := func(debugID string, off uint64) []ios.SymFrame {
+ if debugID == "" {
+ return nil
+ }
+ symbolsKey := IOSSymbolsKey(projectId, debugID)
+ cacheKey := iosFlatKey(symbolsKey)
+ if sharedCache.IsNegative(cacheKey) {
+ return nil
+ }
+ data := getBlob(ctx, cacheKey, loadIOSBlob(cacheKey, symbolsKey, debugID, arch), local)
+ if data == nil {
+ return nil
+ }
+ return ios.LookupFlat(data, off)
+ }
+
+ out := ios.RenderResolved(trace, iosErrorPreamble(rawTrace), lookup)
+ if out == "" {
+ return rawTrace
+ }
+ return out
+}
+
+func iosErrorPreamble(raw string) string {
+ lines := strings.Split(raw, "\n")
+ cut := len(lines)
+ for i, ln := range lines {
+ if strings.HasPrefix(strings.TrimSpace(ln), "***") {
+ cut = i
+ break
+ }
+ }
+ 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) {
+ base := context.WithoutCancel(ctx)
+
+ if tw, err := readWithTimeout(base, cacheKey); err == nil {
+ if ios.ValidFlat(tw) {
+ return tw, nil
+ }
+ } else if !isStorageNotFound(err) {
+ traceway.CaptureException(fmt.Errorf("failed to read ios flat artifact, rebuilding (key=%s): %w", cacheKey, err))
+ }
+
+ dsym, err := readWithTimeout(base, symbolsKey)
+ if err != nil {
+ return nil, err
+ }
+ blob, buildErr := ios.BuildFlat(dsym, debugID, arch)
+ if buildErr != nil {
+ return nil, fmt.Errorf("failed to build ios flat artifact (key=%s): %w", symbolsKey, buildErr)
+ }
+ if werr := storage.Store.Write(base, cacheKey, blob); werr != nil {
+ traceway.CaptureException(fmt.Errorf("failed to persist ios flat artifact (key=%s): %w", cacheKey, werr))
+ }
+ return blob, nil
+ }
+}
+
+func InvalidateIOSSymbols(keys ...string) {
+ for _, k := range keys {
+ cacheKey := iosFlatKey(k)
+ sharedCache.Invalidate(cacheKey)
+ _ = storage.Store.Delete(context.Background(), cacheKey)
+ }
+}
diff --git a/backend/app/services/ios_symbolicator_test.go b/backend/app/services/ios_symbolicator_test.go
new file mode 100644
index 00000000..68485449
--- /dev/null
+++ b/backend/app/services/ios_symbolicator_test.go
@@ -0,0 +1,144 @@
+package services
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/storage"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
+
+ "github.com/google/uuid"
+)
+
+const iosFixtureDir = "../symbolicator/ios/fixtures/sample"
+const iosFixtureUUID = "2dd71042118432be8f92dd4e3d3fe24a"
+
+func readIOSFixture(t *testing.T, name string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(iosFixtureDir, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func TestResolveIOSStackTrace(t *testing.T) {
+ useMemCache(t)
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store := newDartMemStore()
+ storage.Store = store
+
+ projectId := uuid.New()
+ store.data[IOSSymbolsKey(projectId, iosFixtureUUID)] = readIOSFixture(t, "sample.dsym")
+
+ raw := string(readIOSFixture(t, "trace.txt"))
+ out := ResolveIOSStackTrace(context.Background(), projectId, raw)
+
+ got := resolvedFrameLines(out)
+ want := expectedLines(readIOSFixture(t, "expected.txt"))
+ if len(got) != len(want) {
+ t.Fatalf("frame count: got %d want %d\nout:\n%s", len(got), len(want), out)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("frame %d: got %q want %q", i, got[i], want[i])
+ }
+ }
+ if !strings.HasPrefix(out, "SampleError: boom") {
+ t.Errorf("error preamble not preserved:\n%s", out)
+ }
+}
+
+func TestResolveIOSStackTraceNoSymbols(t *testing.T) {
+ useMemCache(t)
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ storage.Store = newDartMemStore()
+
+ raw := string(readIOSFixture(t, "trace.txt"))
+ out := ResolveIOSStackTrace(context.Background(), uuid.New(), raw)
+
+ if strings.Contains(out, "leaf (") {
+ t.Errorf("did not expect symbolication without uploaded symbols:\n%s", out)
+ }
+ if !strings.Contains(out, "sample+0x460") {
+ t.Errorf("unresolved frame should fall back to image+offset:\n%s", out)
+ }
+}
+
+func TestResolveIOSStackTraceInvalidationParity(t *testing.T) {
+ useMemCache(t)
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store := newDartMemStore()
+ storage.Store = store
+
+ projectId := uuid.New()
+ raw := string(readIOSFixture(t, "trace.txt"))
+
+ if out := ResolveIOSStackTrace(context.Background(), projectId, raw); strings.Contains(out, "leaf (") {
+ t.Fatal("did not expect symbolication before upload")
+ }
+
+ key := IOSSymbolsKey(projectId, iosFixtureUUID)
+ store.data[key] = readIOSFixture(t, "sample.dsym")
+ InvalidateIOSSymbols(key)
+
+ out := ResolveIOSStackTrace(context.Background(), projectId, raw)
+ if !strings.Contains(out, "leaf (") {
+ t.Errorf("symbols not picked up after invalidation:\n%s", out)
+ }
+}
+
+func TestIOSSymbolsColdBuildsAndCachesFlat(t *testing.T) {
+ useMemCache(t)
+ prev := storage.Store
+ defer func() { storage.Store = prev }()
+ store := newDartMemStore()
+ storage.Store = store
+
+ projectId := uuid.New()
+ dsymKey := IOSSymbolsKey(projectId, iosFixtureUUID)
+ store.data[dsymKey] = readIOSFixture(t, "sample.dsym")
+ raw := string(readIOSFixture(t, "trace.txt"))
+
+ if out := ResolveIOSStackTrace(context.Background(), projectId, raw); !strings.Contains(out, "leaf (") {
+ t.Fatalf("first resolve did not symbolicate:\n%s", out)
+ }
+
+ twKey := iosFlatKey(dsymKey)
+ store.mu.Lock()
+ flat, hasFlat := store.data[twKey]
+ store.mu.Unlock()
+ if !hasFlat {
+ t.Fatalf("expected a built .tw artifact at %s", twKey)
+ }
+ if !ios.ValidFlat(flat) {
+ t.Error("persisted .tw artifact is invalid")
+ }
+ t.Logf("built .tw %d bytes from dSYM %d bytes", len(flat), len(store.data[dsymKey]))
+
+ sharedCache = newSymbolicatorCache()
+ store.mu.Lock()
+ delete(store.data, dsymKey)
+ store.mu.Unlock()
+
+ if out := ResolveIOSStackTrace(context.Background(), projectId, raw); !strings.Contains(out, "leaf (") {
+ t.Errorf("cold load from .tw failed:\n%s", out)
+ }
+}
+
+func TestIOSSymbolsKeyForms(t *testing.T) {
+ pid := uuid.New()
+ dashed := "2DD7-1042-1184-32BE-8F92-DD4E3D3FE24A"
+ if IOSSymbolsKey(pid, dashed) != IOSSymbolsKey(pid, iosFixtureUUID) {
+ t.Error("dashed/uppercase UUID must produce the same key as normalized hex")
+ }
+ if !strings.HasSuffix(IOSSymbolsKey(pid, iosFixtureUUID), "/"+iosFixtureUUID+".dsym") {
+ t.Errorf("key %q should be <uuid>.dsym", IOSSymbolsKey(pid, iosFixtureUUID))
+ }
+}
diff --git a/backend/app/services/sourcemap_resolver.go b/backend/app/services/sourcemap_resolver.go
index 2815e4ea..3ca3d88a 100644
--- a/backend/app/services/sourcemap_resolver.go
+++ b/backend/app/services/sourcemap_resolver.go
@@ -100,6 +100,14 @@ type borrow struct {
done func()
}
+func releaseBorrows(local map[string]borrow) {
+ for _, br := range local {
+ if br.done != nil {
+ br.done()
+ }
+ }
+}
+
func ResolveStackTrace(ctx context.Context, projectId uuid.UUID, stackTrace string, debugIds map[string]string) string {
prefix := SourceMapStorageKey(projectId, "")
@@ -109,13 +117,7 @@ func ResolveStackTrace(ctx context.Context, projectId uuid.UUID, stackTrace stri
maxFrames := 50
local := map[string]borrow{}
- defer func() {
- for _, br := range local {
- if br.done != nil {
- br.done()
- }
- }
- }()
+ defer releaseBorrows(local)
for _, line := range lines {
if framesResolved >= maxFrames {
diff --git a/backend/app/services/symbolicator_cache.go b/backend/app/services/symbolicator_cache.go
index 6eaf1f0f..6ed39ce5 100644
--- a/backend/app/services/symbolicator_cache.go
+++ b/backend/app/services/symbolicator_cache.go
@@ -7,6 +7,7 @@ import (
"github.com/tracewayapp/traceway/backend/app/storage"
"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"
@@ -14,7 +15,7 @@ import (
)
func validArtifact(b []byte) bool {
- return sourcemap.ValidTW(b) || dart.ValidFlat(b)
+ return sourcemap.ValidTW(b) || dart.ValidFlat(b) || ios.ValidFlat(b)
}
var sharedCache = newSymbolicatorCache()
diff --git a/backend/app/symbolicator/ios/build.go b/backend/app/symbolicator/ios/build.go
new file mode 100644
index 00000000..de3eec0c
--- /dev/null
+++ b/backend/app/symbolicator/ios/build.go
@@ -0,0 +1,387 @@
+package ios
+
+import (
+ "debug/dwarf"
+ "encoding/binary"
+ "path/filepath"
+ "sort"
+)
+
+const maxInlineFrames = 64
+
+func BuildFlat(dsymBytes []byte, uuid, arch string) ([]byte, error) {
+ data, textVMAddr, found, err := dwarfForSlice(dsymBytes, uuid, arch)
+ if err != nil {
+ return nil, err
+ }
+ return flatten(data, textVMAddr, found).marshal(), nil
+}
+
+type flatBuilder struct {
+ textVMAddr uint64
+ uuid string
+
+ entries []flatEntry
+ frames []flatFrame
+ files []string
+ fns []string
+}
+
+type flatEntry struct {
+ pc, hi uint64
+ frameStart uint32
+ frameCount uint32
+}
+
+type flatFrame struct {
+ fileIdx int32
+ line int32
+ col int32
+ fnIdx int32
+}
+
+type funcRange struct {
+ low, high uint64
+ off dwarf.Offset
+}
+
+type lineRow struct {
+ addr, end uint64
+ file string
+ line, col int
+}
+
+func flatten(data *dwarf.Data, textVMAddr uint64, uuid string) *flatBuilder {
+ f := &flatBuilder{textVMAddr: textVMAddr, uuid: uuid}
+ files := newInterner()
+ fns := newInterner()
+
+ rdr := data.Reader()
+ for {
+ cu, err := rdr.Next()
+ if err != nil || cu == nil {
+ break
+ }
+ if cu.Tag != dwarf.TagCompileUnit {
+ rdr.SkipChildren()
+ continue
+ }
+
+ lr, lrErr := data.LineReader(cu)
+
+ topFuncs, bounds := collectFuncsAndBounds(data, rdr)
+ if lrErr != nil || lr == nil || len(topFuncs) == 0 {
+ continue
+ }
+ sort.Slice(topFuncs, func(i, j int) bool { return topFuncs[i].low < topFuncs[j].low })
+ lineFiles := lr.Files()
+
+ var raw []dwarf.LineEntry
+ for {
+ var le dwarf.LineEntry
+ if err := lr.Next(&le); err != nil {
+ break
+ }
+ raw = append(raw, le)
+ }
+ var rows []lineRow
+ for i := 0; i+1 < len(raw); i++ {
+ le := raw[i]
+ if le.EndSequence {
+ continue
+ }
+ end := raw[i+1].Address
+ if end <= le.Address {
+ continue
+ }
+ file := ""
+ if le.File != nil {
+ file = le.File.Name
+ }
+ rows = append(rows, lineRow{addr: le.Address, end: end, file: file, line: le.Line, col: le.Column})
+ bounds = append(bounds, le.Address, end)
+ }
+ sort.Slice(rows, func(i, j int) bool { return rows[i].addr < rows[j].addr })
+ bounds = sortUnique(bounds)
+
+ var lastFrames []SymFrame
+ for bi := 0; bi+1 < len(bounds); bi++ {
+ a, b := bounds[bi], bounds[bi+1]
+ fn := findFunc(topFuncs, a)
+ if fn == nil {
+ lastFrames = nil
+ continue
+ }
+ var chain []*dwarf.Entry
+ cr := data.Reader()
+ cr.Seek(fn.off)
+ descend(data, cr, a, &chain)
+ if len(chain) == 0 {
+ lastFrames = nil
+ continue
+ }
+ lf, ll, lc := rowAt(rows, a)
+ sfs := framesFromChain(data, chain, lineFiles, lf, ll, lc)
+
+ if lastFrames != nil && len(f.entries) > 0 && f.entries[len(f.entries)-1].hi == a && sameFrames(sfs, lastFrames) {
+ f.entries[len(f.entries)-1].hi = b
+ continue
+ }
+ start := uint32(len(f.frames))
+ for _, sf := range sfs {
+ f.frames = append(f.frames, flatFrame{
+ fileIdx: files.intern(normalizeFilePath(sf.File)),
+ line: int32(sf.Line),
+ col: int32(sf.Col),
+ fnIdx: fns.intern(sf.Function),
+ })
+ }
+ f.entries = append(f.entries, flatEntry{pc: a, hi: b, frameStart: start, frameCount: uint32(len(sfs))})
+ lastFrames = sfs
+ }
+ }
+
+ f.files = files.list
+ f.fns = fns.list
+ sort.Slice(f.entries, func(i, j int) bool { return f.entries[i].pc < f.entries[j].pc })
+ return f
+}
+
+func collectFuncsAndBounds(d *dwarf.Data, rdr *dwarf.Reader) ([]funcRange, []uint64) {
+ var funcs []funcRange
+ var bounds []uint64
+ depth := 0
+ for {
+ e, err := rdr.Next()
+ if err != nil || e == nil {
+ return funcs, bounds
+ }
+ if e.Tag == 0 {
+ depth--
+ if depth < 0 {
+ return funcs, bounds
+ }
+ continue
+ }
+ if e.Tag == dwarf.TagSubprogram || e.Tag == dwarf.TagInlinedSubroutine {
+ if rs, rerr := d.Ranges(e); rerr == nil {
+ for _, rg := range rs {
+ if rg[1] > rg[0] {
+ bounds = append(bounds, rg[0], rg[1])
+ if e.Tag == dwarf.TagSubprogram && depth == 0 {
+ funcs = append(funcs, funcRange{low: rg[0], high: rg[1], off: e.Offset})
+ }
+ }
+ }
+ }
+ }
+ if e.Children {
+ depth++
+ }
+ }
+}
+
+func findFunc(funcs []funcRange, addr uint64) *funcRange {
+ i := sort.Search(len(funcs), func(i int) bool { return funcs[i].low > addr }) - 1
+ if i >= 0 && addr >= funcs[i].low && addr < funcs[i].high {
+ return &funcs[i]
+ }
+ return nil
+}
+
+func rowAt(rows []lineRow, addr uint64) (string, int, int) {
+ i := sort.Search(len(rows), func(i int) bool { return rows[i].addr > addr }) - 1
+ if i >= 0 && addr >= rows[i].addr && addr < rows[i].end {
+ return rows[i].file, rows[i].line, rows[i].col
+ }
+ return "", 0, 0
+}
+
+func sortUnique(xs []uint64) []uint64 {
+ if len(xs) < 2 {
+ return xs
+ }
+ sort.Slice(xs, func(i, j int) bool { return xs[i] < xs[j] })
+ out := xs[:1]
+ for _, x := range xs[1:] {
+ if x != out[len(out)-1] {
+ out = append(out, x)
+ }
+ }
+ return out
+}
+
+func sameFrames(a, b []SymFrame) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func framesFromChain(d *dwarf.Data, chain []*dwarf.Entry, files []*dwarf.LineFile, leafFile string, leafLine, leafCol int) []SymFrame {
+ if len(chain) > maxInlineFrames {
+ chain = chain[len(chain)-maxInlineFrames:]
+ }
+ out := make([]SymFrame, len(chain))
+ for i := len(chain) - 1; i >= 0; i-- {
+ pos := len(chain) - 1 - i
+ sf := SymFrame{Function: nameOf(d, chain[i])}
+ if i == len(chain)-1 {
+ sf.File, sf.Line, sf.Col = leafFile, leafLine, leafCol
+ } else {
+ inner := chain[i+1]
+ if v, ok := inner.Val(dwarf.AttrCallFile).(int64); ok && int(v) < len(files) && files[v] != nil {
+ sf.File = files[v].Name
+ }
+ if v, ok := inner.Val(dwarf.AttrCallLine).(int64); ok {
+ sf.Line = int(v)
+ }
+ if v, ok := inner.Val(dwarf.AttrCallColumn).(int64); ok {
+ sf.Col = int(v)
+ }
+ }
+ out[pos] = sf
+ }
+ return out
+}
+
+func descend(d *dwarf.Data, r *dwarf.Reader, pc uint64, chain *[]*dwarf.Entry) {
+ for {
+ e, err := r.Next()
+ if err != nil || e == nil || e.Tag == 0 {
+ return
+ }
+ scope := e.Tag == dwarf.TagSubprogram || e.Tag == dwarf.TagInlinedSubroutine
+ block := e.Tag == dwarf.TagLexDwarfBlock
+ if (scope || block) && rangesContain(d, e, pc) {
+ if scope {
+ *chain = append(*chain, e)
+ }
+ if e.Children {
+ descend(d, r, pc, chain)
+ }
+ return
+ }
+ if e.Children {
+ r.SkipChildren()
+ }
+ }
+}
+
+func rangesContain(d *dwarf.Data, e *dwarf.Entry, pc uint64) bool {
+ rs, err := d.Ranges(e)
+ if err != nil {
+ return false
+ }
+ for _, r := range rs {
+ if pc >= r[0] && pc < r[1] {
+ return true
+ }
+ }
+ return false
+}
+
+func nameOf(d *dwarf.Data, e *dwarf.Entry) string {
+ if n, ok := e.Val(dwarf.AttrName).(string); ok && n != "" {
+ return n
+ }
+ for _, attr := range []dwarf.Attr{dwarf.AttrAbstractOrigin, dwarf.AttrSpecification} {
+ if off, ok := e.Val(attr).(dwarf.Offset); ok {
+ r := d.Reader()
+ r.Seek(off)
+ if ref, err := r.Next(); err == nil && ref != nil {
+ if n := nameOf(d, ref); n != "" {
+ return n
+ }
+ }
+ }
+ }
+ return "<unknown>"
+}
+
+func normalizeFilePath(path string) string {
+ if path == "" {
+ return path
+ }
+ return filepath.Base(path)
+}
+
+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 (f *flatBuilder) marshal() []byte {
+ le := binary.LittleEndian
+ fileOffsets, fileBlob := encodeStringTable(f.files)
+ fnOffsets, fnBlob := encodeStringTable(f.fns)
+
+ size := dwHeaderSize +
+ len(f.entries)*flatEntrySize +
+ len(f.frames)*flatFrameSize +
+ len(fileOffsets)*4 + len(fileBlob) +
+ len(fnOffsets)*4 + len(fnBlob) +
+ len(f.uuid)
+
+ out := make([]byte, 0, size)
+ out = append(out, twMagic[:]...)
+ out = le.AppendUint32(out, twVersion)
+ out = le.AppendUint64(out, f.textVMAddr)
+ out = le.AppendUint64(out, 0)
+ out = le.AppendUint32(out, uint32(len(f.entries)))
+ out = le.AppendUint32(out, uint32(len(f.frames)))
+ out = le.AppendUint32(out, uint32(len(f.files)))
+ out = le.AppendUint32(out, uint32(len(f.fns)))
+ out = le.AppendUint32(out, uint32(len(f.uuid)))
+ out = le.AppendUint32(out, 0)
+ for _, e := range f.entries {
+ out = le.AppendUint64(out, e.pc)
+ out = le.AppendUint64(out, e.hi)
+ out = le.AppendUint32(out, e.frameStart)
+ out = le.AppendUint32(out, e.frameCount)
+ }
+ for _, fr := range f.frames {
+ out = le.AppendUint32(out, uint32(fr.fileIdx))
+ out = le.AppendUint32(out, uint32(fr.line))
+ out = le.AppendUint32(out, uint32(fr.col))
+ out = le.AppendUint32(out, uint32(fr.fnIdx))
+ }
+ for _, off := range fileOffsets {
+ out = le.AppendUint32(out, off)
+ }
+ out = append(out, fileBlob...)
+ for _, off := range fnOffsets {
+ out = le.AppendUint32(out, off)
+ }
+ out = append(out, fnBlob...)
+ out = append(out, f.uuid...)
+ return out
+}
+
+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
+}
diff --git a/backend/app/symbolicator/ios/fixtures/sample/expected.txt b/backend/app/symbolicator/ios/fixtures/sample/expected.txt
new file mode 100644
index 00000000..fbbbc931
--- /dev/null
+++ b/backend/app/symbolicator/ios/fixtures/sample/expected.txt
@@ -0,0 +1,4 @@
+leaf (sample.c:7:18)
+compute (sample.c:14)
+main (sample.c:18)
+UnknownLib+0x1234
diff --git a/backend/app/symbolicator/ios/fixtures/sample/sample.c b/backend/app/symbolicator/ios/fixtures/sample/sample.c
new file mode 100644
index 00000000..353fea84
--- /dev/null
+++ b/backend/app/symbolicator/ios/fixtures/sample/sample.c
@@ -0,0 +1,22 @@
+// Fixture source for the dSYM symbolication round-trip test.
+// Built with -O1 so always_inline produces a DWARF inlined_subroutine, which
+// exercises inline-frame reconstruction in flatten()/LookupFlat().
+#include <stdio.h>
+
+__attribute__((noinline)) int leaf(int x) {
+ return x * x + 1;
+}
+
+static __attribute__((always_inline)) inline int inlined_helper(int x) {
+ return leaf(x) + x;
+}
+
+__attribute__((noinline)) int compute(int x) {
+ return inlined_helper(x) + 2;
+}
+
+int main(int argc, char** argv) {
+ int r = compute(argc);
+ printf("%d\n", r);
+ return r;
+}
diff --git a/backend/app/symbolicator/ios/fixtures/sample/sample.dsym b/backend/app/symbolicator/ios/fixtures/sample/sample.dsym
new file mode 100644
index 00000000..779ce3b9
Binary files /dev/null and b/backend/app/symbolicator/ios/fixtures/sample/sample.dsym differ
diff --git a/backend/app/symbolicator/ios/fixtures/sample/sample_fat.dsym b/backend/app/symbolicator/ios/fixtures/sample/sample_fat.dsym
new file mode 100644
index 00000000..6e10390c
Binary files /dev/null and b/backend/app/symbolicator/ios/fixtures/sample/sample_fat.dsym differ
diff --git a/backend/app/symbolicator/ios/fixtures/sample/trace.txt b/backend/app/symbolicator/ios/fixtures/sample/trace.txt
new file mode 100644
index 00000000..15ebb609
--- /dev/null
+++ b/backend/app/symbolicator/ios/fixtures/sample/trace.txt
@@ -0,0 +1,7 @@
+SampleError: boom
+*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
+os: ios arch: arm64
+#00 2dd71042118432be8f92dd4e3d3fe24a 0x460 sample
+#01 2dd71042118432be8f92dd4e3d3fe24a 0x478 sample
+#02 2dd71042118432be8f92dd4e3d3fe24a 0x494 sample
+#03 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 0x1234 UnknownLib
diff --git a/backend/app/symbolicator/ios/fixtures/sample/trace_honeycomb.txt b/backend/app/symbolicator/ios/fixtures/sample/trace_honeycomb.txt
new file mode 100644
index 00000000..7806cf57
--- /dev/null
+++ b/backend/app/symbolicator/ios/fixtures/sample/trace_honeycomb.txt
@@ -0,0 +1,6 @@
+SampleError: boom
+os: ios arch: arm64
+0 sample 0x0000000100000460 2DD71042-1184-32BE-8F92-DD4E3D3FE24A + 1120
+1 sample 0x0000000100000478 2DD71042-1184-32BE-8F92-DD4E3D3FE24A + 1144
+2 sample 0x0000000100000494 2DD71042-1184-32BE-8F92-DD4E3D3FE24A + 1172
+3 UnknownLib 0x0000000100001234 AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA + 4660
diff --git a/backend/app/symbolicator/ios/flat.go b/backend/app/symbolicator/ios/flat.go
new file mode 100644
index 00000000..c12f9f35
--- /dev/null
+++ b/backend/app/symbolicator/ios/flat.go
@@ -0,0 +1,153 @@
+package ios
+
+import (
+ "encoding/binary"
+ "fmt"
+ "sort"
+)
+
+type SymFrame struct {
+ Function string
+ File string
+ Line int
+ Col int
+}
+
+func (s SymFrame) Location() string {
+ if s.Line <= 0 {
+ return s.File
+ }
+ if s.Col <= 0 {
+ return fmt.Sprintf("%s:%d", s.File, s.Line)
+ }
+ return fmt.Sprintf("%s:%d:%d", s.File, s.Line, s.Col)
+}
+
+var twMagic = [4]byte{'T', 'W', 'I', 'O'}
+
+const (
+ twVersion = 1
+ flatEntrySize = 24
+ flatFrameSize = 16
+ dwHeaderSize = 48
+)
+
+type flatLayout struct {
+ base uint64
+ entryCount int
+ framesOff int
+ frameCount int
+ fileTableOff int
+ filesCount int
+ fnTableOff int
+ fnsCount int
+}
+
+func readFlatLayout(data []byte) (flatLayout, bool) {
+ var l flatLayout
+ if len(data) < dwHeaderSize {
+ return l, false
+ }
+ le := binary.LittleEndian
+ if data[0] != twMagic[0] || data[1] != twMagic[1] || data[2] != twMagic[2] || data[3] != twMagic[3] {
+ return l, false
+ }
+ if le.Uint32(data[4:]) != twVersion {
+ return l, false
+ }
+ l.base = le.Uint64(data[8:])
+ entryCount := int64(le.Uint32(data[24:]))
+ frameCount := int64(le.Uint32(data[28:]))
+ l.filesCount = int(le.Uint32(data[32:]))
+ l.fnsCount = int(le.Uint32(data[36:]))
+ n := int64(len(data))
+
+ entriesOff := int64(dwHeaderSize)
+ framesOff := entriesOff + entryCount*flatEntrySize
+ fileTableOff := framesOff + frameCount*flatFrameSize
+ if entryCount < 0 || frameCount < 0 || l.filesCount < 0 || l.fnsCount < 0 ||
+ framesOff < entriesOff || fileTableOff < framesOff {
+ return l, false
+ }
+ fileBlobOff := fileTableOff + int64(l.filesCount+1)*4
+ if fileBlobOff > n {
+ return l, false
+ }
+ fileBlobLen := int64(le.Uint32(data[fileTableOff+int64(l.filesCount)*4:]))
+ fnTableOff := fileBlobOff + fileBlobLen
+ fnBlobOff := fnTableOff + int64(l.fnsCount+1)*4
+ if fnTableOff < fileBlobOff || fnBlobOff > n {
+ return l, false
+ }
+ fnBlobLen := int64(le.Uint32(data[fnTableOff+int64(l.fnsCount)*4:]))
+ if fnBlobOff+fnBlobLen > n {
+ return l, false
+ }
+
+ l.entryCount = int(entryCount)
+ l.frameCount = int(frameCount)
+ l.framesOff = int(framesOff)
+ l.fileTableOff = int(fileTableOff)
+ l.fnTableOff = int(fnTableOff)
+ return l, true
+}
+
+func ValidFlat(data []byte) bool {
+ _, ok := readFlatLayout(data)
+ return ok
+}
+
+func LookupFlat(data []byte, off uint64) []SymFrame {
+ l, ok := readFlatLayout(data)
+ if !ok {
+ return nil
+ }
+ pc := l.base + off
+
+ le := binary.LittleEndian
+ entryAt := func(i int) (pcLo, hi uint64, frameStart, frameCount uint32) {
+ rec := data[dwHeaderSize+i*flatEntrySize:]
+ return le.Uint64(rec), le.Uint64(rec[8:]), le.Uint32(rec[16:]), le.Uint32(rec[20:])
+ }
+
+ i := sort.Search(l.entryCount, func(i int) bool {
+ pcLo, _, _, _ := entryAt(i)
+ return pcLo > pc
+ }) - 1
+ if i < 0 {
+ return nil
+ }
+ ePc, eHi, frameStart, frameCount := entryAt(i)
+ if pc < ePc || pc >= eHi {
+ return nil
+ }
+ if uint64(frameStart)+uint64(frameCount) > uint64(l.frameCount) {
+ return nil
+ }
+ out := make([]SymFrame, 0, frameCount)
+ for k := uint32(0); k < frameCount; k++ {
+ rec := data[l.framesOff+int(frameStart+k)*flatFrameSize:]
+ fileIdx := int32(le.Uint32(rec))
+ line := int32(le.Uint32(rec[4:]))
+ col := int32(le.Uint32(rec[8:]))
+ fnIdx := int32(le.Uint32(rec[12:]))
+ file, _ := stringAt(data, l.fileTableOff, l.filesCount, fileIdx)
+ fn, _ := stringAt(data, l.fnTableOff, l.fnsCount, fnIdx)
+ out = append(out, SymFrame{Function: fn, File: file, Line: int(line), Col: int(col)})
+ }
+ return out
+}
+
+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/ios/flat_test.go b/backend/app/symbolicator/ios/flat_test.go
new file mode 100644
index 00000000..e0d3b40e
--- /dev/null
+++ b/backend/app/symbolicator/ios/flat_test.go
@@ -0,0 +1,116 @@
+package ios
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+const fixtureUUID = "2dd71042118432be8f92dd4e3d3fe24a"
+
+func readFixture(t *testing.T, name string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join("fixtures", "sample", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func buildFixtureTW(t *testing.T) []byte {
+ t.Helper()
+ tw, err := BuildFlat(readFixture(t, "sample.dsym"), fixtureUUID, "arm64")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !ValidFlat(tw) {
+ t.Fatal("BuildFlat produced bytes ValidFlat rejects")
+ }
+ return tw
+}
+
+func TestLookupKnownOffsets(t *testing.T) {
+ tw := buildFixtureTW(t)
+ cases := []struct {
+ off uint64
+ fn string
+ loc string
+ }{
+ {0x460, "leaf", "sample.c:7:18"},
+ {0x478, "compute", "sample.c:14"},
+ {0x494, "main", "sample.c:18"},
+ }
+ for _, c := range cases {
+ got := LookupFlat(tw, c.off)
+ if len(got) == 0 {
+ t.Errorf("offset 0x%x did not resolve", c.off)
+ continue
+ }
+ inner := got[0]
+ if inner.Function != c.fn || inner.Location() != c.loc {
+ t.Errorf("offset 0x%x: got %s (%s), want %s (%s)", c.off, inner.Function, inner.Location(), c.fn, c.loc)
+ }
+ }
+}
+
+func TestInlineChain(t *testing.T) {
+ got := LookupFlat(buildFixtureTW(t), 0x47c)
+ if len(got) < 2 {
+ t.Fatalf("offset 0x47c resolved %d frames, want >= 2 (inline): %+v", len(got), got)
+ }
+ if got[0].Function != "inlined_helper" {
+ t.Errorf("innermost = %q, want inlined_helper", got[0].Function)
+ }
+ if got[len(got)-1].Function != "compute" {
+ t.Errorf("outermost = %q, want compute", got[len(got)-1].Function)
+ }
+}
+
+func TestBuildFlatRejectsInvalid(t *testing.T) {
+ for _, b := range [][]byte{nil, []byte("no"), []byte("not a mach-o at all"), make([]byte, 64)} {
+ if _, err := ReadUUIDs(b); err == nil {
+ t.Errorf("ReadUUIDs accepted %d-length non-Mach-O", len(b))
+ }
+ if _, err := BuildFlat(b, "", "arm64"); err == nil {
+ t.Errorf("BuildFlat accepted %d-length non-Mach-O", len(b))
+ }
+ }
+}
+
+func TestValidFlatRejectsBadData(t *testing.T) {
+ for _, b := range [][]byte{nil, []byte("no"), []byte("TWIOxxxx"), []byte("TWDF\x03\x00\x00\x00"), make([]byte, 64)} {
+ if ValidFlat(b) {
+ t.Errorf("ValidFlat=true for %d-length bad input", len(b))
+ }
+ if got := LookupFlat(b, 1); got != nil {
+ t.Errorf("LookupFlat returned %v for bad data", got)
+ }
+ }
+}
+
+func TestIsMachO(t *testing.T) {
+ accept := [][]byte{
+ {0xfe, 0xed, 0xfa, 0xce},
+ {0xfe, 0xed, 0xfa, 0xcf},
+ {0xce, 0xfa, 0xed, 0xfe},
+ {0xcf, 0xfa, 0xed, 0xfe},
+ {0xca, 0xfe, 0xba, 0xbe},
+ {0xbe, 0xba, 0xfe, 0xca},
+ }
+ for _, b := range accept {
+ if !IsMachO(b) {
+ t.Errorf("IsMachO rejected valid magic %x", b)
+ }
+ }
+ reject := [][]byte{
+ nil, {0xfe}, {0x7f, 'E', 'L', 'F'},
+ {0xfd, 0xed, 0xfa, 0xce},
+ {0xfe, 0xed, 0xfa, 0xc0},
+ {'T', 'W', 'I', 'O'},
+ }
+ for _, b := range reject {
+ if IsMachO(b) {
+ t.Errorf("IsMachO accepted invalid magic %x", b)
+ }
+ }
+}
diff --git a/backend/app/symbolicator/ios/macho.go b/backend/app/symbolicator/ios/macho.go
new file mode 100644
index 00000000..fc36ff91
--- /dev/null
+++ b/backend/app/symbolicator/ios/macho.go
@@ -0,0 +1,147 @@
+package ios
+
+import (
+ "bytes"
+ "debug/dwarf"
+ "debug/macho"
+ "fmt"
+)
+
+const cmdUUID = 0x1b
+
+type SliceInfo struct {
+ UUID string
+ Arch string
+}
+
+func isFatMagic(data []byte) bool {
+ return len(data) >= 4 &&
+ (data[0] == 0xca && data[1] == 0xfe && data[2] == 0xba && data[3] == 0xbe ||
+ data[0] == 0xbe && data[1] == 0xba && data[2] == 0xfe && data[3] == 0xca)
+}
+
+func IsMachO(data []byte) bool {
+ if len(data) < 4 {
+ return false
+ }
+ switch {
+ case data[0] == 0xfe && data[1] == 0xed && data[2] == 0xfa && (data[3] == 0xce || data[3] == 0xcf):
+ return true
+ case (data[0] == 0xce || data[0] == 0xcf) && data[1] == 0xfa && data[2] == 0xed && data[3] == 0xfe:
+ return true
+ }
+ return isFatMagic(data)
+}
+
+func machoFiles(data []byte) ([]*macho.File, func(), error) {
+ if len(data) < 4 {
+ return nil, func() {}, fmt.Errorf("not a Mach-O file: too short")
+ }
+ if isFatMagic(data) {
+ fat, err := macho.NewFatFile(bytes.NewReader(data))
+ if err != nil {
+ return nil, func() {}, fmt.Errorf("reading fat Mach-O: %w", err)
+ }
+ files := make([]*macho.File, len(fat.Arches))
+ for i := range fat.Arches {
+ files[i] = fat.Arches[i].File
+ }
+ return files, func() { fat.Close() }, nil
+ }
+ f, err := macho.NewFile(bytes.NewReader(data))
+ if err != nil {
+ return nil, func() {}, fmt.Errorf("not a Mach-O file: %w", err)
+ }
+ return []*macho.File{f}, func() { f.Close() }, nil
+}
+
+func ReadUUIDs(data []byte) ([]SliceInfo, error) {
+ files, done, err := machoFiles(data)
+ if err != nil {
+ return nil, err
+ }
+ defer done()
+ var out []SliceInfo
+ for _, f := range files {
+ uuid := readMachoUUID(f)
+ if uuid == "" {
+ continue
+ }
+ out = append(out, SliceInfo{UUID: uuid, Arch: archFromCPU(f.Cpu)})
+ }
+ if len(out) == 0 {
+ return nil, fmt.Errorf("no Mach-O slice with an LC_UUID")
+ }
+ return out, nil
+}
+
+func dwarfForSlice(data []byte, uuid, arch string) (*dwarf.Data, uint64, string, error) {
+ files, done, err := machoFiles(data)
+ if err != nil {
+ return nil, 0, "", err
+ }
+ defer done()
+
+ uuid = NormalizeUUID(uuid)
+ want := NormalizeArch(arch)
+ var chosen *macho.File
+ if uuid != "" {
+ for _, f := range files {
+ if readMachoUUID(f) == uuid {
+ chosen = f
+ break
+ }
+ }
+ }
+ if chosen == nil {
+ for _, f := range files {
+ if want == "" || NormalizeArch(archFromCPU(f.Cpu)) == want {
+ chosen = f
+ break
+ }
+ }
+ }
+ if chosen == nil && len(files) == 1 {
+ chosen = files[0]
+ }
+ if chosen == nil {
+ return nil, 0, "", fmt.Errorf("no slice matching uuid %q / arch %q in dSYM", uuid, arch)
+ }
+ d, err := chosen.DWARF()
+ if err != nil {
+ return nil, 0, "", fmt.Errorf("reading DWARF: %w", err)
+ }
+ var textVMAddr uint64
+ if seg := chosen.Segment("__TEXT"); seg != nil {
+ textVMAddr = seg.Addr
+ }
+ return d, textVMAddr, readMachoUUID(chosen), nil
+}
+
+func readMachoUUID(f *macho.File) string {
+ for _, l := range f.Loads {
+ lb, ok := l.(macho.LoadBytes)
+ if !ok {
+ continue
+ }
+ raw := lb.Raw()
+ if len(raw) >= 24 && f.ByteOrder.Uint32(raw[0:4]) == cmdUUID {
+ return fmt.Sprintf("%x", raw[8:24])
+ }
+ }
+ return ""
+}
+
+func archFromCPU(c macho.Cpu) string {
+ switch c {
+ case macho.CpuArm64:
+ return "arm64"
+ case macho.CpuAmd64:
+ return "x64"
+ case macho.CpuArm:
+ return "arm"
+ case macho.Cpu386:
+ return "ia32"
+ }
+ return fmt.Sprintf("cpu_%d", uint32(c))
+}
diff --git a/backend/app/symbolicator/ios/macho_test.go b/backend/app/symbolicator/ios/macho_test.go
new file mode 100644
index 00000000..9377e738
--- /dev/null
+++ b/backend/app/symbolicator/ios/macho_test.go
@@ -0,0 +1,80 @@
+package ios
+
+import (
+ "encoding/binary"
+ "testing"
+)
+
+const (
+ fatArm64UUID = "3185fc2b69b738638f132803dac76198"
+ fatArm64eUUID = "7b1d8aee3ed8339e88b1595d0f815ffe"
+)
+
+func embeddedUUID(tw []byte) string {
+ if len(tw) < dwHeaderSize {
+ return ""
+ }
+ n := int(binary.LittleEndian.Uint32(tw[40:]))
+ if n <= 0 || n > len(tw) {
+ return ""
+ }
+ return string(tw[len(tw)-n:])
+}
+
+func TestReadUUIDsThin(t *testing.T) {
+ slices, err := ReadUUIDs(readFixture(t, "sample.dsym"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(slices) != 1 || slices[0].UUID != fixtureUUID || slices[0].Arch != "arm64" {
+ t.Errorf("slices = %+v, want one {%s arm64}", slices, fixtureUUID)
+ }
+}
+
+func TestReadUUIDsFat(t *testing.T) {
+ slices, err := ReadUUIDs(readFixture(t, "sample_fat.dsym"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(slices) != 2 {
+ t.Fatalf("got %d slices, want 2: %+v", len(slices), slices)
+ }
+ got := map[string]string{}
+ for _, s := range slices {
+ got[s.UUID] = s.Arch
+ }
+ if got[fatArm64UUID] != "arm64" || got[fatArm64eUUID] != "arm64" {
+ t.Errorf("fat slices = %+v, want both arch arm64 with the two UUIDs", slices)
+ }
+}
+
+func TestBuildFlatFatSelectsByUUID(t *testing.T) {
+ fat := readFixture(t, "sample_fat.dsym")
+ for _, want := range []string{fatArm64UUID, fatArm64eUUID} {
+ tw, err := BuildFlat(fat, want, "arm64")
+ if err != nil {
+ t.Fatalf("BuildFlat(uuid=%s): %v", want, err)
+ }
+ if got := embeddedUUID(tw); got != want {
+ t.Errorf("BuildFlat(uuid=%s, arm64) built the %s slice, UUID selection failed", want, got)
+ }
+ }
+}
+
+func TestBuildFlatArchFallbackOnUUIDMismatch(t *testing.T) {
+ tw, err := BuildFlat(readFixture(t, "sample.dsym"), "00000000000000000000000000000000", "arm64")
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := LookupFlat(tw, 0x460)
+ if len(got) == 0 || got[0].Function != "leaf" {
+ t.Fatalf("arch fallback failed to resolve: %+v", got)
+ }
+}
+
+func TestBuildFlatNoMatchingSlice(t *testing.T) {
+ fat := readFixture(t, "sample_fat.dsym")
+ if _, err := BuildFlat(fat, "ffffffffffffffffffffffffffffffff", "ppc"); err == nil {
+ t.Error("expected an error for an unknown uuid+arch in a multi-slice dSYM")
+ }
+}
diff --git a/backend/app/symbolicator/ios/normalize.go b/backend/app/symbolicator/ios/normalize.go
new file mode 100644
index 00000000..c986ac4c
--- /dev/null
+++ b/backend/app/symbolicator/ios/normalize.go
@@ -0,0 +1,34 @@
+package ios
+
+import "strings"
+
+func NormalizeUUID(uuid string) string {
+ var b strings.Builder
+ for _, r := range strings.ToLower(strings.TrimSpace(uuid)) {
+ if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+func NormalizeArch(arch string) string {
+ a := strings.ToLower(strings.TrimSpace(arch))
+ switch a {
+ case "x86_64", "x64", "amd64":
+ return "x64"
+ case "aarch64", "arm64", "arm64e":
+ return "arm64"
+ case "armv7", "armv7s", "arm":
+ return "arm"
+ case "ia32", "x86", "i386":
+ return "ia32"
+ }
+ var b strings.Builder
+ for _, r := range a {
+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
diff --git a/backend/app/symbolicator/ios/normalize_test.go b/backend/app/symbolicator/ios/normalize_test.go
new file mode 100644
index 00000000..951c1b4a
--- /dev/null
+++ b/backend/app/symbolicator/ios/normalize_test.go
@@ -0,0 +1,42 @@
+package ios
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestNormalizeUUID(t *testing.T) {
+ cases := map[string]string{
+ "2DD71042-1184-32BE-8F92-DD4E3D3FE24A": "2dd71042118432be8f92dd4e3d3fe24a",
+ " FE66-4295 ": "fe664295",
+ "abcdef0123456789": "abcdef0123456789",
+ "GHIJ": "",
+ }
+ for in, want := range cases {
+ if got := NormalizeUUID(in); got != want {
+ t.Errorf("NormalizeUUID(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestNormalizeArch(t *testing.T) {
+ cases := map[string]string{
+ "arm64": "arm64",
+ "arm64e": "arm64",
+ "aarch64": "arm64",
+ " ARM64": "arm64",
+ "x86_64": "x64",
+ "amd64": "x64",
+ "armv7s": "arm",
+ "i386": "ia32",
+ "../../x": "x",
+ }
+ for in, want := range cases {
+ if got := NormalizeArch(in); got != want {
+ t.Errorf("NormalizeArch(%q) = %q, want %q", in, got, want)
+ }
+ if strings.ContainsAny(NormalizeArch(in), "/.") {
+ t.Errorf("NormalizeArch(%q) leaked a path separator", in)
+ }
+ }
+}
diff --git a/backend/app/symbolicator/ios/stack_frame.go b/backend/app/symbolicator/ios/stack_frame.go
new file mode 100644
index 00000000..e1726005
--- /dev/null
+++ b/backend/app/symbolicator/ios/stack_frame.go
@@ -0,0 +1,159 @@
+package ios
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+const maxFrames = 50
+
+type StackFrame struct {
+ UUID string
+ Offset uint64
+ Image string
+ Raw string
+}
+
+type StackTrace struct {
+ OS string
+ Arch string
+ Frames []StackFrame
+}
+
+var (
+ osArchRe = regexp.MustCompile(`os:\s*(\S+)\s+arch:\s*(\S+)`)
+ frameRe = regexp.MustCompile(`^\s*#(\d+)\s+([0-9a-fA-F]{32})\s+0x([0-9a-fA-F]+)\s*(.*)$`)
+)
+
+func ParseTrace(text string) StackTrace {
+ var t StackTrace
+ for _, line := range strings.Split(text, "\n") {
+ if t.OS == "" {
+ if m := osArchRe.FindStringSubmatch(line); m != nil {
+ t.OS, t.Arch = m[1], m[2]
+ }
+ }
+ if m := frameRe.FindStringSubmatch(line); m != nil {
+ off, _ := strconv.ParseUint(m[3], 16, 64)
+ t.Frames = append(t.Frames, StackFrame{
+ UUID: strings.ToLower(m[2]),
+ Offset: off,
+ Image: strings.TrimSpace(m[4]),
+ Raw: strings.TrimSpace(line),
+ })
+ }
+ }
+ return t
+}
+
+func IsIOSTrace(text string) bool {
+ for _, line := range strings.Split(text, "\n") {
+ if frameRe.MatchString(line) {
+ return true
+ }
+ }
+ return false
+}
+
+func IsIOSLanguage(lang string) bool {
+ switch strings.ToLower(strings.TrimSpace(lang)) {
+ case "swift", "ios":
+ return true
+ default:
+ return false
+ }
+}
+
+func RenderResolved(trace StackTrace, preamble string, lookup func(uuid string, off uint64) []SymFrame) string {
+ var b strings.Builder
+ if preamble != "" {
+ b.WriteString(preamble)
+ b.WriteByte('\n')
+ }
+ n := 0
+ for _, f := range trace.Frames {
+ if n >= maxFrames {
+ break
+ }
+ resolved := lookup(f.UUID, f.Offset)
+ if len(resolved) == 0 {
+ fmt.Fprintf(&b, "#%d %s+0x%x\n", n, frameLabel(f), f.Offset)
+ n++
+ continue
+ }
+ for _, sf := range resolved {
+ if n >= maxFrames {
+ break
+ }
+ fmt.Fprintf(&b, "#%d %s (%s)\n", n, sf.Function, sf.Location())
+ n++
+ }
+ }
+ return strings.TrimRight(b.String(), "\n")
+}
+
+func frameLabel(f StackFrame) string {
+ if f.Image != "" {
+ return f.Image
+ }
+ if len(f.UUID) >= 8 {
+ return f.UUID[:8]
+ }
+ return f.UUID
+}
+
+var (
+ honeycombFrameRe = regexp.MustCompile(`^\s*[0-9]+\s+([\w .+-]+?)\s+0x[0-9a-fA-F]+\s+([\w .+-]*?)\s+\+\s+([0-9]+)\s*$`)
+ honeycombUUIDRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
+)
+
+func IsHoneycombTrace(text string) bool {
+ for _, line := range strings.Split(text, "\n") {
+ if honeycombFrameRe.MatchString(line) {
+ return true
+ }
+ }
+ return false
+}
+
+func ParseHoneycombTrace(text, buildUUID, appExecutable string) StackTrace {
+ var t StackTrace
+ for _, line := range strings.Split(text, "\n") {
+ if t.OS == "" {
+ if m := osArchRe.FindStringSubmatch(line); m != nil {
+ t.OS, t.Arch = m[1], m[2]
+ }
+ }
+ m := honeycombFrameRe.FindStringSubmatch(line)
+ if m == nil {
+ continue
+ }
+ binary := strings.TrimSpace(m[1])
+ ref := strings.TrimSpace(m[2])
+ off, err := strconv.ParseUint(m[3], 10, 64)
+ if err != nil {
+ continue
+ }
+ var uuid, image string
+ switch {
+ case honeycombUUIDRe.MatchString(ref):
+ uuid, image = NormalizeUUID(ref), binary
+ case ref != "" && ref == appExecutable:
+ uuid, image = NormalizeUUID(buildUUID), ref
+ default:
+ continue
+ }
+ if uuid == "" {
+ continue
+ }
+ t.Frames = append(t.Frames, StackFrame{
+ UUID: uuid,
+ Offset: off,
+ Image: image,
+ Raw: strings.TrimSpace(line),
+ })
+ }
+ return t
+}
diff --git a/backend/app/symbolicator/ios/stack_frame_test.go b/backend/app/symbolicator/ios/stack_frame_test.go
new file mode 100644
index 00000000..8e639eaa
--- /dev/null
+++ b/backend/app/symbolicator/ios/stack_frame_test.go
@@ -0,0 +1,112 @@
+package ios
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestParseTrace(t *testing.T) {
+ raw, err := os.ReadFile(filepath.Join("fixtures", "sample", "trace.txt"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ tr := ParseTrace(string(raw))
+
+ if tr.OS != "ios" || tr.Arch != "arm64" {
+ t.Errorf("os/arch = %q/%q, want ios/arm64", tr.OS, tr.Arch)
+ }
+ if len(tr.Frames) != 4 {
+ t.Fatalf("got %d frames, want 4", len(tr.Frames))
+ }
+ f0 := tr.Frames[0]
+ if f0.UUID != "2dd71042118432be8f92dd4e3d3fe24a" || f0.Offset != 0x460 || f0.Image != "sample" {
+ t.Errorf("frame0 = %+v", f0)
+ }
+ if tr.Frames[3].Image != "UnknownLib" || tr.Frames[3].Offset != 0x1234 {
+ t.Errorf("frame3 = %+v", tr.Frames[3])
+ }
+}
+
+func TestIsHoneycombTrace(t *testing.T) {
+ hc := "0 sample 0x100000460 2DD71042-1184-32BE-8F92-DD4E3D3FE24A + 1120"
+ if !IsHoneycombTrace(hc) {
+ t.Error("honeycomb trace not detected")
+ }
+ tw := "#00 2dd71042118432be8f92dd4e3d3fe24a 0x460 sample"
+ if IsHoneycombTrace(tw) {
+ t.Error("traceway trace misdetected as honeycomb")
+ }
+}
+
+func TestParseHoneycombTrace(t *testing.T) {
+ raw, err := os.ReadFile(filepath.Join("fixtures", "sample", "trace_honeycomb.txt"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ tr := ParseHoneycombTrace(string(raw), "", "")
+ if tr.OS != "ios" || tr.Arch != "arm64" {
+ t.Errorf("os/arch = %q/%q, want ios/arm64", tr.OS, tr.Arch)
+ }
+ if len(tr.Frames) != 4 {
+ t.Fatalf("got %d frames, want 4", len(tr.Frames))
+ }
+ f0 := tr.Frames[0]
+ if f0.UUID != "2dd71042118432be8f92dd4e3d3fe24a" || f0.Offset != 0x460 || f0.Image != "sample" {
+ t.Errorf("frame0 = %+v", f0)
+ }
+ if tr.Frames[3].Offset != 0x1234 {
+ t.Errorf("frame3 offset = %#x, want 0x1234", tr.Frames[3].Offset)
+ }
+}
+
+func TestParseHoneycombTraceBinaryName(t *testing.T) {
+ raw := "os: ios arch: arm64\n0 sample 0x100000460 sample + 1120"
+ tr := ParseHoneycombTrace(raw, "2DD71042-1184-32BE-8F92-DD4E3D3FE24A", "sample")
+ if len(tr.Frames) != 1 {
+ t.Fatalf("got %d frames, want 1", len(tr.Frames))
+ }
+ if tr.Frames[0].UUID != "2dd71042118432be8f92dd4e3d3fe24a" || tr.Frames[0].Offset != 0x460 {
+ t.Errorf("frame = %+v", tr.Frames[0])
+ }
+}
+
+func TestParseHoneycombTraceCorpusFormat(t *testing.T) {
+ raw := "os: ios arch: arm64\n" +
+ "0 sample 0x0000000100000460 2DD71042-1184-32BE-8F92-DD4E3D3FE24A + 1120\n" +
+ "1 sample 0x0000000100000494 2dd71042-1184-32be-8f92-dd4e3d3fe24a + 1172"
+ tr := ParseHoneycombTrace(raw, "", "")
+ if len(tr.Frames) != 2 {
+ t.Fatalf("got %d frames, want 2", len(tr.Frames))
+ }
+ if tr.Frames[0].UUID != "2dd71042118432be8f92dd4e3d3fe24a" || tr.Frames[0].Offset != 0x460 || tr.Frames[0].Image != "sample" {
+ t.Errorf("frame0 = %+v", tr.Frames[0])
+ }
+ if tr.Frames[1].UUID != "2dd71042118432be8f92dd4e3d3fe24a" || tr.Frames[1].Offset != 0x494 {
+ t.Errorf("frame1 = %+v", tr.Frames[1])
+ }
+}
+
+func TestParseHoneycombTraceSpacedBinary(t *testing.T) {
+ raw := "12 Chateaux Bufeaux 0x000000010000abcd 6A8CB813-45F6-3652-AD33-778FD1EAB196 + 100436"
+ tr := ParseHoneycombTrace(raw, "", "")
+ if len(tr.Frames) != 1 {
+ t.Fatalf("got %d frames, want 1", len(tr.Frames))
+ }
+ if tr.Frames[0].Image != "Chateaux Bufeaux" || tr.Frames[0].UUID != "6a8cb81345f63652ad33778fd1eab196" || tr.Frames[0].Offset != 100436 {
+ t.Errorf("frame = %+v", tr.Frames[0])
+ }
+}
+
+func TestIsIOSTrace(t *testing.T) {
+ if !IsIOSTrace("os: ios arch: arm64\n#00 2dd71042118432be8f92dd4e3d3fe24a 0x460 sample") {
+ t.Error("valid iOS trace not detected")
+ }
+ dart := "#00 abs 00000001131eca6b _kDartIsolateSnapshotInstructions+0x141e6b"
+ if IsIOSTrace(dart) {
+ t.Error("dart trace misdetected as iOS")
+ }
+ if IsIOSTrace("just some text\nat foo (bar.js:1:2)") {
+ t.Error("js/plain text misdetected as iOS")
+ }
+}
diff --git a/backend/app/symbolicator/otelprocessor/cache.go b/backend/app/symbolicator/otelprocessor/cache.go
index 100278c5..14f04ae0 100644
--- a/backend/app/symbolicator/otelprocessor/cache.go
+++ b/backend/app/symbolicator/otelprocessor/cache.go
@@ -8,12 +8,13 @@ import (
"os"
"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)
+ return sourcemap.ValidTW(b) || dart.ValidFlat(b) || ios.ValidFlat(b)
}
func isObjectNotFound(err error) bool { return errors.Is(err, errObjectNotFound) }
@@ -56,7 +57,7 @@ func cacheKey(url, buildUUID string) string {
return hex.EncodeToString(sum[:]) + ".tw"
}
-func dartCacheKey(symbolsKey string) string {
+func flatCacheKey(symbolsKey string) string {
sum := sha256.Sum256([]byte(symbolsKey))
return hex.EncodeToString(sum[:]) + ".tw"
}
diff --git a/backend/app/symbolicator/otelprocessor/config.go b/backend/app/symbolicator/otelprocessor/config.go
index b70082c7..7f28a3ea 100644
--- a/backend/app/symbolicator/otelprocessor/config.go
+++ b/backend/app/symbolicator/otelprocessor/config.go
@@ -43,6 +43,9 @@ type Config struct {
BuildUUIDAttributeKey string `mapstructure:"build_uuid_attribute_key"`
+ IOSBuildUUIDAttributeKey string `mapstructure:"ios_build_uuid_attribute_key"`
+ AppExecutableAttributeKey string `mapstructure:"app_executable_attribute_key"`
+
SourceMapStoreKey string `mapstructure:"source_map_store"`
LocalSourceMaps LocalSourceMapsConfig `mapstructure:"local_source_maps"`
S3SourceMaps S3SourceMapsConfig `mapstructure:"s3_source_maps"`
@@ -57,6 +60,7 @@ type Config struct {
CacheMaxDiskPct int `mapstructure:"cache_max_disk_pct"`
DartDefaultArch string `mapstructure:"dart_default_arch"`
+ IOSDefaultArch string `mapstructure:"ios_default_arch"`
LanguageAttributeKey string `mapstructure:"language_attribute_key"`
AllowedLanguages []string `mapstructure:"allowed_languages"`
diff --git a/backend/app/symbolicator/otelprocessor/factory.go b/backend/app/symbolicator/otelprocessor/factory.go
index 6be13b8e..c646f420 100644
--- a/backend/app/symbolicator/otelprocessor/factory.go
+++ b/backend/app/symbolicator/otelprocessor/factory.go
@@ -49,6 +49,9 @@ func createDefaultConfig() component.Config {
BuildUUIDAttributeKey: "app.debug.source_map_uuid",
+ IOSBuildUUIDAttributeKey: "app.debug.build_uuid",
+ AppExecutableAttributeKey: "app.bundle.executable",
+
SourceMapStoreKey: fileStoreKey,
LocalSourceMaps: LocalSourceMapsConfig{Path: "."},
@@ -58,6 +61,8 @@ func createDefaultConfig() component.Config {
CacheMaxMB: 2048,
+ IOSDefaultArch: "arm64",
+
LanguageAttributeKey: "telemetry.sdk.language",
}
}
diff --git a/backend/app/symbolicator/otelprocessor/ios_test.go b/backend/app/symbolicator/otelprocessor/ios_test.go
new file mode 100644
index 00000000..db0db855
--- /dev/null
+++ b/backend/app/symbolicator/otelprocessor/ios_test.go
@@ -0,0 +1,266 @@
+package otelprocessor
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "go.opentelemetry.io/collector/pdata/pcommon"
+)
+
+const iosFixtureDir = "../ios/fixtures/sample"
+
+func TestSymbolicateIOSTrace(t *testing.T) {
+ dsym, err := os.ReadFile(filepath.Join(iosFixtureDir, "sample.dsym"))
+ if err != nil {
+ t.Skipf("ios fixture not available (%v)", err)
+ }
+ raw, err := os.ReadFile(filepath.Join(iosFixtureDir, "trace.txt"))
+ if err != nil {
+ t.Skipf("ios fixture trace not available (%v)", err)
+ }
+
+ store := t.TempDir()
+ if err := os.WriteFile(filepath.Join(store, "2dd71042118432be8f92dd4e3d3fe24a.dsym"), dsym, 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.ExceptionTypeAttributeKey, "SampleError")
+ attrs.PutStr(p.cfg.ExceptionMessageAttributeKey, "boom")
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, string(raw))
+
+ p.processRecord(context.Background(), attrs, pcommon.NewMap())
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ for _, want := range []string{"leaf (sample.c:7:18)", "compute (sample.c:14)", "main (sample.c:18)"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("expected resolved frame %q in:\n%s", want, got)
+ }
+ }
+ if !strings.Contains(got, "UnknownLib+0x1234") {
+ t.Errorf("expected unresolved system frame as image+offset in:\n%s", got)
+ }
+ if v, ok := attrs.Get(p.cfg.SymbolicatorFailureAttributeKey); !ok || v.Bool() {
+ t.Errorf("expected symbolicator.failed=false, got %v", v)
+ }
+}
+
+func TestSymbolicateHoneycombIOSTrace(t *testing.T) {
+ dsym, err := os.ReadFile(filepath.Join(iosFixtureDir, "sample.dsym"))
+ if err != nil {
+ t.Skipf("ios fixture not available (%v)", err)
+ }
+ raw, err := os.ReadFile(filepath.Join(iosFixtureDir, "trace_honeycomb.txt"))
+ if err != nil {
+ t.Skipf("honeycomb ios fixture not available (%v)", err)
+ }
+ store := t.TempDir()
+ if err := os.WriteFile(filepath.Join(store, "2dd71042118432be8f92dd4e3d3fe24a.dsym"), dsym, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, string(raw))
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "swift")
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ for _, want := range []string{"leaf (sample.c:7:18)", "compute (sample.c:14)", "main (sample.c:18)"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("expected resolved frame %q in:\n%s", want, got)
+ }
+ }
+ if v, ok := attrs.Get(p.cfg.SymbolicatorFailureAttributeKey); !ok || v.Bool() {
+ t.Errorf("expected symbolicator.failed=false, got %v", v)
+ }
+}
+
+func TestSymbolicateHoneycombIOSBinaryName(t *testing.T) {
+ dsym, err := os.ReadFile(filepath.Join(iosFixtureDir, "sample.dsym"))
+ if err != nil {
+ t.Skipf("ios fixture not available (%v)", err)
+ }
+ store := t.TempDir()
+ if err := os.WriteFile(filepath.Join(store, "2dd71042118432be8f92dd4e3d3fe24a.dsym"), dsym, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, "os: ios arch: arm64\n0 sample 0x100000460 sample + 1120\n2 sample 0x100000494 sample + 1172")
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "swift")
+ resource.PutStr(p.cfg.IOSBuildUUIDAttributeKey, "2DD71042-1184-32BE-8F92-DD4E3D3FE24A")
+ resource.PutStr(p.cfg.AppExecutableAttributeKey, "sample")
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ if !strings.Contains(got, "leaf (sample.c:7:18)") || !strings.Contains(got, "main (sample.c:18)") {
+ t.Errorf("binary-name honeycomb trace not resolved:\n%s", got)
+ }
+}
+
+func TestSymbolicateIOSByLanguageHeader(t *testing.T) {
+ dsym, err := os.ReadFile(filepath.Join(iosFixtureDir, "sample.dsym"))
+ if err != nil {
+ t.Skipf("ios fixture not available (%v)", err)
+ }
+ raw, err := os.ReadFile(filepath.Join(iosFixtureDir, "trace.txt"))
+ if err != nil {
+ t.Skipf("ios fixture trace not available (%v)", err)
+ }
+ store := t.TempDir()
+ if err := os.WriteFile(filepath.Join(store, "2dd71042118432be8f92dd4e3d3fe24a.dsym"), dsym, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, string(raw))
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "swift")
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ if !strings.Contains(got, "leaf (sample.c:7:18)") || !strings.Contains(got, "main (sample.c:18)") {
+ t.Errorf("language-routed iOS trace not resolved:\n%s", got)
+ }
+}
+
+func TestSymbolicateIOSByLanguageHeaderIOSValue(t *testing.T) {
+ dsym, err := os.ReadFile(filepath.Join(iosFixtureDir, "sample.dsym"))
+ if err != nil {
+ t.Skipf("ios fixture not available (%v)", err)
+ }
+ raw, err := os.ReadFile(filepath.Join(iosFixtureDir, "trace.txt"))
+ if err != nil {
+ t.Skipf("ios fixture trace not available (%v)", err)
+ }
+ store := t.TempDir()
+ if err := os.WriteFile(filepath.Join(store, "2dd71042118432be8f92dd4e3d3fe24a.dsym"), dsym, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, string(raw))
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "ios")
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ if got := strAttr(attrs, p.cfg.StackTraceAttributeKey); !strings.Contains(got, "leaf (sample.c:7:18)") {
+ t.Errorf("language=ios did not route to the iOS symbolicator:\n%s", got)
+ }
+}
+
+func TestIOSLanguageLeavesSymbolicStackUntouched(t *testing.T) {
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: t.TempDir()}
+ })
+
+ symbolic := "BoomError: kaboom\n at App.run() (App.swift:12:5)"
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, symbolic)
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "ios")
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ if got := strAttr(attrs, p.cfg.StackTraceAttributeKey); got != symbolic {
+ t.Errorf("symbolic stack was modified:\n got: %q\nwant: %q", got, symbolic)
+ }
+ if _, ok := attrs.Get(p.cfg.SymbolicatorFailureAttributeKey); ok {
+ t.Error("no-op iOS path should not set the failure flag")
+ }
+}
+
+func TestSymbolicateIOSBenchmarkCorpus(t *testing.T) {
+ dsym, err := os.ReadFile(filepath.Join(iosFixtureDir, "sample.dsym"))
+ if err != nil {
+ t.Skipf("ios fixture not available (%v)", err)
+ }
+ store := t.TempDir()
+ synthetic := "00000000000000000000000000000001"
+ if err := os.WriteFile(filepath.Join(store, synthetic+".dsym"), dsym, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: store}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.ExceptionTypeAttributeKey, "IOSError")
+ attrs.PutStr(p.cfg.ExceptionMessageAttributeKey, "bench")
+ attrs.PutStr(p.cfg.StackTraceAttributeKey,
+ "IOSError: bench\nos: ios arch: arm64\n#00 "+synthetic+" 0x460 sample\n#01 "+synthetic+" 0x494 sample")
+ resource := pcommon.NewMap()
+ resource.PutStr(p.cfg.LanguageAttributeKey, "swift")
+
+ p.processRecord(context.Background(), attrs, resource)
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ if !strings.Contains(got, "sample.c") {
+ t.Errorf("expected resolved frames (drain OK marker sample.c):\n%s", got)
+ }
+ if strings.Contains(got, "sample+0x") {
+ t.Errorf("unexpected unresolved frames (drain FAIL marker sample+0x):\n%s", got)
+ }
+}
+
+func TestSymbolicateIOSTraceMissingSymbols(t *testing.T) {
+ raw, err := os.ReadFile(filepath.Join(iosFixtureDir, "trace.txt"))
+ if err != nil {
+ t.Skipf("ios fixture trace not available (%v)", err)
+ }
+
+ p := newTestProcessor(t, func(c *Config) {
+ c.SourceMapStoreKey = fileStoreKey
+ c.LocalSourceMaps = LocalSourceMapsConfig{Path: t.TempDir()}
+ })
+
+ attrs := pcommon.NewMap()
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, string(raw))
+ p.processRecord(context.Background(), attrs, pcommon.NewMap())
+
+ got := strAttr(attrs, p.cfg.StackTraceAttributeKey)
+ if strings.Contains(got, "leaf (") {
+ t.Errorf("did not expect symbolication without artifacts:\n%s", got)
+ }
+ if !strings.Contains(got, "sample+0x460") {
+ t.Errorf("expected stable image+offset frames, got:\n%s", got)
+ }
+ if v, ok := attrs.Get(p.cfg.SymbolicatorFailureAttributeKey); !ok || !v.Bool() {
+ t.Errorf("expected symbolicator.failed=true when no dSYM is available, got %v (present=%v)", v, ok)
+ }
+ if errMsg := strAttr(attrs, p.cfg.SymbolicatorErrorAttributeKey); errMsg == "" {
+ t.Error("expected symbolicator error attribute to be set when symbols are missing")
+ }
+}
diff --git a/backend/app/symbolicator/otelprocessor/store.go b/backend/app/symbolicator/otelprocessor/store.go
index b9710045..55e6185d 100644
--- a/backend/app/symbolicator/otelprocessor/store.go
+++ b/backend/app/symbolicator/otelprocessor/store.go
@@ -19,6 +19,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/tracewayapp/traceway/backend/app/symbolicator/dart"
+ "github.com/tracewayapp/traceway/backend/app/symbolicator/ios"
)
const (
@@ -120,6 +121,19 @@ func (a *artifactStore) getDartSymbols(ctx context.Context, buildID, arch string
return data, nil
}
+func (a *artifactStore) iosSymbolsKey(uuid string) string {
+ return a.key("", ios.NormalizeUUID(uuid)+".dsym")
+}
+
+func (a *artifactStore) getIOSDsym(ctx context.Context, uuid string) ([]byte, error) {
+ key := a.iosSymbolsKey(uuid)
+ data, err := a.store.fetch(ctx, key)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find ios symbols %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 1f3513de..fe05f2aa 100644
--- a/backend/app/symbolicator/otelprocessor/symbolicate.go
+++ b/backend/app/symbolicator/otelprocessor/symbolicate.go
@@ -8,6 +8,7 @@ import (
"strings"
"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/sourcemap/jsstack"
"github.com/tracewayapp/traceway/backend/app/symbolicator/twcache"
@@ -24,6 +25,7 @@ const (
var errMismatchedLength = errors.New("mismatched stacktrace attribute lengths")
var errUnparseableStackTrace = errors.New("unable to parse stack trace")
var errMissingDartBuild = errors.New("dart trace missing build_id or arch")
+var errNoIOSSymbols = errors.New("no ios symbols found")
type symbolicatorProcessor struct {
cfg *Config
@@ -58,11 +60,25 @@ func (p *symbolicatorProcessor) processRecord(ctx context.Context, attrs, resour
}
originalStack := stackVal.Str()
+ lang := strAttr(attrs, p.cfg.LanguageAttributeKey)
+ if lang == "" {
+ lang = strAttr(resource, p.cfg.LanguageAttributeKey)
+ }
+ if ios.IsIOSLanguage(lang) {
+ p.symbolicateIOSTrace(ctx, attrs, resource, originalStack)
+ return
+ }
+
if dart.IsNonSymbolic(originalStack) {
p.symbolicateDartTrace(ctx, attrs, originalStack)
return
}
+ if ios.IsIOSTrace(originalStack) || ios.IsHoneycombTrace(originalStack) {
+ p.symbolicateIOSTrace(ctx, attrs, resource, originalStack)
+ return
+ }
+
buildUUID := ""
if v, ok := resource.Get(p.cfg.BuildUUIDAttributeKey); ok {
buildUUID = v.Str()
@@ -176,7 +192,7 @@ func (p *symbolicatorProcessor) symbolicateDartTrace(ctx context.Context, attrs
return
}
- key := dartCacheKey(p.store.dartSymbolsKey(trace.BuildID, arch))
+ key := flatCacheKey(p.store.dartSymbolsKey(trace.BuildID, arch))
if p.cache.IsNegative(key) {
fail(fmt.Errorf("failed to find dart symbols for build %s/%s", trace.BuildID, arch))
return
@@ -234,6 +250,102 @@ func (p *symbolicatorProcessor) renderDartTrace(attrs pcommon.Map, trace dart.St
return strings.TrimRight(b.String(), "\n")
}
+func (p *symbolicatorProcessor) symbolicateIOSTrace(ctx context.Context, attrs, resource pcommon.Map, rawStack string) {
+ trace := ios.ParseTrace(rawStack)
+ if len(trace.Frames) == 0 {
+ buildUUID := strAttr(resource, p.cfg.IOSBuildUUIDAttributeKey)
+ appExecutable := strAttr(resource, p.cfg.AppExecutableAttributeKey)
+ trace = ios.ParseHoneycombTrace(rawStack, buildUUID, appExecutable)
+ }
+ if len(trace.Frames) == 0 {
+ return
+ }
+
+ attrs.PutStr(p.cfg.SymbolicatorParsingMethodAttributeKey, parsingMethodParsed)
+ if p.cfg.PreserveStackTrace {
+ attrs.PutStr(p.cfg.OriginalStackTraceAttributeKey, rawStack)
+ }
+
+ arch := trace.Arch
+ if arch == "" {
+ arch = p.cfg.IOSDefaultArch
+ }
+ if arch == "" {
+ arch = "arm64"
+ }
+
+ dataByUUID := map[string][]byte{}
+ var dones []func()
+ defer func() {
+ for _, d := range dones {
+ d()
+ }
+ }()
+ var resolveErr error
+ resolved := false
+ resolver := func(debugID string) []byte {
+ if d, ok := dataByUUID[debugID]; ok {
+ return d
+ }
+ key := flatCacheKey(p.store.iosSymbolsKey(debugID))
+ if p.cache.IsNegative(key) {
+ dataByUUID[debugID] = nil
+ if resolveErr == nil {
+ resolveErr = fmt.Errorf("failed to find ios symbols for %s", debugID)
+ }
+ return nil
+ }
+ data, done, err := p.cache.Get(ctx, key, func(ctx context.Context) ([]byte, error) {
+ fetchCtx, cancel := context.WithTimeout(ctx, p.cfg.Timeout)
+ defer cancel()
+ dsym, err := p.store.getIOSDsym(fetchCtx, debugID)
+ if err != nil {
+ return nil, err
+ }
+ return ios.BuildFlat(dsym, debugID, arch)
+ })
+ if err != nil {
+ dataByUUID[debugID] = nil
+ if resolveErr == nil {
+ resolveErr = err
+ }
+ return nil
+ }
+ dones = append(dones, done)
+ dataByUUID[debugID] = data
+ resolved = true
+ return data
+ }
+
+ attrs.PutStr(p.cfg.StackTraceAttributeKey, p.renderIOSTrace(attrs, trace, resolver))
+ if resolved {
+ attrs.PutBool(p.cfg.SymbolicatorFailureAttributeKey, false)
+ } else {
+ if resolveErr == nil {
+ resolveErr = errNoIOSSymbols
+ }
+ attrs.PutBool(p.cfg.SymbolicatorFailureAttributeKey, true)
+ attrs.PutStr(p.cfg.SymbolicatorErrorAttributeKey, resolveErr.Error())
+ }
+ p.putProcessorMeta(attrs)
+}
+
+func (p *symbolicatorProcessor) renderIOSTrace(attrs pcommon.Map, trace ios.StackTrace, resolver func(string) []byte) string {
+ preamble := ""
+ if excType := strAttr(attrs, p.cfg.ExceptionTypeAttributeKey); excType != "" {
+ if excMessage := strAttr(attrs, p.cfg.ExceptionMessageAttributeKey); excMessage != "" {
+ preamble = excType + ": " + excMessage
+ }
+ }
+ return ios.RenderResolved(trace, preamble, func(uuid string, off uint64) []ios.SymFrame {
+ data := resolver(uuid)
+ if data == nil {
+ return nil
+ }
+ return ios.LookupFlat(data, off)
+ })
+}
+
func (p *symbolicatorProcessor) languageAllowed(attrs, resource pcommon.Map) bool {
if len(p.cfg.AllowedLanguages) == 0 {
return true
diff --git a/benchmarks/processor/README.md b/benchmarks/processor/README.md
index 0ca8d786..cf7d7d8f 100644
--- a/benchmarks/processor/README.md
+++ b/benchmarks/processor/README.md
@@ -1,8 +1,9 @@
# benchmarks/processor
-Head-to-head benchmark of the Traceway source map symbolicator processor (oxc build)
-against Honeycomb's reference sourcemapprocessor, measuring sustained symbolication
-throughput and resident memory while ramping load to the breaking point.
+Head-to-head benchmark of the Traceway symbolicator processor against Honeycomb's
+reference processors (the `sourcemapprocessor` for JS and the `dsymprocessor` for
+iOS), measuring sustained symbolication throughput and resident memory while
+ramping load to the breaking point.
## Topology
@@ -36,6 +37,9 @@ stacktraces/sec; the drain's symbolicated percentage is the correctness check.
| `traceway-goja-disk` | otelcol-bench-traceway | goja | mmap'd `.tw` disk tier |
| `traceway-dart-mem` | otelcol-bench-traceway | DWARF flatten | in-memory `.tw` only |
| `traceway-dart-disk` | otelcol-bench-traceway | DWARF flatten | mmap'd `.tw` disk tier |
+| `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 |
One traceway binary (built with `-tags oxc`) serves all variants; language
(JS source maps vs. Dart symbols), parser, and cache mode are runtime config.
@@ -47,14 +51,33 @@ JS-only.
## Language
`benchmark-processor` takes a `language` input: `js` (the 5 JS impls incl.
-Honeycomb), `dart` (the two `traceway-dart-*` impls), or `both`. Locally, just
-list the impls in `IMPLS`. The Dart corpus replicates a committed seed
+Honeycomb), `dart` (the two `traceway-dart-*` impls), `ios` (the two
+`traceway-ios-*` 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
churn/oom scenarios exercise the cache the same way the JS corpus does. The
drain's symbolicated check uses Dart markers (`crash.dart` resolved vs.
`_kDart…SnapshotInstructions` unresolved) selected automatically per impl.
+The traceway iOS impls work the same way: a committed dSYM seed
+(`seeds/ios/app.dsym`) hardlinked under N synthetic build UUIDs as `<uuid>.dsym`
+(one inode for N builds), with the trace's per-frame UUID substituted per build.
+The traceway processor auto-routes the non-symbolic iOS trace, reads the dSYM by
+UUID, and flattens its DWARF to a `.tw` on a cache miss (the dSYM analog of the
+Dart `.symbols` flatten).
+
+`honeycomb-ios` runs the same seed against Honeycomb's `dsymprocessor`. Two things
+differ from the traceway iOS path. Honeycomb is logs-only, so loadgen sends OTLP
+logs (not traces). And Honeycomb keys its symcache by the dSYM's embedded
+`LC_UUID`, so the corpus cannot hardlink one inode: corpusgen patches the
+`LC_UUID` per build and writes a real `<UUID>.dSYM/Contents/Resources/DWARF/<binary>`
+bundle. The trace is the Apple-style frame format Honeycomb parses
+(`<idx> <bin> 0x<addr> <UUID> + <offset>`). Traceway's own OTel processor accepts
+that exact Honeycomb frame format too (`ios.ParseHoneycombTrace`, routed for both
+traces and logs), so the same input shape resolves on both engines. Drain markers:
+`sample.c` resolved vs. `sample+0x` unresolved.
+
## Scenarios
- `hot`: one bundle, always cache-warm. Pure resolve throughput ramp.
@@ -73,6 +96,15 @@ drain's symbolicated check uses Dart markers (`crash.dart` resolved vs.
The oom run defaults to a small SUT (ccx13, 8 GB) so the breaking point
arrives quickly.
+For `ios` and `honeycomb-ios` there is no padding lever (a dSYM is fixed-size and
+the engine holds a parsed symbol cache, not the raw artifact), so `oom` is instead
+a bounded-cache eviction soak: `OOM_ENTRIES` distinct build UUIDs cycle through a
+small `OOM_CACHE` (128 by default, well under the corpus) under sustained load on
+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.
+
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
sourcemap stays valid because frames sit on line 1 before the padding.
@@ -91,6 +123,7 @@ timeline, not a single number.
./run-local.sh
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
```
Needs go, cargo, node, jq. Builds both collectors (the Traceway one with
@@ -119,7 +152,8 @@ but the collector.
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.
+are uploaded as `results-<impl>` artifacts. `ios` runs `honeycomb-ios` alongside
+the two `traceway-ios` impls.
## Knobs
@@ -128,6 +162,7 @@ are uploaded as `results-<impl>` artifacts.
| `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 |
| `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-ios.yaml b/benchmarks/processor/config-honeycomb-ios.yaml
new file mode 100644
index 00000000..2469d9e2
--- /dev/null
+++ b/benchmarks/processor/config-honeycomb-ios.yaml
@@ -0,0 +1,33 @@
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+
+processors:
+ dsym_symbolicator:
+ dsym_store: file_store
+ local_dsyms:
+ path: ${env:STORE_PATH}
+ dsym_cache_size: ${env:CACHE_SIZE:-128}
+ preserve_stack_trace: false
+ allowed_languages: [swift, ios]
+
+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: [dsym_symbolicator]
+ exporters: [otlphttp/drain]
diff --git a/benchmarks/processor/corpusgen/main.go b/benchmarks/processor/corpusgen/main.go
index 8e928745..0634ddf4 100644
--- a/benchmarks/processor/corpusgen/main.go
+++ b/benchmarks/processor/corpusgen/main.go
@@ -1,12 +1,16 @@
package main
import (
+ "bytes"
+ "debug/macho"
+ "encoding/hex"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"regexp"
+ "strconv"
"strings"
)
@@ -21,8 +25,9 @@ type dartBuild struct {
}
type dartCorpus struct {
- Language string `json:"language"`
- Builds []dartBuild `json:"builds"`
+ Language string `json:"language"`
+ BinaryName string `json:"binaryName,omitempty"`
+ Builds []dartBuild `json:"builds"`
}
const vlqChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
@@ -166,7 +171,9 @@ func main() {
bundle := flag.String("bundle", "../../testing/symbolication/node-app/dist/app.mjs", "")
mapFile := flag.String("map", "../../testing/symbolication/node-app/dist/app.mjs.map", "")
symbols := flag.String("symbols", "seeds/dart/app.debug.elf", "dart: seed .symbols/.elf")
- traceFile := flag.String("trace", "seeds/dart/trace.txt", "dart: seed non-symbolic trace")
+ 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")
entries := flag.Int("entries", 1, "")
padKB := flag.Int("pad-kb", 256, "")
mapPadKB := flag.Int("map-pad-kb", 0, "")
@@ -181,6 +188,14 @@ func main() {
generateDart(*out, *symbols, *traceFile, *entries)
return
}
+ if *language == "ios" {
+ generateIOS(*out, *dsym, *traceFile, *entries)
+ return
+ }
+ if *language == "honeycomb-ios" {
+ generateHoneycombIOS(*out, *dsym, *traceFile, *binary, *entries)
+ return
+ }
bundleBytes, err := os.ReadFile(*bundle)
if err != nil {
@@ -269,3 +284,156 @@ func substituteBuildID(trace, buildID string) string {
}
return "build_id: '" + buildID + "'\n" + trace
}
+
+var iosFrameUUIDRe = regexp.MustCompile(`(#\d+\s+)[0-9a-fA-F]{32}(\s+0x)`)
+
+func generateIOS(out, dsymPath, tracePath string, entries int) {
+ dsym, err := os.ReadFile(dsymPath)
+ if err != nil {
+ panic(fmt.Errorf("reading ios seed dSYM %q: %w", dsymPath, err))
+ }
+ template, err := os.ReadFile(tracePath)
+ if err != nil {
+ panic(fmt.Errorf("reading ios seed trace %q: %w", tracePath, err))
+ }
+ absSeed, err := filepath.Abs(dsymPath)
+ if err != nil {
+ panic(err)
+ }
+ arch := "arm64"
+ if m := archRe.FindStringSubmatch(string(template)); m != nil {
+ arch = m[1]
+ }
+
+ c := dartCorpus{Language: "ios"}
+ for n := 0; n < entries; n++ {
+ uuid := fmt.Sprintf("%032x", n)
+ dest := filepath.Join(out, uuid+".dsym")
+ _ = os.Remove(dest)
+ if err := os.Link(absSeed, dest); err != nil {
+ if werr := os.WriteFile(dest, dsym, 0o644); werr != nil {
+ panic(werr)
+ }
+ }
+ c.Builds = append(c.Builds, dartBuild{BuildID: uuid, Trace: substituteIOSUUID(string(template), uuid)})
+ }
+ data, _ := json.MarshalIndent(c, "", " ")
+ if err := os.WriteFile(filepath.Join(out, "corpus.json"), data, 0o644); err != nil {
+ panic(err)
+ }
+ fmt.Printf("wrote %d ios builds (arch %s, seed %s) to %s\n", entries, arch, dsymPath, out)
+}
+
+func substituteIOSUUID(trace, uuid string) string {
+ return iosFrameUUIDRe.ReplaceAllString(trace, "${1}"+uuid+"${2}")
+}
+
+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 {
+ h := strings.ToUpper(hex32)
+ if len(h) != 32 {
+ return h
+ }
+ return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32]
+}
+
+func seedMachoUUID(data []byte) []byte {
+ f, err := macho.NewFile(bytes.NewReader(data))
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+ for _, l := range f.Loads {
+ lb, ok := l.(macho.LoadBytes)
+ if !ok {
+ continue
+ }
+ raw := lb.Raw()
+ if len(raw) >= 24 && f.ByteOrder.Uint32(raw[0:4]) == 0x1b {
+ return append([]byte(nil), raw[8:24]...)
+ }
+ }
+ return nil
+}
+
+func patchMachoUUID(seed, oldUUID, newUUID []byte) []byte {
+ out := make([]byte, len(seed))
+ copy(out, seed)
+ if i := bytes.Index(out, oldUUID); i >= 0 {
+ copy(out[i:i+16], newUUID)
+ }
+ return out
+}
+
+type iosSeedFrame struct {
+ idx int
+ uuid32 string
+ image string
+ offset uint64
+}
+
+func generateHoneycombIOS(out, dsymPath, tracePath, binaryName string, entries int) {
+ seed, err := os.ReadFile(dsymPath)
+ if err != nil {
+ panic(fmt.Errorf("reading ios seed dSYM %q: %w", dsymPath, err))
+ }
+ template, err := os.ReadFile(tracePath)
+ if err != nil {
+ panic(fmt.Errorf("reading ios seed trace %q: %w", tracePath, err))
+ }
+ oldUUID := seedMachoUUID(seed)
+ if oldUUID == nil {
+ panic(fmt.Errorf("seed dSYM %q has no LC_UUID", dsymPath))
+ }
+
+ arch := "arm64"
+ if m := archRe.FindStringSubmatch(string(template)); m != nil {
+ arch = m[1]
+ }
+
+ var frames []iosSeedFrame
+ for _, line := range strings.Split(string(template), "\n") {
+ m := twFrameRe.FindStringSubmatch(line)
+ if m == nil {
+ continue
+ }
+ idx, _ := strconv.Atoi(m[1])
+ off, _ := strconv.ParseUint(m[3], 16, 64)
+ frames = append(frames, iosSeedFrame{idx: idx, uuid32: strings.ToLower(m[2]), image: m[4], offset: off})
+ }
+ if len(frames) == 0 {
+ panic(fmt.Errorf("ios seed trace %q has no frames", tracePath))
+ }
+
+ c := dartCorpus{Language: "honeycomb-ios", BinaryName: binaryName}
+ for n := 0; n < entries; n++ {
+ buildHex := fmt.Sprintf("%032x", n)
+ buildUUID := hyphenateUUID(buildHex)
+ newUUID, _ := hex.DecodeString(buildHex)
+
+ dwarfDir := filepath.Join(out, buildUUID+".dSYM", "Contents", "Resources", "DWARF")
+ if err := os.MkdirAll(dwarfDir, 0o755); err != nil {
+ panic(err)
+ }
+ if err := os.WriteFile(filepath.Join(dwarfDir, binaryName), patchMachoUUID(seed, oldUUID, newUUID), 0o644); err != nil {
+ panic(err)
+ }
+
+ var b strings.Builder
+ fmt.Fprintf(&b, "os: ios arch: %s\n", arch)
+ for _, f := range frames {
+ uuid := buildUUID
+ if f.uuid32 != frames[0].uuid32 {
+ uuid = hyphenateUUID(f.uuid32)
+ }
+ fmt.Fprintf(&b, "%d %s 0x%016x %s + %d\n", f.idx, f.image, 0x100000000+f.offset, uuid, f.offset)
+ }
+ c.Builds = append(c.Builds, dartBuild{BuildID: buildUUID, Trace: b.String()})
+ }
+ data, _ := json.MarshalIndent(c, "", " ")
+ if err := os.WriteFile(filepath.Join(out, "corpus.json"), data, 0o644); err != nil {
+ panic(err)
+ }
+ fmt.Printf("wrote %d honeycomb-ios builds (arch %s, binary %s, seed %s) to %s\n", entries, arch, binaryName, dsymPath, out)
+}
diff --git a/benchmarks/processor/loadgen/main.go b/benchmarks/processor/loadgen/main.go
index b2f666de..21fc3255 100644
--- a/benchmarks/processor/loadgen/main.go
+++ b/benchmarks/processor/loadgen/main.go
@@ -17,6 +17,8 @@ import (
"time"
"go.opentelemetry.io/collector/pdata/pcommon"
+ "go.opentelemetry.io/collector/pdata/plog"
+ "go.opentelemetry.io/collector/pdata/plog/plogotlp"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
)
@@ -41,6 +43,33 @@ func buildBodyDart(trace string, spans int) []byte {
return buildBody("dart", "DartError", "bench", trace, spans)
}
+func buildBodyIOS(trace string, spans int) []byte {
+ return buildBody("swift", "IOSError", "bench", trace, spans)
+}
+
+func buildBodyHoneycombIOSLogs(trace, binaryName, buildUUID 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", "swift")
+ res.PutStr("app.bundle.executable", binaryName)
+ res.PutStr("app.debug.build_uuid", buildUUID)
+ sl := rl.ScopeLogs().AppendEmpty()
+ for i := 0; i < records; i++ {
+ lr := sl.LogRecords().AppendEmpty()
+ lr.Attributes().PutStr("exception.type", "IOSError")
+ 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()
@@ -98,9 +127,10 @@ func main() {
panic(err)
}
var c struct {
- Language string `json:"language"`
- Urls []string `json:"urls"`
- Builds []struct {
+ Language string `json:"language"`
+ BinaryName string `json:"binaryName"`
+ Urls []string `json:"urls"`
+ Builds []struct {
BuildID string `json:"buildId"`
Trace string `json:"trace"`
} `json:"builds"`
@@ -109,12 +139,23 @@ func main() {
panic(err)
}
var bodies [][]byte
- if c.Language == "dart" {
+ switch c.Language {
+ case "dart":
bodies = make([][]byte, len(c.Builds))
for i, b := range c.Builds {
bodies[i] = buildBodyDart(b.Trace, *spansPerReq)
}
- } else {
+ case "ios":
+ bodies = make([][]byte, len(c.Builds))
+ for i, b := range c.Builds {
+ bodies[i] = buildBodyIOS(b.Trace, *spansPerReq)
+ }
+ case "honeycomb-ios":
+ bodies = make([][]byte, len(c.Builds))
+ for i, b := range c.Builds {
+ bodies[i] = buildBodyHoneycombIOSLogs(b.Trace, c.BinaryName, b.BuildID, *spansPerReq)
+ }
+ default:
bodies = make([][]byte, len(c.Urls))
for i, u := range c.Urls {
bodies[i] = buildBodyJS(u, *spansPerReq)
diff --git a/benchmarks/processor/manifest-honeycomb.yaml b/benchmarks/processor/manifest-honeycomb.yaml
index 6437f7ad..1f7c0862 100644
--- a/benchmarks/processor/manifest-honeycomb.yaml
+++ b/benchmarks/processor/manifest-honeycomb.yaml
@@ -10,6 +10,7 @@ receivers:
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
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 9f44a25a..1614a718 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 <honeycomb|traceway-oxc-mem|traceway-oxc-disk|traceway-goja-mem|traceway-goja-disk>}"
+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)}"
SCENARIOS="${SCENARIOS:-hot churn oom}"
CHURN_ENTRIES="${CHURN_ENTRIES:-512}"
PAD_KB="${PAD_KB:-256}"
@@ -26,6 +26,7 @@ RUN_ID="${GITHUB_RUN_ID:-local}-$IMPL"
command -v hcloud >/dev/null || { echo "hcloud CLI required" >&2; exit 1; }
[ -d artifacts ] || { echo "artifacts/ missing, build first (see workflow or run-local.sh build_all)" >&2; exit 1; }
+SIGNAL=traces
case "$IMPL" in
honeycomb) COL_BIN=otelcol-bench-honeycomb; COL_CFG=config-honeycomb.yaml; PARSER=goja; DISK=; LANG=js ;;
traceway-oxc-mem) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=oxc; DISK=; LANG=js ;;
@@ -34,20 +35,25 @@ case "$IMPL" in
traceway-goja-disk) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=1; LANG=js ;;
traceway-dart-mem) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=; LANG=dart ;;
traceway-dart-disk) COL_BIN=otelcol-bench-traceway; COL_CFG=config-traceway.yaml; PARSER=goja; DISK=1; LANG=dart ;;
+ 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 ;;
*) echo "unknown impl $IMPL" >&2; exit 1 ;;
esac
-if [ "$LANG" = dart ]; then
- OK_MARKER=crash.dart; FAIL_MARKER=_kDartIsolateSnapshotInstructions
-else
- OK_MARKER=../src/inventory.js; FAIL_MARKER=.mjs:1:
-fi
+case "$LANG" in
+ dart) OK_MARKER=crash.dart; FAIL_MARKER=_kDartIsolateSnapshotInstructions ;;
+ ios|honeycomb-ios) OK_MARKER=sample.c; FAIL_MARKER=sample+0x ;;
+ *) 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 "$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" ;;
- oom) echo "$OOM_ENTRIES $OOM_PAD_KB $OOM_MAP_PAD_KB:$OOM_MAPPINGS_PAD_KB $OOM_ENTRIES $OOM_CONNECTIONS $OOM_DURATION $OOM_SUT_TYPE" ;;
+ oom) echo "$OOM_ENTRIES $OOM_PAD_KB $OOM_MAP_PAD_KB:$OOM_MAPPINGS_PAD_KB $oom_cache $OOM_CONNECTIONS $OOM_DURATION $OOM_SUT_TYPE" ;;
esac
}
@@ -98,11 +104,12 @@ for scenario in $SCENARIOS; do
outdir="$RESULTS/$tag"
mkdir -p "$outdir"
- if [ "$LANG" = dart ]; then
- corpusgen_cmd="./corpusgen --language dart --symbols seeds/dart/app.debug.elf --trace seeds/dart/trace.txt --entries $entries --out corpus-$scenario"
- else
- 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"
- fi
+ case "$LANG" in
+ 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" ;;
+ *) 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
$SSH "root@$ip" "cd /opt/bench && [ -f corpus-$scenario/corpus.json ] || $corpusgen_cmd"
done
@@ -114,14 +121,14 @@ for scenario in $SCENARIOS; do
T0=$($SSH "root@$SUT_IP" "date +%s")
$SSH "root@$SUT_IP" "cd /opt/bench || exit 1; nohup bash rss-sampler.sh \$(cat collector.pid) rss.csv > /dev/null 2>&1 &"
- $SSH "root@$LDG_IP" "cd /opt/bench && ./loadgen --target http://$SUT_IP:4318/v1/traces --corpus corpus-$scenario/corpus.json --connections $conns --step-duration $dur --spans-per-request $SPANS_PER_REQUEST --out loadgen.json" || true
+ $SSH "root@$LDG_IP" "rm -f /opt/bench/loadgen-$scenario.json; cd /opt/bench && ./loadgen --target http://$SUT_IP:4318/v1/$SIGNAL --corpus corpus-$scenario/corpus.json --connections $conns --step-duration $dur --spans-per-request $SPANS_PER_REQUEST --out loadgen-$scenario.json" || true
if ! $SSH "root@$SUT_IP" "kill -0 \$(cat /opt/bench/collector.pid) 2>/dev/null"; then
TDEAD=$($SSH "root@$SUT_IP" "tail -1 /opt/bench/rss.csv | cut -d, -f1")
echo "$(( TDEAD - T0 ))" > "$outdir/died"
fi
$SSH "root@$LDG_IP" "curl -sf http://127.0.0.1:9319/stats" > "$outdir/drain.json" || echo '{}' > "$outdir/drain.json"
- $SCP "root@$LDG_IP:/opt/bench/loadgen.json" "$outdir/loadgen.json"
+ $SCP "root@$LDG_IP:/opt/bench/loadgen-$scenario.json" "$outdir/loadgen.json" || true
$SSH "root@$SUT_IP" "kill \$(cat /opt/bench/collector.pid) 2>/dev/null; sleep 2" || true
$SCP "root@$SUT_IP:/opt/bench/rss.csv" "$outdir/rss.csv" || true
$SCP "root@$SUT_IP:/opt/bench/collector.log" "$outdir/collector.log" || true
diff --git a/benchmarks/processor/run-local.sh b/benchmarks/processor/run-local.sh
index d4b42183..3e4161bb 100755
--- a/benchmarks/processor/run-local.sh
+++ b/benchmarks/processor/run-local.sh
@@ -40,16 +40,18 @@ build_all() {
(cd loadgen && go mod tidy >/dev/null 2>&1; go build -o loadgen .)
(cd corpusgen && go build -o corpusgen .)
- if echo "$IMPLS" | grep -qE 'honeycomb|oxc|goja' && [ ! -f ../../testing/symbolication/node-app/dist/app.mjs ]; then
+ if echo "$IMPLS" | grep -qE 'oxc|goja|(^| )honeycomb( |$)' && [ ! -f ../../testing/symbolication/node-app/dist/app.mjs ]; then
(cd ../../testing/symbolication/node-app && npm install && npm run build)
fi
}
scenario_params() {
+ local oom_cache="$OOM_ENTRIES"
+ case "$2" in ios|honeycomb-ios) 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" ;;
- oom) echo "$OOM_ENTRIES $OOM_PAD_KB $OOM_MAP_PAD_KB:$OOM_MAPPINGS_PAD_KB $OOM_ENTRIES $OOM_CONNECTIONS $OOM_DURATION" ;;
+ oom) echo "$OOM_ENTRIES $OOM_PAD_KB $OOM_MAP_PAD_KB:$OOM_MAPPINGS_PAD_KB $oom_cache $OOM_CONNECTIONS $OOM_DURATION" ;;
esac
}
@@ -59,6 +61,10 @@ gen_corpus() {
if [ ! -f "$dir/corpus.json" ]; then
if [ "$lang" = dart ]; then
./corpusgen/corpusgen --language dart --entries "$entries" --out "$dir" >&2
+ elif [ "$lang" = ios ]; then
+ ./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
else
./corpusgen/corpusgen --entries "$entries" --pad-kb "$pad" --map-pad-kb "${mappad%%:*}" --mappings-pad-kb "${mappad##*:}" --out "$dir" >&2
fi
@@ -75,6 +81,9 @@ impl_env() {
traceway-goja-disk) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER=goja DISK=1 LANG=js" ;;
traceway-dart-mem) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER= DISK= LANG=dart" ;;
traceway-dart-disk) echo "BIN=./build-traceway/otelcol-bench-traceway CFG=config-traceway.yaml PARSER= DISK=1 LANG=dart" ;;
+ 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" ;;
*) echo "unknown impl $1" >&2; return 1 ;;
esac
}
@@ -82,15 +91,16 @@ impl_env() {
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" ;;
*) echo "OK_MARKER=../src/inventory.js FAIL_MARKER=.mjs:1:" ;;
esac
}
run_one() {
local impl="$1" scenario="$2"
- read -r entries pad mappad cachesize conns dur <<< "$(scenario_params "$scenario")"
- local BIN CFG PARSER DISK LANG
+ local BIN CFG PARSER DISK LANG SIGNAL=traces
eval "$(impl_env "$impl")"
+ read -r entries pad mappad cachesize conns dur <<< "$(scenario_params "$scenario" "$LANG")"
local store
store=$(gen_corpus "$LANG" "$scenario" "$entries" "$pad" "$mappad")
local OK_MARKER FAIL_MARKER
@@ -129,7 +139,7 @@ run_one() {
local t0
t0=$(date +%s)
- ./loadgen/loadgen --target http://127.0.0.1:4318/v1/traces --corpus "$store/corpus.json" \
+ ./loadgen/loadgen --target "http://127.0.0.1:4318/v1/$SIGNAL" --corpus "$store/corpus.json" \
--connections "$conns" --step-duration "$dur" \
--spans-per-request "$SPANS_PER_REQUEST" --out "$outdir/loadgen.json" || true
diff --git a/benchmarks/processor/seeds/ios/app.dsym b/benchmarks/processor/seeds/ios/app.dsym
new file mode 100644
index 00000000..779ce3b9
Binary files /dev/null and b/benchmarks/processor/seeds/ios/app.dsym differ
diff --git a/benchmarks/processor/seeds/ios/trace.txt b/benchmarks/processor/seeds/ios/trace.txt
new file mode 100644
index 00000000..36f3dc57
--- /dev/null
+++ b/benchmarks/processor/seeds/ios/trace.txt
@@ -0,0 +1,7 @@
+IOSError: bench
+*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
+os: ios arch: arm64
+#00 2dd71042118432be8f92dd4e3d3fe24a 0x460 sample
+#01 2dd71042118432be8f92dd4e3d3fe24a 0x47c sample
+#02 2dd71042118432be8f92dd4e3d3fe24a 0x478 sample
+#03 2dd71042118432be8f92dd4e3d3fe24a 0x494 sample
diff --git a/docs/components/FrameworkPicker.jsx b/docs/components/FrameworkPicker.jsx
index 854db554..a362e114 100644
--- a/docs/components/FrameworkPicker.jsx
+++ b/docs/components/FrameworkPicker.jsx
@@ -169,6 +169,14 @@ const FRAMEWORKS = [
icon: "/android.png",
href: "/client/android",
},
+ {
+ value: "ios",
+ label: "iOS",
+ description: "Native iOS (Swift) apps with automatic crash and exception capture via Swift Package Manager.",
+ icon: "/ios.png",
+ iconClassName: "framework-picker-icon--adaptive",
+ href: "/client/ios",
+ },
{
value: "react-native",
label: "React Native",
@@ -203,7 +211,7 @@ export default function FrameworkPicker() {
<img
src={fw.icon}
alt={fw.label}
- className="framework-picker-icon"
+ className={`framework-picker-icon${fw.iconClassName ? ` ${fw.iconClassName}` : ""}`}
/>
<span className="framework-picker-label">{fw.label}</span>
<span className="framework-picker-desc">{fw.description}</span>
diff --git a/docs/components/SdkContext.jsx b/docs/components/SdkContext.jsx
index da6ef43d..a0c3e2b4 100644
--- a/docs/components/SdkContext.jsx
+++ b/docs/components/SdkContext.jsx
@@ -25,6 +25,7 @@ export const SDK_OPTIONS = [
{ value: 'python-django', label: 'Django' },
{ value: 'flutter', label: 'Flutter' },
{ value: 'android', label: 'Android' },
+ { value: 'ios', label: 'iOS' },
{ value: 'react-native', label: 'React Native' },
]
@@ -56,6 +57,7 @@ const FOLDER_SDK = {
'django': 'python-django',
'flutter': 'flutter',
'android': 'android',
+ 'ios': 'ios',
}
// Shared reference folders — the SDK cannot be derived from the path alone.
diff --git a/docs/pages/client/_meta.json b/docs/pages/client/_meta.json
index dff8ce17..90d63527 100644
--- a/docs/pages/client/_meta.json
+++ b/docs/pages/client/_meta.json
@@ -28,5 +28,6 @@
"django": "Django",
"flutter": "Flutter",
"android": "Android",
+ "ios": "iOS",
"react-native": "React Native"
}
diff --git a/docs/pages/client/ios/_meta.json b/docs/pages/client/ios/_meta.json
new file mode 100644
index 00000000..8393d864
--- /dev/null
+++ b/docs/pages/client/ios/_meta.json
@@ -0,0 +1,3 @@
+{
+ "index": "Quick Start"
+}
diff --git a/docs/pages/client/ios/index.mdx b/docs/pages/client/ios/index.mdx
new file mode 100644
index 00000000..f139b62f
--- /dev/null
+++ b/docs/pages/client/ios/index.mdx
@@ -0,0 +1,167 @@
+# iOS Quick Start
+
+Integrate Traceway into your native iOS application with the [`traceway-ios`](https://github.com/tracewayapp/traceway-ios) Swift package. Pure Swift, zero third-party dependencies. It captures errors and crashes only (no metrics, no transactions, no session replay) and speaks the same `/api/report` wire format as the other SDKs, so a single Traceway backend handles iOS alongside everything else.
+
+## Requirements
+
+- iOS 13.0+
+- Swift 5.9+ / Xcode 15+
+
+## Installation
+
+Install with Swift Package Manager. In Xcode, choose **File > Add Package Dependencies** and enter the repository URL:
+
+```
+https://github.com/tracewayapp/traceway-ios.git
+```
+
+Or add it directly to your `Package.swift`:
+
+```swift
+dependencies: [
+ .package(url: "https://github.com/tracewayapp/traceway-ios.git", from: "0.1.0"),
+],
+```
+
+Then add `"Traceway"` to your target's dependencies:
+
+```swift
+.target(
+ name: "MyApp",
+ dependencies: ["Traceway"]
+),
+```
+
+## Setup
+
+Call `Traceway.start(connectionString:options:)` as early as possible so it is installed before any code that might crash. In SwiftUI, do it from your `App.init`:
+
+```swift
+import SwiftUI
+import Traceway
+
+@main
+struct MyApp: App {
+ init() {
+ Traceway.start(
+ connectionString: "your-token@https://cloud.tracewayapp.com/api/report",
+ options: TracewayOptions(version: "1.0.0")
+ )
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ ContentView()
+ }
+ }
+}
+```
+
+In UIKit, do it from `application(_:didFinishLaunchingWithOptions:)`:
+
+```swift
+import UIKit
+import Traceway
+
+@main
+class AppDelegate: UIResponder, UIApplicationDelegate {
+ func application(
+ _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
+ ) -> Bool {
+ Traceway.start(
+ connectionString: "your-token@https://cloud.tracewayapp.com/api/report",
+ options: TracewayOptions(version: "1.0.0")
+ )
+ return true
+ }
+}
+```
+
+## What Gets Captured Automatically
+
+After `Traceway.start(...)` runs, the following sources are captured with no additional configuration:
+
+- **Uncaught NSExceptions**: ObjC / UIKit exceptions that escape to the top of the stack.
+- **Fatal signals**: Swift runtime traps such as force-unwrapping a `nil`, array out-of-bounds access, `fatalError()`, and integer overflow, surfacing as `SIGTRAP`, `SIGILL`, `SIGABRT`, or `SIGSEGV`.
+
+Hard crashes are persisted to disk and uploaded on the **next launch**, so a crash that takes the process down still reaches your dashboard.
+
+## Capture Errors Manually
+
+```swift
+import Traceway
+
+// Capture any Swift Error
+do {
+ try riskyOperation()
+} catch {
+ Traceway.capture(error)
+}
+
+// Capture an NSError
+Traceway.capture(error: nsError)
+
+// Capture a message
+Traceway.capture(message: "User completed onboarding")
+
+// Force send pending reports (seconds; nil waits indefinitely)
+Traceway.flush(timeout: 5)
+```
+
+## With Options
+
+`TracewayOptions` accepts the following parameters. Field names mirror the other SDKs so configuration can be ported directly.
+
+| Option | Default | Description |
+|--------|---------|-------------|
+| `sampleRate` | `1.0` | Fraction of exceptions to keep (0.0 to 1.0) |
+| `debug` | `false` | Log SDK activity via `NSLog` |
+| `version` | `""` | App version, sent as `appVersion` |
+| `debounceMs` | `1500` | Delay before batching and uploading |
+| `retryDelayMs` | `10000` | Delay before retrying a failed upload |
+| `maxPendingExceptions` | `5` | In-memory cap; oldest dropped when exceeded |
+| `persistToDisk` | `true` | Persist pending reports so they survive restarts |
+| `maxLocalFiles` | `5` | Max persisted report files |
+| `localFileMaxAgeHours` | `12` | Delete unsynced files older than this |
+
+```swift
+Traceway.start(
+ connectionString: "your-token@https://cloud.tracewayapp.com/api/report",
+ options: TracewayOptions(
+ sampleRate: 0.5,
+ debug: true,
+ version: "2.1.0",
+ debounceMs: 2000
+ )
+)
+```
+
+## Test Your Integration
+
+Add a button that triggers a crash to verify everything is wired up:
+
+```swift
+Button("Send Test Error") {
+ fatalError("Test error from Traceway integration")
+}
+```
+
+When the Xcode debugger is attached, lldb intercepts signals first, so a crash never reaches the SDK. Test crash capture by running **without** the debugger: launch the app from the home screen, trigger the crash, then relaunch and watch the report upload on the next launch. Caught errors sent through `Traceway.capture(...)` upload immediately and do not need this.
+
+## Release Symbolication (dSYM upload)
+
+A release build ships stripped, so crash traces arrive as bare image offsets with no function names or line numbers. Upload the build's `.dSYM` and Traceway symbolicates those traces server-side, turning each frame into `function (file:line:col)`. You upload the raw dSYM; there is no client-side parsing.
+
+The SDK ships an uploader script. Add an Xcode **Run Script** build phase that invokes it:
+
+```sh
+"$SRCROOT/path/to/Scripts/upload_symbols.sh"
+```
+
+The script no-ops on non-Release builds and when the token is unset, so it is safe to leave in place. Set two environment variables for the phase:
+
+- `TRACEWAY_UPLOAD_TOKEN`: your project's source map / symbol **upload token** from the dashboard, the same one used for JavaScript source maps. It is **not** the runtime token in your connection string.
+- `TRACEWAY_URL`: your Traceway base URL (or `/api/report` URL); the script derives the upload URL from it.
+
+See [iOS symbolication](/symbolicator/ios) for the full reference: the script flags, the raw HTTP upload contract for CI without Xcode, and how a non-symbolicated frame resolves into source.
diff --git a/docs/pages/symbolicator/_meta.json b/docs/pages/symbolicator/_meta.json
index cea4972b..f966c717 100644
--- a/docs/pages/symbolicator/_meta.json
+++ b/docs/pages/symbolicator/_meta.json
@@ -2,6 +2,7 @@
"index": "Architecture",
"javascript": "JavaScript",
"dart": "Dart",
+ "ios": "iOS",
"performance": "Performance",
"opentelemetry": "OpenTelemetry",
"library": "Library"
diff --git a/docs/pages/symbolicator/index.mdx b/docs/pages/symbolicator/index.mdx
index bc65d10b..0fcb5b06 100644
--- a/docs/pages/symbolicator/index.mdx
+++ b/docs/pages/symbolicator/index.mdx
@@ -14,7 +14,7 @@ Symbolication happens **once, at ingest**. A report arrives, each stack trace is
The trade-off is that stored traces are immutable snapshots of the symbolication quality at the moment they arrived. Uploading better debug info improves future events, not past ones.
-This is dispatched by the trace, not configured per project: a browser exception resolves against source maps, a Flutter exception against its symbols, and the engine picks the path from the SDK language and the shape of the trace. The collector processor and the library do the same work at a different point in the pipeline.
+This is dispatched by the trace, not configured per project: a browser exception resolves against source maps, a Flutter exception against its symbols, an iOS crash against its dSYM, and the engine picks the path from the SDK language and the shape of the trace. The collector processor and the library do the same work at a different point in the pipeline.
## The pipeline
@@ -39,7 +39,7 @@ The structure is the same regardless of where the debug info came from:
Because the ranges are sorted, a lookup is a single binary search. Because the layout is fixed and little-endian, opening a `.tw` validates its structure and then reads straight from the mapped pages, with no copying or decoding, and the OS page cache shares those pages across every process that maps the same file. Compiling the resolver (parsing the debug info, computing every range, interning every name) runs once at build time; opening the compiled result skips all of it.
-A `.tw` is a cache artifact, never the source of truth. It's versioned by a single integer with no migration path: bump the version and every existing file fails validation and is lazily rebuilt from its original debug info. Each language has its own `.tw` encoding tuned to its debug format; the per-language specifics are on the [JavaScript](/symbolicator/javascript) and [Dart](/symbolicator/dart) pages.
+A `.tw` is a cache artifact, never the source of truth. It's versioned by a single integer with no migration path: bump the version and every existing file fails validation and is lazily rebuilt from its original debug info. Each language has its own `.tw` encoding tuned to its debug format; the per-language specifics are on the [JavaScript](/symbolicator/javascript), [Dart](/symbolicator/dart), and [iOS](/symbolicator/ios) pages.
## Cache tiers
@@ -67,6 +67,7 @@ Raw artifacts are fetched on demand and never kept on local disk by the engine.
- **[JavaScript](/symbolicator/javascript)** — source maps and bundle scope analysis.
- **[Dart](/symbolicator/dart)** — stripped Flutter traces and DWARF.
+- **[iOS](/symbolicator/ios)** — stripped Swift/ObjC release crashes and dSYM/DWARF.
- **[Performance](/symbolicator/performance)** — memory vs disk cache, sizing, benchmarks, and the metrics to watch.
- **[OpenTelemetry](/symbolicator/opentelemetry)** — running the engine as a collector processor.
- **[Library](/symbolicator/library)** — calling the engine from your own Go code.
diff --git a/docs/pages/symbolicator/ios.mdx b/docs/pages/symbolicator/ios.mdx
new file mode 100644
index 00000000..a57e0d69
--- /dev/null
+++ b/docs/pages/symbolicator/ios.mdx
@@ -0,0 +1,119 @@
+# iOS
+
+For iOS, the debug info is the build's `.dSYM` (a Mach-O wrapper around DWARF). A stripped Swift or Objective-C release build keeps no function names or line tables in the shipped binary, so a crash reports against raw machine code. Each frame carries the image's Mach-O UUID, an offset into that image, and the image name:
+
+```
+Fatal error: Unexpectedly found nil while unwrapping an Optional value
+#00 8a5f0c2e1b7d4f93a6e0c8b1d2f3a4b5 0x00000000000a1340 MyApp
+#01 8a5f0c2e1b7d4f93a6e0c8b1d2f3a4b5 0x00000000000a2d10 MyApp
+```
+
+The offset is image-relative (the frame address minus the image's load address), so it is independent of where the dynamic linker slid the image at runtime. With the build's `.dSYM` uploaded, that resolves into named source frames, inline calls expanded:
+
+```
+#0 ProfileViewModel.load() (ProfileViewModel.swift:88:14)
+#1 ProfileView.body.getter (ProfileView.swift:142:20)
+#2 closure #1 in AppDelegate.application(_:didFinishLaunchingWithOptions:) (AppDelegate.swift:24:9)
+```
+
+Symbolication runs server-side from the `.dSYM` you upload; the client never parses anything. This page covers the iOS-specific mechanics in the order you meet them: how to upload the `.dSYM`, the upload API, how a non-symbolic trace is recognized, and how each frame resolves into source. For when symbolication runs, the cache, and the `.tw` format, see [Architecture](/symbolicator).
+
+## The `.dSYM` and why it ships separately
+
+A Release build strips names and line tables out of the binary to shrink the app and protect your source. Xcode writes that stripped debug information into a separate `.dSYM` bundle per build, which ships to you instead of inside the app. Inside the bundle, the Mach-O binary lives at `*.dSYM/Contents/Resources/DWARF/<ProductName>` and carries the DWARF debug info plus the `LC_UUID` load command that anchors it to the build.
+
+Mach-O builds carry no GNU build-id note, so the debug ID is the Mach-O UUID. A fat (universal) `.dSYM` holds one Mach-O slice per architecture you ship, each with its own UUID; the backend stores one entry per slice. Symbols are unique to each build, so upload on every release: a crash can only be symbolicated against the exact build it came from.
+
+## Uploading the `.dSYM` with the Xcode build phase
+
+The [`traceway-ios`](/client/ios) SDK ships an uploader at `Scripts/upload_symbols.sh` that finds the `.dSYM` binaries and posts them. The recommended setup is an Xcode **Run Script** build phase, so symbols upload automatically on every Release build:
+
+```bash
+"${SRCROOT}/path/to/Scripts/upload_symbols.sh"
+```
+
+The script no-ops on non-Release builds and when the token is unset, so it is safe to leave in place for Debug builds and local development. Configure it through the build environment:
+
+| Value | Flag | Env var | Default |
+|---|---|---|---|
+| Upload token | `--token` | `TRACEWAY_UPLOAD_TOKEN` | required |
+| Instance URL | `--url` | `TRACEWAY_URL` | Traceway Cloud |
+| dSYM directory | `--dsym-dir` | | Xcode's `DWARF_DSYM_FOLDER_PATH` |
+
+`TRACEWAY_UPLOAD_TOKEN` is your project's **upload token** from the dashboard, the same one used for JavaScript source maps. It is **not** the runtime token in your `Traceway.start()` connection string. `TRACEWAY_URL` is your Traceway base URL (or the `/api/report` URL); the script derives the upload endpoint from it.
+
+The script finds dSYM binaries at `*.dSYM/Contents/Resources/DWARF/*` and POSTs each one. Pass `--dry-run` to resolve the config and list what would be uploaded without sending.
+
+## Uploading from CI without Xcode
+
+The Run Script phase is convenient, but the uploader is a thin wrapper over a single endpoint. In CI, or anywhere Xcode is not driving the build, post each Mach-O binary directly:
+
+```
+POST /api/symbols/upload
+Authorization: Bearer <upload token>
+Content-Type: multipart/form-data
+```
+
+```bash
+curl -H "Authorization: Bearer $TRACEWAY_UPLOAD_TOKEN" \
+ -F "[email protected]/Contents/Resources/DWARF/MyApp" \
+ https://cloud.tracewayapp.com/api/symbols/upload
+```
+
+| Field | Required | Notes |
+|---|---|---|
+| `files` | yes | One or more Mach-O dSYM binaries. Repeatable to upload several at once. 200 MB per file. |
+
+Unlike the Dart upload, iOS needs no `arch` or `debug_id` form fields. The backend auto-detects the Mach-O, reads the `LC_UUID` straight from the binary, and for a fat dSYM stores one entry per architecture slice. The stored key is content-addressed by UUID:
+
+```
+iossymbols/{projectId}/{uuid}.dsym
+```
+
+Because the key is content-addressed, releases never collide and re-uploading the same build is idempotent. The response reports how many entries were stored:
+
+```json
+{ "uploaded": 2 }
+```
+
+This is the same `/api/symbols/upload` endpoint Dart uses. Dart uploads `.symbols` files; iOS just uploads the Mach-O dSYM, and the backend routes on the file's format.
+
+## How an iOS trace is recognized
+
+The engine recognizes an iOS trace by the SDK language, `swift` or `ios`, or by the frame shape when the language is absent. A non-symbolic iOS frame has this form:
+
+```
+#00 8a5f0c2e1b7d4f93a6e0c8b1d2f3a4b5 0x00000000000a1340 MyApp
+```
+
+The parser pulls three things from each frame:
+
+| Field | Source | Used for |
+|---|---|---|
+| debug ID | the 32-hex Mach-O UUID | matching the trace to an uploaded `.dSYM` |
+| offset | `0x<image-relative-offset>` | the address to resolve, relative to the image base |
+| image | the trailing image name | grouping frames by image |
+
+A trace that is already symbolic, or carries no recognizable iOS frames, passes through untouched.
+
+## How an offset resolves
+
+The matching key is the Mach-O UUID (the debug ID). Because the frame offset is image-relative rather than the absolute runtime address, no runtime slide needs to be sent: the original VM address is reconstructed from the dSYM itself.
+
+1. **Reconstruct the program counter.** The frame's offset is added to the dSYM's `__TEXT` segment VM address, `pc = dSYM __TEXT VMAddr + offset`. That VM address is what the lookup keys on, and it is the same regardless of where the image was slid at runtime.
+2. **Look up the PC.** A binary search over the resolver's range table finds the PC's entry and its span of frames. DWARF inline information means one machine address can stand for several source frames, so a single `#N` offset can expand into a chain of inlined calls, innermost first.
+3. **Render.** Resolved frames print as `#N functionName (file:line:col)`. A frame with no match (a PC outside any known range, or a dSYM that was not uploaded) keeps its raw form, so the trace is never worse than it arrived.
+
+If no dSYM is found for the build's UUID, every frame falls back to its raw offset form.
+
+## The flat format
+
+The `.dSYM` is decoded into Traceway's compact [`.tw`](/symbolicator#the-tw-resolver-format) flat artifact and cached, the same family of encoding used for the JavaScript source maps and the Dart `.symbols`. As with Dart, the iOS `.tw` maps **PC ranges to inline frame spans**: building it flattens the DWARF debug info into a range table sorted by PC, where each entry points at a run of frames (more than one when calls were inlined), plus a frame table of `(file, line, column, function)` records with names interned.
+
+The general properties (memory-mapped, zero-copy on little-endian hosts, a versioned cache artifact rebuilt from the original debug info) are the same as every `.tw`; see [Architecture](/symbolicator#the-tw-resolver-format).
+
+## Related pages
+
+- [iOS SDK](/client/ios): capturing errors and crashes from an iOS app
+- [Architecture](/symbolicator): when symbolication runs, the cache tiers, and the `.tw` format
+- [Performance](/symbolicator/performance): cache sizing and failure handling
diff --git a/docs/pages/symbolicator/opentelemetry.mdx b/docs/pages/symbolicator/opentelemetry.mdx
index 23fab15e..13c29f83 100644
--- a/docs/pages/symbolicator/opentelemetry.mdx
+++ b/docs/pages/symbolicator/opentelemetry.mdx
@@ -12,7 +12,7 @@ It's a drop-in replacement for [Honeycomb's `source_map_symbolicator` processor]
If you want to call the engine from your own Go code instead of a collector, see [Library](/symbolicator/library).
-The same processor also auto-routes non-symbolic Dart AOT traces to the [Dart](/symbolicator/dart) path. The walkthrough below covers the JavaScript source-map workflow.
+The same processor also auto-routes non-symbolic Dart AOT traces and stripped iOS/Swift traces to the [Dart](/symbolicator/dart) and [iOS](/symbolicator/ios) paths. The walkthrough below covers the JavaScript source-map workflow.
## Building a collector with the processor
@@ -212,6 +212,8 @@ Raw string parsing handles the stack formats browsers produce: V8 (including `as
| `build_uuid_attribute_key` | `app.debug.source_map_uuid` | Resource attribute used as a store key prefix |
| `language_attribute_key` | `telemetry.sdk.language` | Attribute checked against `allowed_languages` |
| `allowed_languages` | `[]` | When set, only records with a matching language are processed |
+| `dart_default_arch` | `arm64` | Default CPU architecture used when a Dart trace does not carry one |
+| `ios_default_arch` | `arm64` | Default CPU architecture used when an iOS trace does not carry one |
| `parser` | `goja` | Bundle parser for function names: `goja` or `oxc` (the latter only in `-tags oxc` builds) |
Every attribute key from the table above is remappable (`stack_trace_attribute_key`, `urls_attribute_key`, `symbolicator_failure_attribute_key`, and so on), with the same configuration keys and defaults as Honeycomb's processor.
diff --git a/docs/public/ios.png b/docs/public/ios.png
new file mode 100644
index 00000000..6a2a0acc
Binary files /dev/null and b/docs/public/ios.png differ
diff --git a/docs/styles/custom.css b/docs/styles/custom.css
index 223702e2..16fe486b 100644
--- a/docs/styles/custom.css
+++ b/docs/styles/custom.css
@@ -716,6 +716,14 @@ li:has(> .sdk-selector) > span:first-child {
object-fit: contain;
}
+.framework-picker-icon--adaptive {
+ filter: invert(1);
+}
+
+:is(html[class~="dark"]) .framework-picker-icon--adaptive {
+ filter: none;
+}
+
.framework-picker-label {
font-size: 16px;
font-weight: 600;
diff --git a/docs/theme.config.jsx b/docs/theme.config.jsx
index b701ef62..cfd481e8 100644
--- a/docs/theme.config.jsx
+++ b/docs/theme.config.jsx
@@ -28,6 +28,7 @@ const SDK_VISIBILITY = {
django: "python-django",
flutter: "flutter",
android: "android",
+ ios: "ios",
};
export default {
diff --git a/examples/devtesting-embedded/main.go b/examples/devtesting-embedded/main.go
index 84998479..54760d5a 100644
--- a/examples/devtesting-embedded/main.go
+++ b/examples/devtesting-embedded/main.go
@@ -44,6 +44,8 @@ const (
monitoringToken = "monitoring-dev-token"
flutterToken = "flutter-dev-token"
flutterUploadToken = "flutter-upload-token"
+ iosToken = "ios-dev-token"
+ iosUploadToken = "ios-upload-token"
backendServiceName = "backend-service"
workerServiceName = "worker-service"
@@ -137,6 +139,8 @@ func main() {
tracewaybackend.WithDefaultProject("Traceway Monitoring", "gin", monitoringToken),
tracewaybackend.WithDefaultProject("Flutter App", "flutter", flutterToken),
tracewaybackend.WithDefaultProjectSourceMapToken("Flutter App", flutterUploadToken),
+ tracewaybackend.WithDefaultProject("iOS App", "ios", iosToken),
+ tracewaybackend.WithDefaultProjectSourceMapToken("iOS App", iosUploadToken),
tracewaybackend.WithMonitoringURL(monitoringToken+"@http://localhost:8082/api/report"),
)
diff --git a/frontend/src/lib/components/framework-combobox.svelte b/frontend/src/lib/components/framework-combobox.svelte
index 79626a40..e0c0c01b 100644
--- a/frontend/src/lib/components/framework-combobox.svelte
+++ b/frontend/src/lib/components/framework-combobox.svelte
@@ -40,6 +40,7 @@
{ value: 'opentelemetry', label: 'OpenTelemetry', description: 'Vendor-neutral observability', group: 'Backend' },
{ value: 'flutter', label: 'Flutter', description: 'Mobile UI framework', group: 'Mobile' },
{ value: 'android', label: 'Android', description: 'Native Android (Kotlin/Java)', group: 'Mobile' },
+ { value: 'ios', label: 'iOS', description: 'Native iOS (Swift/Objective-C)', group: 'Mobile' },
] as const;
const selectedFrameworkLabel = $derived(getFrameworkLabel(value));
diff --git a/frontend/src/lib/components/framework-icon.svelte b/frontend/src/lib/components/framework-icon.svelte
index 933a09cb..0df68e2d 100644
--- a/frontend/src/lib/components/framework-icon.svelte
+++ b/frontend/src/lib/components/framework-icon.svelte
@@ -64,6 +64,10 @@
<img src="/flutter.png" alt="Flutter" class={className} style="object-fit: contain;" />
{:else if framework === 'android'}
<img src="/android.png" alt="Android" class={className} style="object-fit: contain;" />
+{:else if framework === 'ios'}
+ <svg class={className} viewBox="0 1 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
+ <path d="M11.05 8.5c-.02-1.5 1.23-2.22 1.28-2.26-.7-1.02-1.78-1.16-2.17-1.18-.92-.09-1.8.54-2.27.54-.47 0-1.19-.53-1.96-.51-1.01.01-1.94.59-2.46 1.49-1.05 1.82-.27 4.51.76 5.99.5.72 1.1 1.53 1.88 1.5.76-.03 1.04-.49 1.96-.49.91 0 1.17.49 1.97.47.81-.01 1.33-.73 1.83-1.46.58-.84.81-1.65.83-1.69-.02-.01-1.59-.61-1.61-2.43zM9.6 4.07c.42-.51.7-1.21.62-1.91-.6.02-1.33.4-1.76.91-.39.45-.73 1.17-.64 1.85.67.05 1.36-.34 1.78-.85z"/>
+ </svg>
{:else}
<img src="/custom.png" alt="Custom" class={className} />
{/if}
diff --git a/frontend/src/lib/components/issues/stack-trace-card.svelte b/frontend/src/lib/components/issues/stack-trace-card.svelte
index b4ae7aae..a8a8d11e 100644
--- a/frontend/src/lib/components/issues/stack-trace-card.svelte
+++ b/frontend/src/lib/components/issues/stack-trace-card.svelte
@@ -11,6 +11,7 @@
isMessage?: boolean;
isJavaScript?: boolean;
isFlutter?: boolean;
+ isIOS?: boolean;
firstSeen?: string;
lastSeen?: string;
totalCount?: number;
@@ -24,6 +25,7 @@
isMessage = false,
isJavaScript = false,
isFlutter = false,
+ isIOS = false,
firstSeen,
lastSeen,
totalCount,
@@ -34,8 +36,9 @@
const tz = $derived(timezone ?? getTimezone());
const showStats = $derived(firstSeen && lastSeen && totalCount !== undefined);
- const parsed = $derived(parseStackTrace(stackTrace));
- const usePretty = $derived((isJavaScript || isFlutter) && parsed.groups.length > 0);
+ const parsed = $derived(parseStackTrace(stackTrace, { ios: isIOS }));
+ const usePretty = $derived((isJavaScript || isFlutter || isIOS) && parsed.groups.length > 0);
+ const groupNoun = $derived(isIOS ? 'system' : 'library');
let expandedGroups = $state<Set<number>>(new Set());
@@ -148,7 +151,7 @@
<ChevronRight class="size-3.5 shrink-0" />
{/if}
<span class="tabular-nums"
- >{group.frames.length} library {group.frames.length === 1
+ >{group.frames.length} {groupNoun} {group.frames.length === 1
? 'frame'
: 'frames'}</span
>
diff --git a/frontend/src/lib/components/setup/source-map-upload-card.svelte b/frontend/src/lib/components/setup/source-map-upload-card.svelte
index df3e0c72..dfbaf9a5 100644
--- a/frontend/src/lib/components/setup/source-map-upload-card.svelte
+++ b/frontend/src/lib/components/setup/source-map-upload-card.svelte
@@ -14,6 +14,7 @@
let projectWithToken = $derived(projectsState.currentProject);
const isFlutter = $derived(projectWithToken?.framework === 'flutter');
+ const isIOS = $derived(projectWithToken?.framework === 'ios');
const isReadonly = $derived(
authState.getRoleForOrganization(projectsState.currentProject?.organizationId ?? 0) ===
@@ -26,9 +27,9 @@
<CardHeader>
<CardTitle class="flex items-center gap-2">
<KeyRound class="h-5 w-5" />
- {isFlutter ? 'Symbol Upload' : 'Source Map Upload'}
+ {isFlutter || isIOS ? 'Symbol Upload' : 'Source Map Upload'}
</CardTitle>
- {#if !isFlutter}
+ {#if !isFlutter && !isIOS}
<CardDescription>
Upload source maps to see original file names and line numbers in stack traces from
minified code.
diff --git a/frontend/src/lib/components/source-map-setup.svelte b/frontend/src/lib/components/source-map-setup.svelte
index 03fc5f39..469608e6 100644
--- a/frontend/src/lib/components/source-map-setup.svelte
+++ b/frontend/src/lib/components/source-map-setup.svelte
@@ -78,6 +78,8 @@ module.exports = {
let copiedCommand = $state(false);
let copiedFlutterBuild = $state(false);
let copiedFlutterUpload = $state(false);
+ let copiedIosBuild = $state(false);
+ let copiedIosUpload = $state(false);
const pluginInstallCommand = 'npm install -D @tracewayapp/bundler-plugin';
@@ -88,7 +90,8 @@ module.exports = {
);
const isFlutter = $derived(project?.framework === 'flutter');
- const artifactLabel = $derived(isFlutter ? 'debug symbols' : 'source maps');
+ const isIOS = $derived(project?.framework === 'ios');
+ const artifactLabel = $derived(isFlutter || isIOS ? 'debug symbols' : 'source maps');
const showBundlerSetup = $derived(project?.framework !== 'react-native');
@@ -112,6 +115,17 @@ module.exports = {
: ''
);
+ const iosBuildCommand =
+ 'xcodebuild -scheme MyApp -configuration Release \\\n -archivePath build/MyApp.xcarchive archive';
+
+ const iosUploadCommand = $derived(
+ project && sourceMapToken
+ ? `curl -X POST ${project.backendUrl}/api/symbols/upload \\
+ -H "Authorization: Bearer ${sourceMapToken}" \\
+ -F "files=@build/MyApp.xcarchive/dSYMs/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp"`
+ : ''
+ );
+
let regenerateDialogOpen = $state(false);
async function generateToken() {
@@ -170,6 +184,18 @@ module.exports = {
copiedFlutterUpload = true;
setTimeout(() => (copiedFlutterUpload = false), 2000);
}
+
+ async function copyIosBuild() {
+ await navigator.clipboard.writeText(iosBuildCommand);
+ copiedIosBuild = true;
+ setTimeout(() => (copiedIosBuild = false), 2000);
+ }
+
+ async function copyIosUpload() {
+ await navigator.clipboard.writeText(iosUploadCommand);
+ copiedIosUpload = true;
+ setTimeout(() => (copiedIosUpload = false), 2000);
+ }
</script>
{#if sourceMapToken}
@@ -254,6 +280,61 @@ module.exports = {
instead of the flag.
</p>
</div>
+ {:else if isIOS}
+ <div>
+ <p class="mb-2 text-sm font-medium">Step 1: Build an archive with dSYMs</p>
+ <div class="relative">
+ <div class="absolute top-2 right-2 z-10">
+ <Button variant="outline" size="sm" onclick={copyIosBuild}>
+ {#if copiedIosBuild}
+ <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={iosBuildCommand} />
+ </div>
+ </div>
+ <p class="mt-2 text-xs text-muted-foreground">
+ Release builds emit a .dSYM bundle per architecture under the archive's dSYMs directory.
+ Replace MyApp with your scheme name.
+ </p>
+ </div>
+ <div>
+ <p class="mb-2 text-sm font-medium">Step 2: Upload the dSYM after each release build</p>
+ <div class="relative">
+ <div class="absolute top-2 right-2 z-10">
+ <Button variant="outline" size="sm" onclick={copyIosUpload}>
+ {#if copiedIosUpload}
+ <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={iosUploadCommand} />
+ </div>
+ </div>
+ <p class="mt-2 text-xs text-muted-foreground">
+ Upload the Mach-O DWARF inside the .dSYM bundle. Symbols are keyed by build UUID, so
+ re-upload on each release.
+ </p>
+ </div>
{:else}
{#if showBundlerSetup}
<div>
@@ -369,6 +450,18 @@ module.exports = {
class="underline hover:text-foreground">Flutter docs</a
>
</p>
+ {:else if isIOS}
+ <p class="text-sm text-muted-foreground">
+ Release crashes report against stripped machine code. Generate a token, then upload your
+ <code class="rounded bg-muted px-1 py-0.5 font-mono text-xs">.dSYM</code> after each release
+ to resolve their stack traces.
+ <a
+ href="https://docs.tracewayapp.com/client/ios"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="underline hover:text-foreground">iOS 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 e663063e..9266e70d 100644
--- a/frontend/src/lib/state/projects.svelte.ts
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -1,9 +1,9 @@
import { api } from '$lib/api';
import { authState } from './auth.svelte';
-export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'react-native' | 'hono' | 'cloudflare' | 'opentelemetry' | 'symfony' | 'laravel' | 'django' | 'flutter' | 'android';
+export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'react-native' | 'hono' | 'cloudflare' | 'opentelemetry' | 'symfony' | 'laravel' | 'django' | 'flutter' | 'android' | 'ios';
-export const FRONTEND_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'jquery', 'react-native', 'flutter', 'android'];
+export const FRONTEND_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'jquery', 'react-native', 'flutter', 'android', 'ios'];
export const JS_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'nextjs', 'nestjs', 'express', 'remix', 'jquery', 'react-native'];
export const FRAMEWORK_LABELS: Record<Framework, string> = {
@@ -30,9 +30,10 @@ export const FRAMEWORK_LABELS: Record<Framework, string> = {
django: 'Django',
flutter: 'Flutter',
android: 'Android',
+ ios: 'iOS',
};
-export const MOBILE_FRAMEWORKS: Framework[] = ['flutter', 'android'];
+export const MOBILE_FRAMEWORKS: Framework[] = ['flutter', 'android', 'ios'];
export function getFrameworkLabel(fw: Framework): string {
return FRAMEWORK_LABELS[fw] ?? fw;
@@ -51,7 +52,7 @@ export function isJsFramework(fw: Framework): boolean {
}
export function supportsSymbolUpload(fw: Framework): boolean {
- return isJsFramework(fw) || fw === 'flutter';
+ return isJsFramework(fw) || fw === 'flutter' || fw === 'ios';
}
export const JS_LANGUAGES = ['webjs', 'nodejs', 'javascript', 'typescript'];
diff --git a/frontend/src/lib/utils/framework-code.ts b/frontend/src/lib/utils/framework-code.ts
index 842828c1..fe61b930 100644
--- a/frontend/src/lib/utils/framework-code.ts
+++ b/frontend/src/lib/utils/framework-code.ts
@@ -48,6 +48,8 @@ export function getInstallCommand(framework: Framework): string {
return 'flutter pub add traceway';
case 'android':
return 'implementation("com.tracewayapp:traceway:1.0.0")';
+ case 'ios':
+ return '.package(url: "https://github.com/tracewayapp/traceway-ios.git", from: "0.1.0")';
case 'custom':
default:
return base;
@@ -403,6 +405,26 @@ class MyApp : Application() {
}
}`;
+ case 'ios':
+ return `import SwiftUI
+import Traceway
+
+@main
+struct MyApp: App {
+ init() {
+ Traceway.start(
+ connectionString: "${connectionString}",
+ options: TracewayOptions(version: "1.0.0")
+ )
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ ContentView()
+ }
+ }
+}`;
+
case 'custom':
default:
return `package main
@@ -472,6 +494,10 @@ throw StateError('Test error from Traceway integration');`;
if (framework === 'android') {
return `// Trigger a test error
throw RuntimeException("Test error from Traceway integration")`;
+ }
+ if (framework === 'ios') {
+ return `// Trigger a test error
+fatalError("Test error from Traceway integration")`;
}
if (framework && isJsFramework(framework)) {
return `// Trigger a test error
@@ -507,6 +533,15 @@ try {
riskyOperation()
} catch (e: Throwable) {
Traceway.captureException(e)
+}`;
+ }
+ if (framework === 'ios') {
+ return `import Traceway
+
+do {
+ try riskyOperation()
+} catch {
+ Traceway.capture(error)
}`;
}
if (framework && isJsFramework(framework)) {
@@ -595,6 +630,7 @@ export function getFrameworkLabel(framework: Framework): string {
django: 'Django',
flutter: 'Flutter',
android: 'Android',
+ ios: 'iOS',
};
return labels[framework] || framework;
}
@@ -608,5 +644,6 @@ export function getCodeLanguage(framework: Framework): 'go' | 'javascript' | 'ba
if (framework === 'cloudflare') return 'javascript';
if (framework === 'flutter') return 'javascript'; // closest to Dart syntax highlighting
if (framework === 'android') return 'javascript'; // closest to Kotlin syntax highlighting
+ if (framework === 'ios') return 'javascript';
return isJsFramework(framework) ? 'javascript' : 'go';
}
diff --git a/frontend/src/lib/utils/stack-trace-parser.ts b/frontend/src/lib/utils/stack-trace-parser.ts
index fd2f63a3..3f00a960 100644
--- a/frontend/src/lib/utils/stack-trace-parser.ts
+++ b/frontend/src/lib/utils/stack-trace-parser.ts
@@ -30,7 +30,36 @@ function isLibraryLocation(location: string): boolean {
);
}
+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'
+]);
+
+function isIOSSystemImage(image: string): boolean {
+ const img = image.trim();
+ if (img === '' || img === '<unknown>') return true;
+ if (/^lib.*\.dylib$/.test(img)) return true;
+ if (/^libswift/.test(img)) return true;
+ return IOS_SYSTEM_IMAGES.has(img);
+}
+
+function isIOSSystemLocation(location: string): boolean {
+ const loc = location.trim();
+ return loc === '' || loc === '<compiler-generated>' || loc === '<unknown>';
+}
+
+function isIOSEntryFunction(fn: string): boolean {
+ const f = fn.trim();
+ return f === 'main';
+}
+
function extractPackageName(location: string): string {
+ const iosImageMatch = location.match(/^(.+?)\+0x[0-9a-fA-F]+$/);
+ if (iosImageMatch) return iosImageMatch[1];
+ if (location === '<compiler-generated>' || location === '<unknown>') return 'system';
+
const nodeModulesMatch = location.match(/node_modules\/([^/]+)/);
if (nodeModulesMatch) return nodeModulesMatch[1];
@@ -47,7 +76,7 @@ function extractPackageName(location: string): string {
return 'library';
}
-export function parseStackTrace(raw: string): ParsedStackTrace {
+export function parseStackTrace(raw: string, opts: { ios?: boolean } = {}): ParsedStackTrace {
const lines = raw.split('\n');
const frames: StackFrame[] = [];
let firstFrameIndex = -1;
@@ -56,8 +85,41 @@ export function parseStackTrace(raw: string): ParsedStackTrace {
const locationPattern = /^\s*.+:\d+:\d+$/;
const dartFramePattern = /^\s*#\d+\s+(.+?)\s+\((.+)\)\s*$/;
const dartUnresolvedPattern = /^\s*#\d+\s+(\S+SnapshotInstructions\+0x[0-9a-fA-F]+)\s*$/;
+ const iosResolvedPattern = /^\s*#\d+\s+(.+?)\s+\((.+)\)\s*$/;
+ const iosUnresolvedPattern = /^\s*#\d+\s+(.+?)\+0x[0-9a-fA-F]+\s*$/;
for (let i = 0; i < lines.length; i++) {
+ if (opts.ios) {
+ const iosResolved = lines[i].match(iosResolvedPattern);
+ if (iosResolved) {
+ const fn = iosResolved[1].trim();
+ const location = iosResolved[2].trim();
+ if (firstFrameIndex === -1) {
+ firstFrameIndex = i;
+ messageEndIndex = i;
+ }
+ frames.push({
+ functionName: fn,
+ location,
+ isLibrary: isIOSSystemLocation(location) || isIOSEntryFunction(fn)
+ });
+ continue;
+ }
+ const iosUnresolved = lines[i].match(iosUnresolvedPattern);
+ if (iosUnresolved) {
+ if (firstFrameIndex === -1) {
+ firstFrameIndex = i;
+ messageEndIndex = i;
+ }
+ frames.push({
+ functionName: null,
+ location: lines[i].trim().replace(/^#\d+\s+/, ''),
+ isLibrary: isIOSSystemImage(iosUnresolved[1].trim())
+ });
+ continue;
+ }
+ }
+
const dartMatch = lines[i].match(dartFramePattern);
if (dartMatch) {
const location = dartMatch[2].trim();
diff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.svelte
index 7da59bb4..d7769584 100644
--- a/frontend/src/routes/issues/[exceptionHash]/+page.svelte
+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte
@@ -41,6 +41,12 @@
: false) || isJsLanguage(latestOccurrence?.attributes?.['telemetry.sdk.language'])
);
const isFlutter = $derived(projectsState.currentProject?.framework === 'flutter');
+ const isIOS = $derived(
+ projectsState.currentProject?.framework === 'ios' ||
+ ['ios', 'swift'].includes(
+ (latestOccurrence?.attributes?.['telemetry.sdk.language'] ?? '').toLowerCase()
+ )
+ );
const hasMoreOccurrences = $derived(total > 10);
const firstLineOfStackTrace = $derived(latestOccurrence?.stackTrace.split('\n')[0] || 'Exception');
@@ -171,6 +177,7 @@
{isMessage}
{isJavaScript}
{isFlutter}
+ {isIOS}
firstSeen={group.firstSeen}
lastSeen={group.lastSeen}
totalCount={group.count}
diff --git a/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte
index 10a94c2c..c35d1a4c 100644
--- a/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte
+++ b/frontend/src/routes/issues/[exceptionHash]/[exceptionId]/+page.svelte
@@ -37,6 +37,12 @@
: false) || isJsLanguage(occurrence?.attributes?.['telemetry.sdk.language'])
);
const isFlutter = $derived(projectsState.currentProject?.framework === 'flutter');
+ const isIOS = $derived(
+ projectsState.currentProject?.framework === 'ios' ||
+ ['ios', 'swift'].includes(
+ (occurrence?.attributes?.['telemetry.sdk.language'] ?? '').toLowerCase()
+ )
+ );
const firstLineOfStackTrace = $derived(occurrence?.stackTrace.split('\n')[0] || 'Exception');
const hasMoreOccurrences = $derived(total > 10);
const subtitleText = $derived(occurrence ? `Event from ${formatDateTime(occurrence.recordedAt, { timezone })}` : 'Loading...');
@@ -177,6 +183,7 @@
{isMessage}
{isJavaScript}
{isFlutter}
+ {isIOS}
bind:showArchiveDialog={showArchiveDialog}
bind:archiving={archiving}
/>
diff --git a/skills/traceway-setup/SKILL.md b/skills/traceway-setup/SKILL.md
index 59a0fe4b..b68854ca 100644
--- a/skills/traceway-setup/SKILL.md
+++ b/skills/traceway-setup/SKILL.md
@@ -1,6 +1,6 @@
---
name: traceway-setup
-description: Connect a project to a Traceway instance so it reports endpoints, spans, errors, background tasks, AI traces, and metrics. Backends use OpenTelemetry over OTLP/HTTP, frontends and mobile apps use the Traceway SDKs, and host metrics use the Traceway OTel Agent. Use when the user wants to add Traceway (or OpenTelemetry tracing that exports to Traceway) to a backend, frontend, full-stack, or mobile project. Accepts a project token and instance URL, e.g. "/traceway-setup with token abc123".
+description: Connect a project to a Traceway instance so it reports endpoints, spans, errors, background tasks, AI traces, and metrics. Backends use OpenTelemetry over OTLP/HTTP, frontends and mobile apps (including native iOS/Swift) use the Traceway SDKs, and host metrics use the Traceway OTel Agent. Use when the user wants to add Traceway (or OpenTelemetry tracing that exports to Traceway) to a backend, frontend, full-stack, mobile, or iOS/Swift project. Accepts a project token and instance URL, e.g. "/traceway-setup with token abc123".
---
# Set Up Traceway in a Project
@@ -13,7 +13,7 @@ Connect an existing project to a Traceway instance so it reports endpoints, span
|---|---|---|
| **Instance URL** | `https://traceway.example.com` | The URL of the Traceway dashboard |
| **Project token** | `abc123...` | Traceway dashboard -> Connection page |
-| **Upload token** (optional; frontend source maps and obfuscated Flutter symbols) | `def456...` | Traceway dashboard -> Connection page -> Source Maps / Symbol Upload |
+| **Upload token** (optional; frontend source maps, obfuscated Flutter symbols, and iOS dSYMs) | `def456...` | Traceway dashboard -> Connection page -> Source Maps / Symbol Upload |
Instance URL and project token may be provided in the invocation (e.g. `/traceway-setup with token abc123 and url https://traceway.example.com`). If either is missing:
@@ -33,7 +33,7 @@ Pick the path by project type. This is not negotiable per framework; it is how T
| **Backend** (any language) | OpenTelemetry, exporting OTLP/HTTP to `<instance>/api/otel/v1/*`. Always, including Go. The native Traceway Go SDK is used only when the user explicitly asks for it. |
| **Frontend** (browser SPA) | Traceway `@tracewayapp/<framework>` SDK + bundler plugin + source map upload (see "Frontend and Mobile" below). |
| **Full-stack JS** (Next.js, SvelteKit, Remix) | BOTH: server side via OpenTelemetry AND browser side via the frontend SDK. |
-| **Mobile** (Flutter, React Native, Android) | The Traceway platform SDK only. Never OTel. |
+| **Mobile** (Flutter, React Native, Android, native Swift iOS) | The Traceway platform SDK. Never OTel. Sole exception: a non-Swift iOS/Apple app has no native SDK, so it uses an OTel library (e.g. Honeycomb) exporting to Traceway like a backend (see "Frontend and Mobile"). |
Two hard rules apply to every backend integration:
@@ -58,7 +58,7 @@ For the exact classification rules, endpoint naming, metric conversion, and all
Before changing anything, build a picture of what needs instrumenting:
-1. **Frameworks and languages**: detect them by reading `package.json` (Node.js), `go.mod` (Go), `composer.json` (PHP), `requirements.txt`/`pyproject.toml` (Python), `pubspec.yaml` (Flutter), `build.gradle` (Android), or asking the user.
+1. **Frameworks and languages**: detect them by reading `package.json` (Node.js), `go.mod` (Go), `composer.json` (PHP), `requirements.txt`/`pyproject.toml` (Python), `pubspec.yaml` (Flutter), `build.gradle` (Android), `Package.swift` / `*.xcodeproj` / `*.xcworkspace` / `Podfile` (iOS/Swift; note whether the sources are Swift or Objective-C, which picks the path in "Frontend and Mobile"), or asking the user.
2. **Services and entry points**: in a monorepo, list each deployable service and its entry point. Each service that should report to Traceway needs its own integration, and usually its own project token (ask the user before reusing one token across services).
3. **Background work**: find cron jobs, queue consumers, schedulers, CLI commands, and long-running workers. These must be instrumented as Tasks (Step 3).
4. **AI/LLM usage**: check dependencies for `openai`, `@anthropic-ai/sdk`, `anthropic`, `langchain` / `@langchain/*`, `ai` (Vercel AI SDK), `litellm`, `google-generativeai`, `cohere`, `openrouter`. If any are present, Step 4 applies.
@@ -250,6 +250,7 @@ For the per-framework init code (plain JS, React, Vue, Svelte/SvelteKit, jQuery)
- **Flutter**: `flutter pub add traceway`, then `Traceway.run(connectionString: '<token>@https://<instance>/api/report', child: MyApp())`. Then check whether the release build is obfuscated (`--obfuscate --split-debug-info`): if it is, production crash stack traces arrive obfuscated and stay unreadable until the build's `.symbols` files are uploaded, so ask the user for the upload token (Step 0) and wire up the symbol upload. For options, platform permissions, the navigator observer, screen recording, privacy masking, the obfuscation check and symbol upload, and the Flutter web caveat, read `flutter.md` in this skill directory. Docs: https://docs.tracewayapp.com/client/flutter
- **React Native**: `npm install @tracewayapp/react-native`, wrap the app in `TracewayProvider`. Docs: https://docs.tracewayapp.com/client/react-native
- **Android**: `implementation("com.tracewayapp:traceway:<version>")`, call `Traceway.init(...)` at startup. Docs: https://docs.tracewayapp.com/client/android
+- **iOS / Swift** (native SwiftUI or UIKit): add the Traceway iOS SDK via Swift Package Manager (`https://github.com/tracewayapp/traceway-ios.git`) and call `Traceway.start(connectionString: "<token>@https://<instance>/api/report", options: TracewayOptions(version: "1.0.0"))` as early as possible. It captures uncaught `NSException`s and fatal signals (hard crashes upload on the next launch) plus manual `Traceway.capture(...)`; it reports errors and crashes only (no session replay). Release crashes arrive as bare addresses until the build's dSYMs are uploaded, so set up dSYM upload with the upload token (Step 0). For init code, options, the debugger caveat, and dSYM upload, read `ios.md` in this skill directory. **If the app is NOT a Swift app** (Objective-C only, a cross-platform stack with no Traceway mobile SDK, or a team standardized on OpenTelemetry), there is no native SDK: use an OTel distribution like Honeycomb with its exporter pointed at `<instance>/api/otel` and a `Authorization: Bearer <project-token>` header, exactly like a backend (Step 2). The non-Swift path is also in `ios.md`.
## Step 5: Deployment and Server Metrics
@@ -287,7 +288,7 @@ Metrics arrive within ~60s under their hostmetrics names (`system.cpu.utilizatio
1. Start the app and hit a few endpoints (or trigger an error on purpose).
2. Check the Traceway dashboard:
- **Endpoints page**: routes appear grouped by pattern (e.g. `GET /api/users/:id`), not by literal URL, and status codes are non-zero.
- - **Issues page**: thrown errors appear with stack traces. For frontend projects, stack traces are symbolicated to original files and lines; for obfuscated Flutter builds, they resolve once the build's `.symbols` files have been uploaded.
+ - **Issues page**: thrown errors appear with stack traces. For frontend projects, stack traces are symbolicated to original files and lines; for obfuscated Flutter builds, they resolve once the build's `.symbols` files have been uploaded; for native iOS Release crashes, they resolve to symbol names and `file:line` once the build's dSYMs have been uploaded.
- **Endpoint detail -> Spans tab**: database queries and outgoing calls appear as children.
- **Tasks page**: after triggering each background job once, it appears under one stable name.
- **AI Traces page** (if Step 4 applied): model calls appear with token counts and cost.
diff --git a/skills/traceway-setup/ios.md b/skills/traceway-setup/ios.md
new file mode 100644
index 00000000..242a331d
--- /dev/null
+++ b/skills/traceway-setup/ios.md
@@ -0,0 +1,195 @@
+# iOS / Apple SDK Reference
+
+iOS and other Apple apps have two integration paths. Pick by what the app is written in:
+
+| App | Path |
+|---|---|
+| **Native Swift** (SwiftUI or UIKit) | The Traceway iOS SDK (below). Recommended. Native crash and error capture, reports to `/api/report` like the other Traceway mobile SDKs. |
+| **Anything else** (Objective-C only, a cross-platform stack with no Traceway mobile SDK, or a team already standardized on OpenTelemetry) | An OpenTelemetry distribution such as Honeycomb's, with its OTLP exporter repointed at Traceway. See "Non-Swift apps" at the bottom. |
+
+The Traceway iOS SDK reports **errors and crashes only**. There is no session or video replay (unlike Flutter). It speaks the same `/api/report` wire format as the Android, Flutter, and JS SDKs, so the backend ingests it with no server changes.
+
+## Swift apps: the Traceway iOS SDK
+
+The SDK lives at `github.com/tracewayapp/traceway-ios`. Pure Swift, zero third-party dependencies, distributed via Swift Package Manager.
+
+### Requirements
+
+- iOS 13.0+
+- Swift 5.9+ / Xcode 15+
+
+### Install (Swift Package Manager)
+
+In Xcode: **File > Add Package Dependencies...** and enter `https://github.com/tracewayapp/traceway-ios.git`, or add it to `Package.swift`:
+
+```swift
+.package(url: "https://github.com/tracewayapp/traceway-ios.git", from: "0.1.0"),
+```
+
+then add `"Traceway"` to the app target's dependencies.
+
+### Initialize
+
+Call `Traceway.start` as early as possible, in the `App` initializer (SwiftUI) or `application(_:didFinishLaunchingWithOptions:)` (UIKit). The connection string format is `<project-token>@https://<instance>/api/report`, identical to the other mobile SDKs.
+
+**SwiftUI:**
+
+```swift
+import SwiftUI
+import Traceway
+
+@main
+struct MyApp: App {
+ init() {
+ Traceway.start(
+ connectionString: "<project-token>@https://<instance>/api/report",
+ options: TracewayOptions(version: "1.0.0")
+ )
+ }
+
+ var body: some Scene {
+ WindowGroup { ContentView() }
+ }
+}
+```
+
+**UIKit:**
+
+```swift
+import UIKit
+import Traceway
+
+@main
+final class AppDelegate: UIResponder, UIApplicationDelegate {
+ func application(
+ _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
+ ) -> Bool {
+ Traceway.start(
+ connectionString: "<project-token>@https://<instance>/api/report",
+ options: TracewayOptions(version: "1.0.0")
+ )
+ return true
+ }
+}
+```
+
+Wire the token through a build setting or `Info.plist` value, not a committed literal. `Traceway.start` returns `nil` and no-ops on a malformed connection string, so a bad value fails quietly rather than crashing the host app.
+
+### What gets captured automatically
+
+After `start`:
+
+- **Uncaught `NSException`s** (Objective-C / UIKit).
+- **Fatal signals**: Swift runtime traps such as force-unwrapping `nil`, array out-of-bounds, `fatalError()`, integer overflow (surface as `SIGTRAP`, `SIGILL`, `SIGABRT`, `SIGSEGV`, ...). Hard crashes are persisted to disk and uploaded on the **next launch**, not at crash time.
+
+### Manual capture
+
+```swift
+do {
+ try somethingThrowing()
+} catch {
+ Traceway.capture(error) // Swift Error
+}
+
+Traceway.capture(error: nsError) // NSError
+Traceway.capture(message: "User completed onboarding")
+```
+
+### Forcing a flush
+
+Managed (in-process) reports are batched and sent after `debounceMs`. To send immediately, for example before a known exit:
+
+```swift
+Traceway.flush(timeout: 5) // seconds; nil = wait indefinitely
+```
+
+### Options (`TracewayOptions`)
+
+| Option | Default | Description |
+|---|---|---|
+| `sampleRate` | `1.0` | Fraction of exceptions to keep (0.0 to 1.0). |
+| `debug` | `false` | Log SDK activity via `NSLog`. |
+| `version` | `""` | App version, sent as `appVersion` (enables release comparison). |
+| `debounceMs` | `1500` | Delay before batching and uploading. |
+| `retryDelayMs` | `10000` | Delay before retrying a failed upload. |
+| `maxPendingExceptions` | `5` | In-memory cap; oldest is dropped when exceeded. |
+| `persistToDisk` | `true` | Persist pending reports so they survive restarts (required for hard-crash capture). |
+| `maxLocalFiles` | `5` | Max persisted report files. |
+| `localFileMaxAgeHours` | `12` | Delete unsynced files older than this. |
+
+### Testing crash capture (debugger caveat)
+
+Hard crashes are intercepted with POSIX signal handlers. When the **Xcode debugger is attached**, lldb intercepts `SIGSEGV` / `SIGTRAP` first, so the SDK's handler never runs and the crash is not recorded. To test the hard-crash path: install once via Xcode, **stop the debugger**, launch the app from the home screen, trigger the crash, then relaunch and watch the report upload from disk. Managed captures (`Traceway.capture(...)`) work with the debugger attached.
+
+### Symbolication: upload dSYMs
+
+Release crash reports arrive as bare instruction addresses against each loaded binary image. They stay unreadable until Traceway resolves them server-side against the build's **dSYM** debug symbols (the Apple equivalent of JavaScript source maps). Upload the dSYMs on every release build; a crash only resolves against the exact build it came from.
+
+**Token.** Symbol uploads authenticate with the dedicated **upload token** (Connection page > Source Maps / Symbol Upload), NOT the project token from the connection string. Get it from Step 0; it is a CI secret, never committed. `readonly` members cannot generate one. The upload endpoint is `https://<instance>/api/symbols/upload`.
+
+**Produce dSYMs.** The build must emit dSYMs: set `DEBUG_INFORMATION_FORMAT = dwarf-with-dsym` for the Release configuration (this is already the default for Archive builds). Without it there are no dSYMs to upload.
+
+**Upload script.** The SDK repo ships a ready-made uploader at `Scripts/upload_symbols.sh`. It finds this build's dSYM DWARF binaries (`*.dSYM/Contents/Resources/DWARF/*`) and POSTs each one as multipart `files=@...` to `/api/symbols/upload`. It derives the upload URL from a base URL or a `/api/report` URL, and no-ops safely (exit 0) on non-Release builds or when the token is unset, so it never breaks a Debug build. Copy it into the app repo, then add a **Run Script** build phase (Target > Build Phases > +) that runs it after the build:
+
+```bash
+"${SRCROOT}/Scripts/upload_symbols.sh"
+```
+
+Set the token and instance for the phase via the environment (CI secret in CI, a local untracked value otherwise):
+
+```bash
+TRACEWAY_UPLOAD_TOKEN=<upload-token>
+TRACEWAY_URL=https://<instance> # base URL; the script appends /api/symbols/upload
+```
+
+To upload by hand (for example from CI after an `xcodebuild archive`), point it at the dSYM directory:
+
+```bash
+TRACEWAY_UPLOAD_TOKEN=<upload-token> TRACEWAY_URL=https://<instance> \
+ ./Scripts/upload_symbols.sh --dsym-dir <path-to>.xcarchive/dSYMs --dry-run
+```
+
+`--dry-run` lists what would be sent without uploading. Inside an Xcode build phase, `DWARF_DSYM_FOLDER_PATH` is set automatically and no `--dsym-dir` is needed. If the SDK script is not vendored, the equivalent is one `find` piped to `curl`:
+
+```bash
+find "$DWARF_DSYM_FOLDER_PATH" -type f -path '*.dSYM/Contents/Resources/DWARF/*' \
+ -exec curl -fsS -H "Authorization: Bearer $TRACEWAY_UPLOAD_TOKEN" \
+ -F "files=@{}" "$TRACEWAY_URL/api/symbols/upload" \;
+```
+
+Self-hosted instances must have blob storage (S3 or a persistent volume) configured, or uploaded symbols disappear when the container is recreated.
+
+### Verify
+
+1. In a Debug build, tap a button that calls `Traceway.capture(SomeError())`, then `Traceway.flush(timeout: 5)`, and confirm it appears on the Issues page within a few seconds.
+2. For hard crashes: build a Release configuration, run it **without the debugger** (home-screen launch), trigger a crash (force-unwrap `nil`, `fatalError()`, ...), relaunch the app, and confirm the crash shows up on Issues.
+3. After uploading dSYMs for that Release build, confirm the crash stack trace shows real symbol names and `file:line`, not bare addresses.
+
+## Non-Swift apps: OpenTelemetry into Traceway
+
+For an iOS/Apple app that is not a Swift app the SDK targets (Objective-C only, a cross-platform stack with no Traceway mobile SDK, or a codebase already standardized on OpenTelemetry), there is no native Traceway SDK. Use an OpenTelemetry distribution such as **Honeycomb's** and repoint its OTLP exporter at Traceway. This is the same OTLP/HTTP path the backend uses (Step 2), so all the rules in `data-model.md` apply.
+
+A Honeycomb-style distro is configured with an API key plus an endpoint. Override both so the data lands in Traceway instead of Honeycomb:
+
+- **Endpoint**: `https://<instance>/api/otel` (the SDK appends `/v1/traces`, `/v1/metrics`, `/v1/logs`).
+- **Auth header**: `Authorization: Bearer <project-token>`. Traceway authenticates on this Bearer header, not on Honeycomb's `x-honeycomb-team`, so set the `Authorization` header explicitly (Honeycomb's own API-key header is ignored by Traceway and harmless).
+- **`service.name`** / **`service.version`**: set them; they become the Server Name and enable release comparison.
+
+```swift
+import Honeycomb
+
+let options = try HoneycombOptions.Builder()
+ .setServiceName("my-ios-app")
+ .setServiceVersion("1.0.0")
+ .setApiEndpoint("https://<instance>/api/otel")
+ .setHeaders(["Authorization": "Bearer <project-token>"])
+ .build()
+Honeycomb.configure(options: options)
+```
+
+(Field and builder names vary by distro version; the three things that matter are endpoint, the `Authorization: Bearer` header, and service name. A plain OpenTelemetry-Swift setup with an `OTLPHTTPExporter` pointed at the same endpoint and header is equivalent.)
+
+Constraints are the backend OTLP rules: OTLP/HTTP only (protobuf or JSON), OTLP/gRPC is NOT supported, gzip is fine, max request body 10 MB.
+
+How the data shows up follows the standard classification in `data-model.md`: recorded `exception` events become **Issues**, instrumented network calls and screen transitions become spans, and any span carrying HTTP attributes that looks like a root request becomes an **Endpoint**. Verify on the Issues page first: throw or record a test error and confirm it appears.