Title: Crash on startup when enabling R8 optimization · Issue #2039 · NativeScript/android · GitHub
Open Graph Title: Crash on startup when enabling R8 optimization · Issue #2039 · NativeScript/android
X Title: Crash on startup when enabling R8 optimization · Issue #2039 · NativeScript/android
Description: Environment Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project): CLI: 9.1.0 Cross-platform modules: @nativescript...
Open Graph Description: Environment Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project): CLI: 9.1...
X Description: Environment Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project): CLI: 9.1...
Opengraph URL: https://github.com/NativeScript/android/issues/2039
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Crash on startup when enabling R8 optimization","articleBody":"**Environment**\nProvide version numbers for the following components (information can be retrieved by running `tns info` in your project folder or by inspecting the `package.json` of the project):\n - CLI: 9.1.0\n - Cross-platform modules: `@nativescript/core` 9.1.0\n - Android Runtime: `@nativescript/android` 9.1.0 (commit `4e7f2076d0065d1bf157efe18f54dd7d7d73b0f4`)\n - iOS Runtime (if applicable): n/a\n - Plugin(s): none — reproduces on a bare `ns create --vue` app\n\nAlso: AGP 8.12.1, Gradle 8.14.3, JDK 21, compileSdk/targetSdk 35, minSdk 24,\nbuild tools 35.0.0, NDK r29. Device: Android emulator, API 35, arm64, 16 KB\npages (`sdk_gphone16k_arm64`).\n\n**Describe the bug**\nGoogle will soon require apps to be better optimized (see https://android-developers.googleblog.com/2026/08/app-quality-memory-optimization-secure-onboarding.html). To enable optimization with R8 one can add this to app.gradle:\n\n```\n buildTypes {\n release {\n minifyEnabled true\n shrinkResources true\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),\n \"${getAppResourcesPath()}/Android/proguard-rules.pro\",\n metadataKeepRules\n }\n }\n```\n\nHowever when doing this the app will crash on startup. Using the Opus 5 (1M) model, the following was found when investigating:\n\nWith `minifyEnabled true`, a NativeScript app crashes on cold\nstart with a **fatal JNI abort that names nothing**:\n\n```\nAbort message: 'JNI DETECTED ERROR IN APPLICATION: java_class == null\n in call to GetStaticFieldID\n from void com.tns.Runtime.runModule(int, java.lang.String)'\nsignal 6 (SIGABRT), code -1 (SI_QUEUE)\n #05 pc 00000000006356bc /apex/com.android.art/lib64/libart.so (art::JNI\u003cfalse>::GetStaticFieldID(...)+904)\n #06 pc 00000000003225cc base.apk!libNativeScript.so\n #07 pc 000000000031d8d0 base.apk!libNativeScript.so\n #08 pc 0000000000335658 base.apk!libNativeScript.so\n```\n\nThere are two separate problems here. The second is the reason the first is so\nexpensive.\n\n### 1. The runtime passes an unchecked `FindClass` result to JNI\n\n`FieldAccessor::GetJavaField` uses `JEnv::FindClass`'s return value without\nchecking it:\n\n```cpp\n// test-app/runtime/src/main/cpp/FieldAccessor.cpp\nif (isStatic) {\n fieldData->clazz = env.FindClass(fieldMetadata.getDeclaringType());\n fieldData->fid = env.GetStaticFieldID(fieldData->clazz, fieldMetadata.name, fieldJniSig);\n```\n\n`JEnv::FindClass` returns `nullptr` — with a Java exception left **pending**\n(`JEnv.cpp`, the `m_env->Throw(...)` branches) — whenever the class is not in the\ndex. `GetStaticFieldID(nullptr, ...)` is then a fatal abort, and it happens\n*before* the runtime constructs any exception, so neither the class nor the\nmember name is ever logged. Calling a further JNI function with an exception\nalready pending is itself illegal, so this is a JNI contract violation\nindependent of the missing class.\n\n`SetJavaField` and `MethodCache::ResolveMethodSignature` guard the identical\npattern with `NS_DCHECK`, which compiles to nothing in release builds\n(`NativeScriptAssert.h`) — so they are equally fatal in exactly the builds where\nthis occurs.\n\nThe consequence is that the crash destroys the information needed to fix it.\nThere is no `-keep` rule you can write for a class whose name you cannot learn.\n\n### 2. Metadata is generated pre-R8 and nothing tells R8 what it covers\n\n`buildMetadata` runs against the full compile classpath before R8. Every type in\nthat metadata is reachable from JavaScript and, typically, from nowhere else — no\nbytecode references it — so R8 is free to shrink or rename it, and the runtime\nthen asks the VM for a name that is no longer there.\n\nTwo failure shapes follow, and the second is what makes the usual advice fail:\n\n- **Class removed.** A bare `ns create --vue` app crashes with\n `ClassNotFoundException: androidx.activity.OnBackPressedCallback`.\n- **A type named in a signature renamed.** After `-keep class androidx.activity.** { *; }`\n the dex contains\n `OnBackPressedDispatcher.addCallback(Landroidx/lifecycle/t;Landroidx/activity/OnBackPressedCallback;)V`\n while the metadata asks for `Landroidx/lifecycle/LifecycleOwner;`. The\n declaring class was kept and the method was kept — a **parameter type** was\n renamed, and JNI resolves by full signature.\n\nSo keeping a class protects nothing unless every type named in every signature\nreachable from JavaScript is kept too. In practice that is the transitive\nclosure of the metadata, i.e. nearly the whole compile classpath, and\nnamespace-by-namespace `-keep` rules cannot converge on it.\n\n**To Reproduce**\n```sh\nns create repro --vue --appid com.example.repro\ncd repro\nnpm pkg set dependencies.@nativescript/core=9.1.0\nnpm pkg set dependencies.@nativescript/android=9.1.0\nnpm install\n```\n\n`App_Resources/Android/app.gradle`, inside `android { }`:\n\n```groovy\nbuildTypes {\n release {\n minifyEnabled true\n shrinkResources true\n proguardFiles getDefaultProguardFile('proguard-android-optimize.txt')\n }\n}\n```\n\nBuild a release APK, `adb uninstall`, install, launch. Crashes on first launch\nwith `ClassNotFoundException: androidx.activity.OnBackPressedCallback`.\n\nTo reach the *unnamed* abort — the one this report is really about — add\n`-keep class androidx.activity.** { *; }`, then put a **static field read on a\nclass R8 renames** at the top of `app.ts`, so it runs inside `runModule`:\n\n```ts\n// androidx.lifecycle.Lifecycle$State is renamed: nothing in bytecode names it\nconst state = (androidx as any).lifecycle.Lifecycle.State.CREATED\n```\n\nThat reproduces the abort quoted above with zero third-party dependencies. In our\ntesting the `libNativeScript.so` frame offsets (`0x3225cc`, `0x31d8d0`,\n`0x335658`) matched a production app's tombstone exactly, confirming the same\ncode path.\n\n**Expected behavior**\n\n1. A class missing from the final dex must never be a silent native abort. The\n runtime should check `FindClass`, consume the pending exception, and raise a\n `NativeScriptException` naming the class and the member — diagnosable from\n JavaScript and actionable with a `-keep` rule.\n2. `minifyEnabled true` should either work out of the box, or fail with an error\n that says what to keep. Today a default `ns create` app cannot be shipped with\n R8 enabled and gives the developer nothing to act on.\n\n**Additional context**\n\nThese were written by Claude (Opus 5) while diagnosing this against the runtime\nsource at `4e7f2076`, built from source and swapped into the app. They work, and\nthey are offered as evidence of where the problem is — **not** as a finished\ndesign. We would expect a maintainer to disagree with parts of the second and\nthird in particular.\n\n**(a) Never hand a null `jclass` to JNI.** Adds\n`JEnv::FindClassOrThrow(className, usage)`, which clears the pending exception\nand throws a `NativeScriptException` naming the class and member, and routes the\nmetadata-driven lookups through it (`FieldAccessor` ×4, `MethodCache`,\n`JsArgConverter`, `JsArgToArrayConverter`). The abort becomes:\n\n```\ncom.tns.NativeScriptException: Module evaluation promise rejected: .../bundle.mjs —\n Cannot resolve class 'androidx.lifecycle.Lifecycle$State' while reading field 'CREATED'.\n```\n\nThis one we would argue for regardless of how the rest is solved. It is small,\nit has no downside, and it converts an undebuggable abort into an ordinary\nerror. The `NS_DCHECK` guards elsewhere should probably become real checks too,\nsince they protect nothing in release builds.\n\n**(b) Generate the keep rules from the metadata.** The metadata already *is* the\nset of types JavaScript can reach, so the generator can emit the rules for it:\n`-keep class X { *; }` for declared types, `-keep class X` for types named only\nin signatures. Wired in via `proguardFiles` plus\n`minify*WithR8.dependsOn(buildMetadata)` — which is acyclic, since\n`buildMetadata` reads compiled classes and dependency jars and never anything R8\nproduces. This is roughly what the commented-out line at `app/build.gradle:1236`\n(\"ensure buildMetadata is done before R8 to allow custom proguard from\nmetadata\") seems to have intended.\n\nTwo traps worth knowing, both silent:\n\n- `buildMetadata` declares only the three `.dat` files as outputs, so Gradle\n considers it up-to-date and never regenerates the rules; R8 then reads a stale\n file. The task needs the generated rule file registered as an output.\n- Nested types are separate tree nodes, so a naive join emits\n `androidx.lifecycle.Lifecycle.State`. ProGuard reads that as class `State` in\n package `…Lifecycle`, matches nothing, and R8 strips the members. A mistyped\n keep rule is never an error — only an absent protection.\n\n**(c) Ship R8's mapping and translate at lookup time.** (b) is correct but\npins every name, so R8 can no longer rename anything — Play's App optimisation\npanel reads ~0 for shrinking and optimisation. Regenerating the metadata after\nR8 is *not* the fix: those names are also the names the JS bundle writes, so\npost-R8 names would break every call site.\n\nWhat does work is translating on the way out. The build writes R8's class\nmapping beside the metadata (`assets/metadata/r8-mapping.dat`), the runtime\nloads it, and `JEnv::FindClass` plus the four member-lookup wrappers translate\nclass names and the `Lsome/Type;` inside signatures. The metadata and JavaScript\nkeep talking about `androidx.lifecycle.LifecycleOwner` while the VM is asked for\n`androidx.lifecycle.t`, and the generated rules can then say\n`-keep,allowobfuscation`.\n\nTranslation turned out to be needed in four places, and the last one is worth\nraising on its own:\n\n| path | where |\n|---|---|\n| JNI class lookup | `JEnv::FindClass` |\n| JNI signatures | the four `JEnv` member-ID wrappers |\n| runtime binding generation | `DexFactory.generateDex` → `Class.forName` |\n| central class lookup | `ClassStorageServiceImpl.retrieveClass` |\n\nEvery Java-side resolution funnels through `ClassStorageServiceImpl`, so one\ntranslation there covers the Java side — except that `DexFactory`'s two\n`Class.forName` calls bypass that service entirely. That looks like an\ninconsistency in the runtime independent of this change.\n\n**This is the part we are least confident in**, and we would rather it prompted a\ndesign discussion than be taken as a patch. Measured on the repro app, 5/5 cold\nstarts clean:\n\n| | names pinned | with remap |\n|---|---|---|\n| classes renamed | 1 251 (30%) | 3 985 (94%) |\n| `r8.json` non-obfuscated | 81.89% | 76.45% |\n| AAB bytes | 43 107 514 | 43 234 501 |\n\n94% of classes renamed, but the obfuscation figure moved only ~5 points and the\nbundle grew 127 KB, because the mapping asset is 271 KB. Known gaps:\n\n- It pins *member* names (`-keepclassmembernames`) so only a class map has to be\n shipped. Members are the bulk of the identifier mass, so this is what caps the\n gain. Allowing member renaming needs the member mapping and signature-keyed\n lookups — a materially bigger change, and the obvious next step for anyone who\n wants this to score well.\n- `com.tns.**` is excluded from renaming, because the runtime resolves those by\n hardcoded name from C++ before the mapping has even been read.\n- Getting the mapping into the APK at all is awkward: assets are merged **and\n compressed** (`compress\u003cVariant>Assets`) before R8 runs, so writing into the\n merged-assets directory from R8's `doLast` puts the file on disk after the only\n task that would have packaged it — silently, with no warning. It works as a\n generated asset source whose task depends on R8, which then also has to be\n declared to the lint tasks. A first-class place for post-R8 build output would\n be better than either.\n\nOn the evidence above we would not claim this pays for itself as an\noptimisation yet. It demonstrates that renaming can be supported without\nbreaking JavaScript; (b) alone ships a smaller bundle for far less machinery.\n\nThe honest summary: (a) is a bug fix we would ship as-is. (b) makes R8 usable and\nis close to what the repository already gestured at. (c) demonstrates that\nrenaming *can* be supported without breaking JavaScript, but the version here\nbuys only part of the available benefit and deserves a better design than we\ngave it.\n\n### Smaller notes\n\n- Metadata filtering (`whitelist.mdg` / `blacklist.mdg`) is read from the Gradle\n root, which `ns prepare` regenerates. A file placed there by hand disappears on\n the next build and the metadata is silently unfiltered. It would help if the\n filters were sourced from `App_Resources` — or at least if an absent filter\n were logged.\n- An absent `whitelist.mdg` defaults to `*:*`, but a present-and-empty one\n replaces that default and allows almost nothing. That asymmetry is a sharp\n edge; an empty whitelist is far more likely to be a mistake than an intent.","author":{"url":"https://github.com/BozzaDaniel","@type":"Person","name":"BozzaDaniel"},"datePublished":"2026-09-11T09:55:16Z","url":"https://github.com/NativeScript/android/issues/2039"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:3244fbae-9b31-5545-f4c3-ceb97b59fc5d |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E0CA:213839:245A3FE:2E73240:6B017928 |
| html-safe-nonce | 4890c1a99c76a5f324bc1d36272aa93cb5ad95e32e6bef1834421b9647a6ad85 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMENBOjIxMzgzOToyNDVBM0ZFOjJFNzMyNDA6NkIwMTc5MjgiLCJ2aXNpdG9yX2lkIjoiNjY4ODY0MTIxNTY4NjA4MDgwOCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 035b20504a806c039e5f8b6cd7bcfd653d8131707e429ee298b2f14a623e13c8 |
| hovercard-subject-tag | issue:5422956087 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/NativeScript/android/2039/issue_layout |
| twitter:image | https://opengraph.githubassets.com/f113ea62692a4405a1d02daed7b90637a480e1cddbccf5999fe1986f6896e9d9/NativeScript/android/issues/2039 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/f113ea62692a4405a1d02daed7b90637a480e1cddbccf5999fe1986f6896e9d9/NativeScript/android/issues/2039 |
| og:image:alt | Environment Provide version numbers for the following components (information can be retrieved by running tns info in your project folder or by inspecting the package.json of the project): CLI: 9.1... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | BozzaDaniel |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/NativeScript/android git https://github.com/NativeScript/android.git |
| octolytics-dimension-user_id | 7392261 |
| octolytics-dimension-user_login | NativeScript |
| octolytics-dimension-repository_id | 29137950 |
| octolytics-dimension-repository_nwo | NativeScript/android |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 29137950 |
| octolytics-dimension-repository_network_root_nwo | NativeScript/android |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width