# Flutter native crashes, ANRs and hangs

> **Status: implemented, device validation pending.** The Flutter SDK's native capture, the symbol
> uploads and the server-side symbolication are written, and the parts that can run on a Linux build
> machine (the TypeScript parsers, ingest, the C crash core, ELF and DWARF symbolication) have been
> tested there. The Dart, Kotlin and Swift code, the Gradle and CocoaPods / Swift Package Manager
> integration and the NDK builds for ARM have **not been compiled or run on a real Android or iOS
> device or in a store build**. Nothing on this page is device-verified. Until a person has worked
> through the validation list at the end, **do not choose Bucker for mobile**.

The Flutter SDK has always captured Dart-layer errors. Most of the crash volume on a real mobile app
is not Dart: a `SIGSEGV` in a plugin's C++, a Java exception on a thread Dart never saw, an Android ANR
the OS killed the app for, an iOS watchdog hang. This page is what the SDK is built to capture, how
to set it up, how to upload the symbols that make the result readable, and what it does not cover.

Every native event is sent as an ordinary Bucker `event`, so issues, grouping, release health, alerts
and the fix loop apply unchanged. There is no separate mobile surface to evaluate.

## What is captured

| Source | Platform | Arrives as |
| --- | --- | --- |
| A signal in any native library (`SIGSEGV`, `SIGABRT`, `SIGBUS`, `SIGILL`, `SIGFPE`, `SIGTRAP`, stack overflow), including your plugins and the Flutter engine | Android | `native` platform, `fatal` |
| An uncaught JVM throwable on a thread Dart never saw | Android | `java`, `fatal` |
| An ANR the OS killed the app for (`ApplicationExitInfo.REASON_ANR`, Android 11 / API 30 and later) | Android | `java`, `fatal`, `contexts.hang` |
| A live main-thread stall past the ANR threshold (a watchdog) | Android | `java`, `error`, `contexts.hang` |
| A Mach exception, signal or uncaught `NSException` (PLCrashReporter) | iOS | `native`, `fatal` |
| A live main-thread hang (a watchdog) | iOS | `native`, `error`, `contexts.hang` |
| MetricKit hang, crash (only when PLCrashReporter did not see it), CPU-exception, disk-write and app-launch diagnostics | iOS 14+ (launch: iOS 16+) | `native`, `contexts.hang` for hangs |
| A frozen Flutter frame, only where no native hang detector is available | both | `dart`, `warning`, `AppHang` |

All hangs share one shape, `contexts.hang` (source, duration in milliseconds, threshold, whether the
OS killed the process, the blocking thread), so "the app froze" is one kind of issue whatever
detected it.

### One launch late

A native crash kills the process before Dart can send anything. The plugin writes a record to
app-private storage, and the **next launch** sends it with the original timestamp, the release that
crashed (never the current one) and the breadcrumbs, user and session the SDK last pushed before the
crash. Up to about one second of the newest breadcrumbs can be missing. The record is deleted on the
device only after its envelope was accepted, written to the offline cache or deliberately dropped, and
its event id is fixed before the crash, so a resend is de-duplicated. The crashed session is ended as
`crashed` (a fatal ANR as `abnormal`), so crash-free rates move.

## Set up

Add the SDK as usual (`flutter pub add bucker_flutter`) and keep `Bucker.init` as early as you can.

```dart
await Bucker.init(
  dsn: 'https://<publicKey>@us.ingest.bucker.io/<projectId>',
  release: 'com.acme.app@1.4.2+118',   // must match what you pass to bucker_symbols
  // All of these are the defaults:
  enableNativeCrashes: true,
  enableAnrDetection: true,            // Android
  anrTimeoutMs: 5000,                  // never below 1000
  enableAppHangTracking: true,         // iOS watchdog and MetricKit; Dart frame timing as a fallback
  appHangTimeoutMs: 2000,              // never below 2000
  attachNativeThreads: false,          // send only the crashed thread's stack
  appRunner: () => runApp(const MyApp()),
);
// NativeCrashSupport.capability is `absent` until the platform plugin answered the handshake.
// NativeCrashSupport.detail says why when it is absent ("plugin not linked", "not a mobile platform", ...).
```

`NativeCrashSupport.capability` is `available` only after the plugin reported its crash handler
installed. If it is `absent`, no native crash can be captured, and the SDK says so rather than
reporting an empty result as "no crashes".

### Android

- Nothing to add for crashes and ANRs: the plugin's `ContentProvider` installs the handlers before
  `Application.onCreate`, so it also covers crashes before `Bucker.init`. To install them from Dart
  instead, set `<meta-data android:name="io.bucker.native.auto_init" android:value="false"/>`.
- Minimum SDK 21. `ApplicationExitInfo` needs API 30; below that the ANR source is the live watchdog
  only.
- To make **JVM and ANR stacks readable after R8**, stamp the mapping id into the APK by adding one line
  to `android/app/build.gradle` (requires Android Gradle Plugin 8):

  ```groovy
  apply from: project(':bucker_flutter').file('bucker-proguard.gradle')
  ```

  The task `buckerStampProguardUuid<Variant>` runs after `minify<Variant>WithR8` and writes the id of
  that build's `mapping.txt` into the app, so a crash names the mapping to look up. It uploads nothing.

### iOS

- Nothing to add for crashes: the plugin enables PLCrashReporter when it registers. Both CocoaPods
  and Swift Package Manager layouts are provided.
- Native capture is **off while a debugger is attached** (the debugger takes the exception ports);
  `NativeCrashSupport.detail` then reads "debugger attached". Test with the app launched from the
  home screen, not from Xcode.
- MetricKit diagnostics are delivered by the OS: on iOS 14 at most once a day, and from iOS 15 on
  the next launch after the diagnostic. So a MetricKit hang or crash arrives a launch, or on iOS 14
  up to a day, after it happened (not yet verified on a device: validation item H-07).
- The app needs no new permission. The plugin ships a privacy manifest.

### A test crash

With `enableNativeTestCrashes: true` the SDK allows `NativeCrashSupport.crashForTesting(kind)` with a
`NativeTestCrash` kind: `segv`, `abort`, `hang`, plus `jvm` on Android and `nsexception` on iOS. Trigger one in a **release** build on a device, relaunch, and
check the issue arrives. This is also the first of the validation items below.

## Upload symbols

A native frame is an address inside a library. It becomes a function and a line only when Bucker has
the debug file for **that exact build**, found by its build id (the debug id). Uploads are keyed by
debug id, never by file name or release.

> **Native uploads are off unless the operator turns them on.** The server accepts `ELF_DEBUG`,
> `DSYM`, `DART_SYMBOLS`, `DART_OBFUSCATION_MAP` and `PROGUARD` only when
> `SYMBOLICATION_NATIVE_UPLOADS=true` is set on the deployment (off by default). Otherwise the upload is
> refused with a `422` (`reason: native-symbolication-not-offered`) and `bucker_symbols` says so.

| What you ship | Upload kind | Where it comes from |
| --- | --- | --- |
| Dart code, with `--obfuscate --split-debug-info` | `DART_SYMBOLS` | the `*.symbols` files in the split-debug-info directory, keyed by their ELF build id |
| Dart names, with `--save-obfuscation-map` | `DART_OBFUSCATION_MAP` | the obfuscation map, uploaded once per `.symbols` build id |
| Your own C/C++ or a plugin's `.so` on Android | `ELF_DEBUG` | the **unstripped** `.so` from the Gradle build (`merged_native_libs`, `cxx`, `cmake`, `ndkBuild`) |
| iOS code, including `App.framework` and plugin frameworks | `DSYM` | the `.dSYM` bundles (zip them, or use the CLI); a universal dSYM is stored as one row per architecture |
| R8 / ProGuard on Android | `PROGUARD` | `build/app/outputs/mapping/<variant>/mapping.txt` |

The one command that does all of it, and checks the result, is `bucker_symbols`:

```bash
export BUCKER_API_URL=https://api.bucker.io
export BUCKER_AUTH_TOKEN=…            # a token that can write artifacts

dart run bucker_flutter:bucker_symbols \
  --org acme --project mobile \
  --target appbundle --flavor prod \
  --save-obfuscation-map \
  --release-version 'com.acme.app@1.4.2+118' --dist 118
```

It builds with `--obfuscate --split-debug-info`, reads the debug ids out of everything the build produced
**and** out of the shipped binaries, refuses to continue if a shipped binary has no matching symbol file
(the flavor bug), uploads everything, then asks the server to resolve the shipped ids and fails the build
if any does not. Use `--native-libs-dir` for unstripped libraries in a custom location, and
`--target ipa` for iOS. `libapp.so` is never uploaded as `ELF_DEBUG`: its symbols are the `.symbols` file
with the same build id.

### CI snippets

Android, GitHub Actions style:

```yaml
- name: Build, upload symbols, verify (Android)
  env:
    BUCKER_API_URL: ${{ secrets.BUCKER_API_URL }}
    BUCKER_AUTH_TOKEN: ${{ secrets.BUCKER_AUTH_TOKEN }}
  run: |
    dart run bucker_flutter:bucker_symbols \
      --org acme --project mobile --target appbundle --flavor prod \
      --save-obfuscation-map --require-shipped-binary \
      --release-version "com.acme.app@${GITHUB_REF_NAME}"
```

iOS (a macOS runner; the dSYMs come out of the archive):

```yaml
- name: Build, upload symbols, verify (iOS)
  env:
    BUCKER_API_URL: ${{ secrets.BUCKER_API_URL }}
    BUCKER_AUTH_TOKEN: ${{ secrets.BUCKER_AUTH_TOKEN }}
  run: |
    dart run bucker_flutter:bucker_symbols \
      --org acme --project mobile --target ipa --flavor prod \
      --save-obfuscation-map --require-shipped-binary \
      --release-version "com.acme.app@${GITHUB_REF_NAME}"
```

If you build outside the CLI, upload each file with the artifacts API (`POST
/orgs/:org/projects/:project/artifacts`, `type` one of the kinds above). `debugId` is optional for the
native file kinds: the server reads it from the file and answers `422 debug-id-mismatch` if you send one
that disagrees. A Mach-O or ELF file can be sent directly or inside a ZIP (at most 64 entries and 256 MiB
inflated; a single file is limited to 64 MiB, which today refuses very large dSYMs).

Exit codes of `bucker_symbols` are stable: `0` all shipped ids resolve, `64` usage, `65` build failed,
`66` a shipped binary has no matching symbol file, `67` the server could not resolve a shipped id,
`68` an upload failed.

### The ProGuard / R8 id

A mapping is keyed by a debug id the server derives from `mapping.txt` itself: the `# uuid:` header if
the file has one, otherwise the first 16 bytes of its SHA-256. The Gradle stamp above and the upload
compute the same id from the same file. R8's own `pg_map_id` header is **not** used as the key.

## ANR versus hang

The two words name different things, and the product keeps them apart:

- **ANR** is Android's own verdict. The OS killed the app because it did not respond (the
  `ApplicationExitInfo` record, `fatal`, delivered on the next launch, duration unknown), or the SDK's
  watchdog saw the main thread blocked for `anrTimeoutMs` (default 5 s) while the app was in the
  foreground (`error`, one event per stall, duration measured).
- **App hang** is the iOS and Dart wording for the same symptom with a lower bar: `appHangTimeoutMs`
  (default 2 s, never below 2 s). Sources are the iOS watchdog, MetricKit's `MXHangDiagnostic`, and as a
  fallback a Dart frame that took too long, which carries no stack.

Both land in the same `contexts.hang` schema, with the stack of the blocked thread as the event's
stack. The exception value shows a **bucket** (`2-5s`, `5-10s`, `10-30s`, `>30s`), not the raw time, so
one stall does not split into many issues; the exact milliseconds are in `contexts.hang.duration_ms`.
The live watchdogs (the Android main-thread watchdog and the iOS watchdog) do not report while the app
is in the background or a debugger is attached, and the Flutter frame-timing fallback does not report
while the app is in the background. Hangs the OS reports afterwards can come from the background: an
`ApplicationExitInfo` ANR and a MetricKit hang carry `contexts.hang.foreground` saying which.

## What is and is not collected

Collected, for a native crash: the signal or exception and its code and fault address, the stack of the
crashed thread with instruction addresses and image paths and build ids, four registers (`pc`, `sp`,
`fp`, `lr`), the loaded libraries, the OS, device and app build, and the breadcrumbs, user and session
the SDK last pushed. For a hang: the source, duration, threshold and the blocking thread's stack.

Not collected: **memory contents** of any kind (no heap, no stack memory, no register other than the
four; the raw Android tombstone `ApplicationExitInfo` offers on Android 12+ is not attached, only its
size, and the server strips one an older SDK sent), other threads' stacks unless you set `attachNativeThreads: true` (the Dart layer drops them
otherwise), screenshots, files, the fatal-error message text of a Swift `fatalError`, or request
bodies and headers. Everything goes through the same scrubbing as any other event.

Two things to know about data at rest on the device:

- The scope the SDK pushes to the native plugin (breadcrumbs, user, session, at most 64 KiB) and a
  pending crash record sit in app-private storage **in plaintext** until the record is sent.
  `envelopeCodec` does not cover them. `beforeBreadcrumb` and `setUser` decide what goes in.
- With `enableNativeCrashes: false` the SDK sends no scope and tells the plugin to uninstall its handlers.
  On Android the init provider still runs first unless you set `auto_init` to `false`; on iOS the change
  applies from the next launch.

## Known limits

Android:

- **ARM unwinding.** On 32-bit ARM the unwinder (EHABI) and the frame-pointer fallback are written but
  unproven across the signal frame; expect short or wrong stacks on some armv7 devices. arm64 frame
  pointers and pointer-authentication bits are also unproven. Frames from code built without frame
  pointers may be shortened.
- **Multi-process apps.** Only the app's main process is read for exit reasons and has the Dart layer;
  a `:remote` process's crash is not turned into an event.
- **Crashes before init.** A crash before the provider runs, or before the Dart `init` has pushed a scope,
  still produces a record but without breadcrumbs, user or release from Dart. A crash loop at startup
  keeps at most 10 records, which are delivered when a launch survives.
- **The signal handler is best-effort.** It writes a complete record first and then tries a more
  thorough unwind that is not guaranteed to be async-signal-safe; if that second step hangs, the first
  record is recovered on the next launch.
- Native main-thread frames are not captured by the Android watchdog (only JVM frames).

iOS:

- **No capture under a debugger.** And a crash on a Simulator is not a reliable test.
- **No bitcode.** Apple no longer recompiles your app, so the dSYMs in your own archive are the ones that
  match the shipped binary; there are no Apple-generated dSYMs to download. Upload them from the build.
- **MetricKit is delayed**: on iOS 14 up to a day, from iOS 15 until the next launch (unverified on a
  device, H-07), and a MetricKit record carries no breadcrumbs, user or
  session. A crash both PLCrashReporter and MetricKit saw is sent once; two different crashes of the same
  kind in one MetricKit window may be merged.
- The compact Swift demangler is partial: some Swift names stay mangled and signatures are omitted.
- PLCrashReporter is pinned to the 1.11 line, which can conflict with an app already on a newer one.

Dart and symbols:

- **Obfuscation needs the matching symbols.** An obfuscated Dart frame resolves only through the
  `.symbols` file with the same build id. A different flavor, a rebuilt app or a stripped CI artifact is a
  different id and the frame stays unresolved.
- Dart frames inside an iOS native stack (image `App`) are not yet mapped to the `.symbols` build id.
- Flutter **web and desktop** are out of scope: there is no native plugin there, so
  `NativeCrashSupport.capability` is `absent` and only Dart-layer capture applies.
- Sentry's own mobile SDKs are not part of this: they are accepted as errors only.

## Troubleshooting: my crash is unreadable

Open the event and look at an unresolved frame. It says why, in a word, and shows the image, address and
offset so you can place it by hand.

| What you see | Meaning | Fix |
| --- | --- | --- |
| "No uploaded map" or "Missing debug id" on a native frame | No debug file with this build id was uploaded for this project | Run `bucker_symbols` for **this** build and flavor, and check the upload did not get a `422` |
| `native-symbolication-not-offered` when uploading | The deployment has native uploads off | The operator sets `SYMBOLICATION_NATIVE_UPLOADS=true` |
| `debug-id-mismatch` when uploading | The `debugId` you sent is not one in the file | Omit `debugId` for native kinds and let the server read it |
| "No image covers this address" | The frame's address is in no library the device listed | Usually a very short record or a library loaded late; check the image list in the Raw tab |
| Frames resolve for your code but not `libflutter.so` | The engine's symbols were not uploaded | Upload the engine's debug symbols for your Flutter version as `ELF_DEBUG` (iOS: `DSYM`), where Flutter publishes them; this path is not yet validated |
| Obfuscated Dart frames, tag `dart.obfuscated=true` | The `.symbols` file for the tagged build id is missing | Upload it; the tag names the id |
| A Java frame named `a.b.c` | The `PROGUARD` mapping is missing, or the Gradle stamp is not applied | Upload `mapping.txt` and apply `bucker-proguard.gradle` |
| An old issue split after an upload | Reprocessing rewrites frames but never regroups; the new events group by their resolved frames | Merging the two issues is a human decision |
| No native events at all | `NativeCrashSupport.capability` is `absent`, a debugger was attached, or the crash was before the plugin loaded | Read `NativeCrashSupport.detail`; launch outside the debugger |

A crash whose native frames are still unresolved is **refused by the automated-fix gate**: Bucker will not
hand an agent a stack it cannot read.

## What is still to be validated by a person

Each of these needs a real device or store account; none has been done.

1. A release-mode `crashForTesting('segv')` and `'abort'` on Android arm64 and armv7 delivers one event on the next launch, and frames resolve after uploading `libapp.so`'s `.symbols` and an `ELF_DEBUG` file.
2. A Java exception in app code does not produce a native record, and a plugin's own `SIGSEGV` does (ART signal-chain ordering).
3. `ApplicationExitInfo` ANR trace parsing on Android 11 to 15, the 5 s watchdog fires once per stall, and nothing fires in the background.
4. The R8 mapping id stamped by Gradle equals the one the server derives, and a JVM crash deobfuscates; the Gradle file builds under AGP 8.
5. The Android module builds for all four ABIs under the NDK, and the signal-handler symbol audit passes on the NDK objects.
6. iOS: PLCrashReporter resolves under CocoaPods and Swift Package Manager, a test crash records on arm64 and arm64e, frames resolve with the real dSYMs, and a real MetricKit hang and crash payload converts as written (including call-tree orientation and the duplicate rule).
7. A real `--obfuscate --split-debug-info` trace symbolicates to the same lines as `flutter symbolize`, on Android and iOS.
8. A crash marks its session `crashed` exactly once and the release attributed is the crashed build's.
9. Store review: no new permission, and the privacy manifest declarations are accepted by Apple and the Play data-safety form.
10. The Dart code compiles and its test suite passes under `flutter test` and `dart analyze`.

The authoritative list, with the numbered items, is in the repository's `docs/unified-platform/wp/NATIVE-CRASH.md`
and the SDK README. Related: [Platforms](platforms.md), [Sentry SDK compatibility](sentry-compat.md),
[DSNs and regions](dsn-and-regions.md).
