From 4b90923467e62f8ef596a1b353701d5de9160536 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 13:29:19 -0300 Subject: [PATCH 1/6] feat(runtime): wrapper lifetime config and counters Reads "wrapperLifetime": { "mode", "scope" } from the top level of the app's package.json, the key iOS reads, once per process. "resurrecting" stays the only mode for now; "rooted" is iOS-only and falls back with a warning. ns:runtime exposes both values as read-only config keys, and getWrapperLifetimeStats() returns per-runtime counters of resurrections, weakened Java objects, collected wrappers, explicit releases and uses of wrappers whose Java object was already collected. --- docs/ns-builtin-modules.md | 37 +++++++ test-app/app/src/main/assets/app/mainpage.js | 1 + .../main/assets/app/tests/testNsRuntime.js | 2 +- .../assets/app/tests/testWrapperLifetime.js | 97 +++++++++++++++++++ test-app/runtime/CMakeLists.txt | 1 + .../runtime/src/main/cpp/NsBuiltinModules.cpp | 45 ++++++++- .../runtime/src/main/cpp/ObjectManager.cpp | 56 ++++++----- test-app/runtime/src/main/cpp/ObjectManager.h | 8 ++ test-app/runtime/src/main/cpp/Runtime.cpp | 2 + test-app/runtime/src/main/cpp/Runtime.h | 2 + .../runtime/src/main/cpp/WrapperLifetime.cpp | 30 ++++++ .../runtime/src/main/cpp/WrapperLifetime.h | 60 ++++++++++++ .../runtime/src/main/cpp/com_tns_Runtime.cpp | 6 +- .../runtime/src/main/cpp/js/ns-runtime.js | 3 +- .../src/main/java/com/tns/AppConfig.java | 43 +++++++- .../src/main/java/com/tns/Runtime.java | 2 + 16 files changed, 366 insertions(+), 29 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/testWrapperLifetime.js create mode 100644 test-app/runtime/src/main/cpp/WrapperLifetime.cpp create mode 100644 test-app/runtime/src/main/cpp/WrapperLifetime.h diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index c2d66a5e4..dd67f9612 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -103,6 +103,7 @@ wrapper. |---|---| | `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. | | `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. | +| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. | | `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). | *Platform note (Android):* the original exception is the Java throwable `x` @@ -117,6 +118,8 @@ Config keys: | key | values | scope | default | |---|---|---|---| | `debug` | comma-separated category list, e.g. `"esm,fetch"` | process-wide (main-isolate writes only; read live by every isolate) | the `NS_DEBUG` environment variable, or `""` | +| `wrapperLifetimeMode` | `"resurrecting"` | process-wide, read-only | the app config `"wrapperLifetime": { "mode": … }`, or `"resurrecting"` | +| `wrapperLifetimeScope` | `"extended"` \| `"all"` | process-wide, read-only | the app config `"wrapperLifetime": { "scope": … }`, or `"extended"` | iOS additionally registers `releasedObjectPolicy`, which governs access to a wrapper whose native counterpart has already been released. Android does not @@ -145,10 +148,44 @@ The `TypeError` messages are part of the contract: | bad `getConfig` arity or non-string key | `getConfig expects (key: string)` | | process-wide key written from a worker | `'' is process-wide and can only be set from the main isolate` | | non-string `debug` value | `'debug' must be a comma-separated category string (), or '' to disable tracing` | +| `setConfig` of `wrapperLifetimeMode` or `wrapperLifetimeScope` | `'' is read-only; set "wrapperLifetime" in the app config` | `` is the runtime's own list of valid category names, which on Android expands to `esm,fetch,registry`. +#### Wrapper lifetime + +How the JS wrappers of Java objects live is chosen once per process by the +top-level `"wrapperLifetime"` object of the app's `package.json`, the same key +iOS reads: + +```json +{ "wrapperLifetime": { "mode": "resurrecting", "scope": "extended" } } +``` + +A value that is not an object, or an unknown `mode` or `scope`, logs a warning +and keeps the default. `"rooted"` is iOS-only: it reads native retain counts, +which Java does not have. + +`"resurrecting"` (the default) keeps a collected wrapper while Java may still +hold its object. The first collection resurrects it and makes the Java side +weak; a later collection releases the wrapper only once Java has collected the +object. The JS properties of a wrapper whose object Java holds therefore +survive, but the Java objects those properties reference were made weak in +the same collection, and Java may collect them under the wrapper: touching one +then throws `Attempt to use cleared object reference`. + +`getWrapperLifetimeStats()` returns counters for the calling isolate, kept in +every build on cold paths only: + +| counter | counts | +|---|---| +| `resurrections` | finalizer callbacks that kept a collected wrapper until the Java side says whether its object is still alive | +| `weakened` | Java objects held weakly because their wrapper was collected | +| `collected` | wrappers released because Java had collected their object | +| `releasedExplicitly` | links released through `__releaseNativeCounterpart` | +| `releasedAccesses` | times JS used a wrapper whose Java object Java had already collected | + Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those values are read once from nativescript.config / package.json the first time diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index a89f86029..87b389ffc 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -60,6 +60,7 @@ require("./tests/dispatchCallbacksOnUiThreadTests"); require("./tests/stringConversionTests"); require("./tests/testsForTypescript"); require("./tests/testGC"); +require("./tests/testWrapperLifetime"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); diff --git a/test-app/app/src/main/assets/app/tests/testNsRuntime.js b/test-app/app/src/main/assets/app/tests/testNsRuntime.js index 3542f0622..cc3ef6da4 100644 --- a/test-app/app/src/main/assets/app/tests/testNsRuntime.js +++ b/test-app/app/src/main/assets/app/tests/testNsRuntime.js @@ -11,7 +11,7 @@ describe("ns:runtime", function () { // The export set is public API, declared alongside docs/ns-builtin-modules.md // — all of them change together. it("exposes exactly the declared surface", function () { - expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "setConfig"]); + expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperLifetimeStats", "setConfig"]); }); it("rejects unknown keys", function () { diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js new file mode 100644 index 000000000..09601afa3 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -0,0 +1,97 @@ +describe("Wrapper lifetime", function () { + var runtime = require("ns:runtime"); + var mode = runtime.getConfig("wrapperLifetimeMode"); + var scope = runtime.getConfig("wrapperLifetimeScope"); + var Holder = com.tns.tests.WrapperHolder; + + function collectJava() { + for (var i = 0; i < 3; i++) { + java.lang.Runtime.getRuntime().gc(); + java.lang.System.runFinalization(); + } + } + + // A JS->Java call: settles the wrappers the last collection queued. + function crossIntoJava() { + java.lang.System.nanoTime(); + } + + afterEach(function () { + Holder.held = null; + }); + + it("reports the configured mode and scope (" + mode + "/" + scope + ")", function () { + expect(["resurrecting"]).toContain(mode); + expect(["extended", "all"]).toContain(scope); + }); + + it("rejects writes to the mode and scope", function () { + expect(function () { + runtime.setConfig("wrapperLifetimeMode", "resurrecting"); + }).toThrowError(TypeError, "'wrapperLifetimeMode' is read-only; set \"wrapperLifetime\" in the app config"); + expect(function () { + runtime.setConfig("wrapperLifetimeScope", "all"); + }).toThrowError(TypeError, "'wrapperLifetimeScope' is read-only; set \"wrapperLifetime\" in the app config"); + }); + + it("exposes numeric counters", function () { + var stats = runtime.getWrapperLifetimeStats(); + expect(Object.keys(stats).sort()).toEqual( + ["collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); + Object.keys(stats).forEach(function (key) { + expect(typeof stats[key]).toBe("number"); + }); + expect(runtime.getWrapperLifetimeStats()).not.toBe(stats); + }); + + it("counts explicit releases", function () { + var before = runtime.getWrapperLifetimeStats().releasedExplicitly; + __releaseNativeCounterpart(new java.lang.Object()); + expect(runtime.getWrapperLifetimeStats().releasedExplicitly).toBe(before + 1); + }); + + if (mode !== "resurrecting") { + return; + } + + it("keeps a collected wrapper until Java has collected its object", function () { + var before = runtime.getWrapperLifetimeStats(); + (function () { + for (var i = 0; i < 20; i++) { + new java.lang.Object(); + } + })(); + gc(); + crossIntoJava(); + var weakened = runtime.getWrapperLifetimeStats(); + expect(weakened.resurrections).toBeGreaterThan(before.resurrections); + expect(weakened.weakened).toBeGreaterThan(before.weakened); + + collectJava(); + gc(); + crossIntoJava(); + expect(runtime.getWrapperLifetimeStats().collected).toBeGreaterThan(before.collected); + }); + + // The shape the "canary" mode removes: a wrapper resurrected because Java holds its + // object keeps its JS properties, but the Java objects those properties reference + // were weakened in the same collection, and Java is free to collect them. + it("lets Java collect an object only a resurrected wrapper's JS property references", function () { + (function () { + var holder = new java.lang.StringBuilder("holder"); + holder.child = new java.lang.StringBuilder("child"); + Holder.held = holder; + })(); + gc(); + crossIntoJava(); + collectJava(); + + var holder = Holder.held; + expect(holder.toString()).toBe("holder"); + var before = runtime.getWrapperLifetimeStats().releasedAccesses; + expect(function () { + holder.child.toString(); + }).toThrowError(/Attempt to use cleared object reference/); + expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before + 1); + }); +}); diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 8f64c421d..28b8eaa4d 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -231,6 +231,7 @@ add_library( src/main/cpp/V8GlobalHelpers.cpp src/main/cpp/V8StringConstants.cpp src/main/cpp/WeakRef.cpp + src/main/cpp/WrapperLifetime.cpp src/main/cpp/WorkerEvents.cpp src/main/cpp/WorkerWrapper.cpp src/main/cpp/Timers.cpp diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 997adcfd7..95a380cda 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -17,6 +17,7 @@ #include "StructuredSerialization.h" #include "TextEncoding.h" #include "TraceLog.h" +#include "WrapperLifetime.h" #include "console/Console.h" #include "robin_hood.h" @@ -79,6 +80,8 @@ constexpr Registration kRegistry[] = { }; constexpr const char* kDebugKey = "debug"; +constexpr const char* kWrapperLifetimeModeKey = "wrapperLifetimeMode"; +constexpr const char* kWrapperLifetimeScopeKey = "wrapperLifetimeScope"; void ThrowTypeError(Isolate* isolate, const std::string& message) { isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String(isolate, message))); @@ -126,6 +129,10 @@ void SetConfigCallback(const FunctionCallbackInfo& info) { } return; } + if (key == kWrapperLifetimeModeKey || key == kWrapperLifetimeScopeKey) { + ThrowTypeError(isolate, "'" + key + "' is read-only; set \"wrapperLifetime\" in the app config"); + return; + } ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'"); } @@ -141,9 +148,40 @@ void GetConfigCallback(const FunctionCallbackInfo& info) { ArgConverter::ConvertToV8String(isolate, tns::EnabledLogCategoryNames())); return; } + if (key == kWrapperLifetimeModeKey) { + info.GetReturnValue().Set(ArgConverter::ConvertToV8String( + isolate, WrapperLifetimeModeName(GetWrapperLifetimeMode()))); + return; + } + if (key == kWrapperLifetimeScopeKey) { + info.GetReturnValue().Set(ArgConverter::ConvertToV8String( + isolate, WrapperLifetimeScopeName(GetWrapperLifetimeScope()))); + return; + } ThrowTypeError(isolate, "Unknown runtime config key: '" + key + "'"); } +void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + ObjectManager* objectManager = Runtime::GetObjectManager(isolate); + if (objectManager == nullptr) { + return; + } + const WrapperLifetimeStats& stats = objectManager->GetLifetimeStats(); + Local context = isolate->GetCurrentContext(); + Local result = Object::New(isolate); + auto set = [&](const char* name, uint64_t value) { + (void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name), + Number::New(isolate, static_cast(value))); + }; + set("resurrections", stats.resurrections); + set("weakened", stats.weakened); + set("collected", stats.collected); + set("releasedExplicitly", stats.releasedExplicitly); + set("releasedAccesses", stats.releasedAccesses); + info.GetReturnValue().Set(result); +} + const Registration* Find(const std::string& specifier) { for (const Registration& registration : kRegistry) { if (specifier == registration.specifier) { @@ -217,9 +255,11 @@ MaybeLocal NsModuleBinding(Local context) { MaybeLocal NsRuntimeBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - Local setConfig, getConfig, escapeException; + Local setConfig, getConfig, escapeException, getWrapperLifetimeStats; if (!v8::Function::New(context, SetConfigCallback).ToLocal(&setConfig) || !v8::Function::New(context, GetConfigCallback).ToLocal(&getConfig) || + !v8::Function::New(context, GetWrapperLifetimeStatsCallback) + .ToLocal(&getWrapperLifetimeStats) || !Interop::CreateEscapeException(context).ToLocal(&escapeException) || !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "setConfig"), setConfig) .FromMaybe(false) || @@ -227,6 +267,9 @@ MaybeLocal NsRuntimeBinding(Local context) { .FromMaybe(false) || !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "escapeException"), escapeException) + .FromMaybe(false) || + !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "getWrapperLifetimeStats"), + getWrapperLifetimeStats) .FromMaybe(false)) { return MaybeLocal(); } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 71395e499..f2e3d0aea 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -106,30 +106,36 @@ void ObjectManager::Init(Isolate* isolate) { JniLocalRef ObjectManager::GetJavaObjectByJsObject( const Local& object) { JSInstanceInfo* jsInstanceInfo = GetJSInstanceInfo(object); - - if (jsInstanceInfo != nullptr) { - jweak existingObject; - try { - existingObject = GetJavaObjectByID(jsInstanceInfo->javaObjectID); - } catch (const NativeScriptException& e) { - // this captures usually the error - auto className = GetClassName(jsInstanceInfo->objectClazz); - throw NativeScriptException("Failed to get Java object by ID. id=" + - std::to_string(jsInstanceInfo->javaObjectID) + - ", class=" + className + ". " + - e.GetErrorMessage()); - } - if (m_useGlobalRefs) { - JniLocalRef javaObject(existingObject, true); - return javaObject; - } else { - JEnv env; - JniLocalRef javaObject(env.NewLocalRef(existingObject)); - return javaObject; - } + if (jsInstanceInfo == nullptr) { + return JniLocalRef(); + } + try { + return JavaObjectOf(jsInstanceInfo); + } catch (const NativeScriptException&) { + m_lifetimeStats.releasedAccesses++; + throw; } +} - return JniLocalRef(); +JniLocalRef ObjectManager::JavaObjectOf(JSInstanceInfo* jsInstanceInfo) { + jweak existingObject; + try { + existingObject = GetJavaObjectByID(jsInstanceInfo->javaObjectID); + } catch (const NativeScriptException& e) { + // this captures usually the error + auto className = GetClassName(jsInstanceInfo->objectClazz); + throw NativeScriptException("Failed to get Java object by ID. id=" + + std::to_string(jsInstanceInfo->javaObjectID) + + ", class=" + className + ". " + + e.GetErrorMessage()); + } + if (m_useGlobalRefs) { + JniLocalRef javaObject(existingObject, true); + return javaObject; + } + JEnv env; + JniLocalRef javaObject(env.NewLocalRef(existingObject)); + return javaObject; } JniLocalRef ObjectManager::GetLiveJavaObjectByJsObject( @@ -144,7 +150,7 @@ JniLocalRef ObjectManager::GetLiveJavaObjectByJsObject( // leave it pointing at memory nothing keeps alive any more. JniLocalRef javaObject; try { - javaObject = GetJavaObjectByJsObject(object); + javaObject = JavaObjectOf(jsInstanceInfo); } catch (const NativeScriptException&) { if (!ReleaseIfCollected(javaObjectID)) { throw; @@ -589,6 +595,7 @@ void ObjectManager::JSObjectFinalizer(Isolate* isolate, // Kept alive until the batch has asked the Java side whether it may die. po->SetWeak(callbackState, JSObjectFinalizerStatic, WeakCallbackType::kFinalizer); + m_lifetimeStats.resurrections++; if (callbackState->queued) { // Collected again before the flush, so whatever handed it back has let go. @@ -746,6 +753,7 @@ void ObjectManager::FlushFinalizedBatch() { state->queued = false; if (weakened) { state->javaWeakened = true; + m_lifetimeStats.weakened++; } } }; @@ -758,6 +766,7 @@ void ObjectManager::ReleaseCollectedWrapper(int javaObjectID) { if (state == nullptr) { return; } + m_lifetimeStats.collected++; Persistent* po = state->target; if (state->linked) { auto object = po->Get(m_isolate); @@ -901,6 +910,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { AssertIsolateLocked(); env.CallVoidMethod(m_javaRuntimeObject, RELEASE_NATIVE_INSTANCE_METHOD_ID, javaObjectID); + m_lifetimeStats.releasedExplicitly++; // The registration outlives the link: it is dropped by the finalizer once // the wrapper is collected. diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 469a18898..f6bbba666 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -14,6 +14,7 @@ #include "LRUCache.h" #include "NativeScriptAssert.h" #include "ObjectIdIndex.h" +#include "WrapperLifetime.h" #include "v8.h" namespace tns { @@ -157,6 +158,8 @@ class ObjectManager { enum class MetadataNodeKeys { JsInfo, CallSuper, Metadata, END }; + const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; } + private: static void InitializeJNI(); @@ -197,6 +200,11 @@ class ObjectManager { // The linked state of object, or null. JSInstanceInfo* GetJSInstanceInfo(const v8::Local& object); + // The linked Java object of jsInstanceInfo; throws if Java has collected it. + JniLocalRef JavaObjectOf(JSInstanceInfo* jsInstanceInfo); + + WrapperLifetimeStats m_lifetimeStats; + JSInstanceInfo* GetJSInstanceInfoFromRuntimeObject( const v8::Local& object); diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 5aa20ac59..4200895b5 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -1,4 +1,5 @@ #include "Runtime.h" +#include "WrapperLifetime.h" #include @@ -263,6 +264,7 @@ void Runtime::Init(JNIEnv* env, jstring filesPath, jstring nativeLibDir, m_uncaughtErrorPolicy = options.uncaughtErrorPolicy == "throw" ? UncaughtErrorPolicy::Throw : UncaughtErrorPolicy::Report; + ConfigureWrapperLifetime(options.wrapperLifetimeMode, options.wrapperLifetimeScope); DEBUG_WRITE("Initializing Telerik NativeScript"); diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 77913df69..762bfc76c 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -141,6 +141,8 @@ class Runtime { std::string profilerOutputDir; bool discardUncaughtJsExceptions; std::string uncaughtErrorPolicy; + std::string wrapperLifetimeMode; + std::string wrapperLifetimeScope; }; static void Init(JNIEnv* _env, jobject obj, int runtimeId, jstring filesPath, jstring nativeLibsDir, jboolean verboseLoggingEnabled, jboolean isDebuggable, jstring packageName, const StartupOptions& options, jstring callingDir, int maxLogcatObjectSize, diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.cpp b/test-app/runtime/src/main/cpp/WrapperLifetime.cpp new file mode 100644 index 000000000..ebb340e7b --- /dev/null +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.cpp @@ -0,0 +1,30 @@ +#include "WrapperLifetime.h" + +#include + +namespace tns { + +const char* WrapperLifetimeModeName(WrapperLifetimeMode mode) { + switch (mode) { + case WrapperLifetimeMode::kResurrecting: + return "resurrecting"; + } + return "resurrecting"; +} + +const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope) { + return scope == WrapperLifetimeScope::kAll ? "all" : "extended"; +} + +void ConfigureWrapperLifetime(const std::string& mode, const std::string& scope) { + static std::once_flag once; + std::call_once(once, [&]() { + if (mode == WrapperLifetimeModeName(WrapperLifetimeMode::kResurrecting)) { + detail::wrapperLifetimeMode = WrapperLifetimeMode::kResurrecting; + } + detail::wrapperLifetimeScope = + scope == "all" ? WrapperLifetimeScope::kAll : WrapperLifetimeScope::kExtended; + }); +} + +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.h b/test-app/runtime/src/main/cpp/WrapperLifetime.h new file mode 100644 index 000000000..5d2b2a60a --- /dev/null +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -0,0 +1,60 @@ +#ifndef WRAPPERLIFETIME_H_ +#define WRAPPERLIFETIME_H_ + +#include +#include + +namespace tns { + +// How the JS wrappers of Java objects live. Process-wide: read from the app +// config "wrapperLifetime": { "mode": ..., "scope": ... } by the first runtime +// that starts, before any wrapper exists, and fixed for the process. +enum class WrapperLifetimeMode { + // kFinalizer callbacks keep a collected wrapper while Java may still hold + // its object: the Java side is made weak, and the wrapper is released only + // once a later collection finds the Java object gone (ObjectManager). + kResurrecting, +}; + +enum class WrapperLifetimeScope { + kExtended, + kAll, +}; + +namespace detail { +inline WrapperLifetimeMode wrapperLifetimeMode = WrapperLifetimeMode::kResurrecting; +inline WrapperLifetimeScope wrapperLifetimeScope = WrapperLifetimeScope::kExtended; +} // namespace detail + +inline WrapperLifetimeMode GetWrapperLifetimeMode() { + return detail::wrapperLifetimeMode; +} +inline WrapperLifetimeScope GetWrapperLifetimeScope() { + return detail::wrapperLifetimeScope; +} + +const char* WrapperLifetimeModeName(WrapperLifetimeMode mode); +const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope); + +// com.tns.AppConfig validated both names. Only the first call takes effect. +void ConfigureWrapperLifetime(const std::string& mode, const std::string& scope); + +// Per-runtime counters (ObjectManager), returned by ns:runtime's +// getWrapperLifetimeStats(). Touched only under the isolate's Locker. +struct WrapperLifetimeStats { + // Finalizer callbacks that kept a collected wrapper until the Java side + // says whether its object is still alive. + uint64_t resurrections = 0; + // Java objects held weakly because their wrapper was collected. + uint64_t weakened = 0; + // Wrappers released because Java had collected their object. + uint64_t collected = 0; + // Links released through __releaseNativeCounterpart. + uint64_t releasedExplicitly = 0; + // Times JS used a wrapper whose Java object was already collected. + uint64_t releasedAccesses = 0; +}; + +} // namespace tns + +#endif /* WRAPPERLIFETIME_H_ */ diff --git a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index 8358e8812..df36a92ef 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -95,7 +95,7 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_setManualInstrumentationModeLegac setManualInstrumentationModeFast_impl(_env, clazz, mode); } -extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jobject obj, jint runtimeId, jstring filesPath, jstring nativeLibDir, jboolean verboseLoggingEnabled, jboolean isDebuggable, jstring packageName, jstring v8Flags, jboolean codeCache, jstring profilerOutputDir, jboolean discardUncaughtJsExceptions, jstring uncaughtErrorPolicy, jstring callingDir, jint maxLogcatObjectSize, jboolean forceLog) { +extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jobject obj, jint runtimeId, jstring filesPath, jstring nativeLibDir, jboolean verboseLoggingEnabled, jboolean isDebuggable, jstring packageName, jstring v8Flags, jboolean codeCache, jstring profilerOutputDir, jboolean discardUncaughtJsExceptions, jstring uncaughtErrorPolicy, jstring wrapperLifetimeMode, jstring wrapperLifetimeScope, jstring callingDir, jint maxLogcatObjectSize, jboolean forceLog) { JEnv::EntryScope envScope(_env); try { Runtime::StartupOptions options{ @@ -103,7 +103,9 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jo codeCache == JNI_TRUE, ArgConverter::jstringToString(profilerOutputDir), discardUncaughtJsExceptions == JNI_TRUE, - ArgConverter::jstringToString(uncaughtErrorPolicy)}; + ArgConverter::jstringToString(uncaughtErrorPolicy), + ArgConverter::jstringToString(wrapperLifetimeMode), + ArgConverter::jstringToString(wrapperLifetimeScope)}; Runtime::Init(_env, obj, runtimeId, filesPath, nativeLibDir, verboseLoggingEnabled, isDebuggable, packageName, options, callingDir, maxLogcatObjectSize, forceLog); } catch (NativeScriptException& e) { e.ReThrowToJava(); diff --git a/test-app/runtime/src/main/cpp/js/ns-runtime.js b/test-app/runtime/src/main/cpp/js/ns-runtime.js index b7e678bd4..b72da8630 100644 --- a/test-app/runtime/src/main/cpp/js/ns-runtime.js +++ b/test-app/runtime/src/main/cpp/js/ns-runtime.js @@ -6,10 +6,11 @@ // per-isolate) are defined and validated on the native side, so this file // stays a thin, frozen surface. -const { setConfig, getConfig, escapeException } = binding; +const { setConfig, getConfig, escapeException, getWrapperLifetimeStats } = binding; const { ObjectFreeze } = primordials; exports.setConfig = setConfig; exports.getConfig = getConfig; exports.escapeException = escapeException; +exports.getWrapperLifetimeStats = getWrapperLifetimeStats; ObjectFreeze(exports); diff --git a/test-app/runtime/src/main/java/com/tns/AppConfig.java b/test-app/runtime/src/main/java/com/tns/AppConfig.java index 3ec37c7e1..149501a07 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -24,7 +24,9 @@ protected enum KnownKeys { EnableLineBreakpoins("enableLineBreakpoints", false), EnableMultithreadedJavascript("enableMultithreadedJavascript", false), UncaughtErrorPolicy("uncaughtErrorPolicy", "report"), - InterfaceProxies("interfaceProxies", false); + InterfaceProxies("interfaceProxies", false), + WrapperLifetimeMode("mode", "resurrecting"), + WrapperLifetimeScope("scope", "extended"); private final String name; private final Object defaultValue; @@ -44,6 +46,8 @@ public Object getDefaultValue() { private final static String AndroidKey = "android"; private final static String SecurityKey = "security"; + // Top level, like iOS, so one app config selects the mode on both platforms. + private final static String WrapperLifetimeKey = "wrapperLifetime"; private final Object[] values; @@ -104,6 +108,9 @@ public AppConfig(File appDir) { Log.w("JS", String.format("Unknown uncaughtErrorPolicy \"%s\" - expected \"report\" or \"throw\". The default \"report\" will be used.", policy)); } } + if (rootObject.has(WrapperLifetimeKey)) { + readWrapperLifetime(rootObject.opt(WrapperLifetimeKey)); + } if (rootObject.has(AndroidKey)) { JSONObject androidObject = rootObject.getJSONObject(AndroidKey); if (androidObject.has(KnownKeys.V8FlagsKey.getName())) { @@ -155,6 +162,40 @@ public AppConfig(File appDir) { } } + private void readWrapperLifetime(Object config) { + if (!(config instanceof JSONObject)) { + Log.w("JS", "wrapperLifetime must be an object; using the defaults."); + return; + } + JSONObject object = (JSONObject) config; + Object mode = object.opt(KnownKeys.WrapperLifetimeMode.getName()); + if (mode != null) { + if ("resurrecting".equals(mode)) { + values[KnownKeys.WrapperLifetimeMode.ordinal()] = mode; + } else if ("rooted".equals(mode)) { + Log.w("JS", "wrapperLifetime mode \"rooted\" reads native retain counts and is iOS-only; using \"resurrecting\"."); + } else { + Log.w("JS", String.format("Unknown wrapperLifetime mode %s; using \"resurrecting\".", JSONObject.quote(String.valueOf(mode)))); + } + } + Object scope = object.opt(KnownKeys.WrapperLifetimeScope.getName()); + if (scope != null) { + if ("extended".equals(scope) || "all".equals(scope)) { + values[KnownKeys.WrapperLifetimeScope.ordinal()] = scope; + } else { + Log.w("JS", String.format("Unknown wrapperLifetime scope %s; using \"extended\".", JSONObject.quote(String.valueOf(scope)))); + } + } + } + + public String getWrapperLifetimeMode() { + return (String)values[KnownKeys.WrapperLifetimeMode.ordinal()]; + } + + public String getWrapperLifetimeScope() { + return (String)values[KnownKeys.WrapperLifetimeScope.ordinal()]; + } + public String getV8Flags() { return (String)values[KnownKeys.V8FlagsKey.ordinal()]; } diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index c9e5ea27f..28ea30570 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -39,6 +39,7 @@ public class Runtime { private native void initNativeScript(int runtimeId, String filesPath, String nativeLibDir, boolean verboseLoggingEnabled, boolean isDebuggable, String packageName, String v8Flags, boolean codeCache, String profilerOutputDir, boolean discardUncaughtJsExceptions, String uncaughtErrorPolicy, + String wrapperLifetimeMode, String wrapperLifetimeScope, String callingDir, int maxLogcatObjectSize, boolean forceLog); private native void runModule(int runtimeId, String filePath) throws NativeScriptException; @@ -809,6 +810,7 @@ private void init(Logger logger, String appName, String nativeLibDir, File rootD initNativeScript(getRuntimeId(), Module.getApplicationFilesPath(), nativeLibDir, logger.isEnabled(), isDebuggable, appName, appConfig.getV8Flags(), appConfig.getCodeCache(), appConfig.getProfilerOutputDir(), appConfig.getDiscardUncaughtJsExceptions(), appConfig.getUncaughtErrorPolicy(), + appConfig.getWrapperLifetimeMode(), appConfig.getWrapperLifetimeScope(), callingJsDir, appConfig.getMaxLogcatObjectSize(), forceConsoleLog); if (logger.isEnabled()) { From d9b11ef2f9acca7eb093fc5f641869668f1e50ea Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 13:54:31 -0300 Subject: [PATCH 2/6] feat(runtime): count method calls on released wrappers as released accesses --- docs/ns-builtin-modules.md | 2 +- .../main/assets/app/tests/testWrapperLifetime.js | 13 +++++++++---- test-app/runtime/src/main/cpp/CallbackHandlers.cpp | 1 + test-app/runtime/src/main/cpp/ObjectManager.h | 3 +++ test-app/runtime/src/main/cpp/WrapperLifetime.h | 3 ++- 5 files changed, 16 insertions(+), 6 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index dd67f9612..304c59c19 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -184,7 +184,7 @@ every build on cold paths only: | `weakened` | Java objects held weakly because their wrapper was collected | | `collected` | wrappers released because Java had collected their object | | `releasedExplicitly` | links released through `__releaseNativeCounterpart` | -| `releasedAccesses` | times JS used a wrapper whose Java object Java had already collected | +| `releasedAccesses` | times JS used a wrapper whose Java object Java had already collected, or called a method on a wrapper whose link was released | Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js index 09601afa3..e7504d39f 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -44,10 +44,15 @@ describe("Wrapper lifetime", function () { expect(runtime.getWrapperLifetimeStats()).not.toBe(stats); }); - it("counts explicit releases", function () { - var before = runtime.getWrapperLifetimeStats().releasedExplicitly; - __releaseNativeCounterpart(new java.lang.Object()); - expect(runtime.getWrapperLifetimeStats().releasedExplicitly).toBe(before + 1); + it("counts explicit releases, and calls on a released wrapper", function () { + var before = runtime.getWrapperLifetimeStats(); + var released = new java.lang.Object(); + __releaseNativeCounterpart(released); + expect(runtime.getWrapperLifetimeStats().releasedExplicitly).toBe(before.releasedExplicitly + 1); + expect(function () { + released.hashCode(); + }).toThrowError(/no longer has available Java instance counterpart/); + expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1); }); if (mode !== "resurrecting") { diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index ae99e715d..d47dba3f8 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -528,6 +528,7 @@ void CallbackHandlers::CallJavaMethod(const Local &caller, const string ss << "No java object found on which to call \"" << methodName << "\" method. It is possible your Javascript object is not linked with the corresponding Java class. Try passing context(this) to the constructor function."; } else { + objectManager->CountReleasedAccess(); ss << "Failed calling " << methodName << " on a " << className << " instance. The JavaScript instance no longer has available Java instance counterpart."; } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index f6bbba666..fbf5adeef 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -160,6 +160,9 @@ class ObjectManager { const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; } + // JS called a method on a wrapper whose link is gone. + void CountReleasedAccess() { m_lifetimeStats.releasedAccesses++; } + private: static void InitializeJNI(); diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.h b/test-app/runtime/src/main/cpp/WrapperLifetime.h index 5d2b2a60a..3ad20078c 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -51,7 +51,8 @@ struct WrapperLifetimeStats { uint64_t collected = 0; // Links released through __releaseNativeCounterpart. uint64_t releasedExplicitly = 0; - // Times JS used a wrapper whose Java object was already collected. + // Times JS used a wrapper whose Java object was already collected, or + // called a method on one whose link was released. uint64_t releasedAccesses = 0; }; From 135bb9f2ed9cd28b9e517c4fec440f29462c18ae Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 18:58:57 -0300 Subject: [PATCH 3/6] fix(runtime): count only released wrappers, and report counters as own properties releasedAccesses counted a method call on any object without a Java link, such as a plain object a Java method was called on, not only a wrapper whose link was released. getWrapperLifetimeStats() built its result with Set, so a setter on Object.prototype could swallow a counter; it defines own data properties now. --- .../assets/app/tests/testWrapperLifetime.js | 20 +++++++++++++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 7 ++++++- .../runtime/src/main/cpp/NsBuiltinModules.cpp | 4 ++-- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js index e7504d39f..c346be2eb 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -53,6 +53,26 @@ describe("Wrapper lifetime", function () { released.hashCode(); }).toThrowError(/no longer has available Java instance counterpart/); expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1); + + // Not a wrapper at all: not a released access. + expect(function () { + new java.lang.Object().hashCode.call({}); + }).toThrow(); + expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1); + }); + + it("reports counters as own properties whatever Object.prototype defines", function () { + Object.defineProperty(Object.prototype, "collected", { + set: function () {}, + configurable: true + }); + try { + var stats = runtime.getWrapperLifetimeStats(); + expect(Object.prototype.hasOwnProperty.call(stats, "collected")).toBe(true); + expect(typeof stats.collected).toBe("number"); + } finally { + delete Object.prototype.collected; + } }); if (mode !== "resurrecting") { diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index d47dba3f8..7811ab8b8 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -528,7 +528,12 @@ void CallbackHandlers::CallJavaMethod(const Local &caller, const string ss << "No java object found on which to call \"" << methodName << "\" method. It is possible your Javascript object is not linked with the corresponding Java class. Try passing context(this) to the constructor function."; } else { - objectManager->CountReleasedAccess(); + // A wrapper whose link is gone, not any object a method was called on. + auto receiver = ObjectManager::UnwrapProxy(caller); + if (receiver->IsObject() && + ObjectManager::IsJsRuntimeObject(receiver.As())) { + objectManager->CountReleasedAccess(); + } ss << "Failed calling " << methodName << " on a " << className << " instance. The JavaScript instance no longer has available Java instance counterpart."; } diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 95a380cda..490fc5620 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -171,8 +171,8 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { Local context = isolate->GetCurrentContext(); Local result = Object::New(isolate); auto set = [&](const char* name, uint64_t value) { - (void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name), - Number::New(isolate, static_cast(value))); + (void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name), + Number::New(isolate, static_cast(value))); }; set("resurrections", stats.resurrections); set("weakened", stats.weakened); From 6da836160d4c17c0fa002db80d44d06e3ed326d5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 19:49:08 -0300 Subject: [PATCH 4/6] fix(runtime): count every use of a wrapper whose link is gone releasedAccesses only counted method calls on a released wrapper: field accesses and arguments failed before reaching the counter. A released link now leaves null in JsInfo, distinct from the undefined of a link never made, so GetJavaObjectByJsObject counts any lookup of such a wrapper. Array buffers and typed arrays no longer count. --- docs/ns-builtin-modules.md | 2 +- .../assets/app/tests/testWrapperLifetime.js | 23 ++++++++++++-- .../runtime/src/main/cpp/CallbackHandlers.cpp | 6 ---- .../runtime/src/main/cpp/ObjectManager.cpp | 30 +++++++++++++++---- test-app/runtime/src/main/cpp/ObjectManager.h | 10 +++++-- 5 files changed, 54 insertions(+), 17 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 304c59c19..57dd6e1a6 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -184,7 +184,7 @@ every build on cold paths only: | `weakened` | Java objects held weakly because their wrapper was collected | | `collected` | wrappers released because Java had collected their object | | `releasedExplicitly` | links released through `__releaseNativeCounterpart` | -| `releasedAccesses` | times JS used a wrapper whose Java object Java had already collected, or called a method on a wrapper whose link was released | +| `releasedAccesses` | lookups of the Java object of a wrapper whose link was released or whose Java object Java had already collected: calling its methods, using its fields or passing it to Java. Resolving an overloaded method looks its arguments up too, so one call can count more than once | Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js index c346be2eb..cfb068329 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -55,10 +55,29 @@ describe("Wrapper lifetime", function () { expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1); // Not a wrapper at all: not a released access. + var hashCode = new java.lang.Object().hashCode; + [{}, new ArrayBuffer(8), new Int8Array(8)].forEach(function (receiver) { + expect(function () { + hashCode.call(receiver); + }).toThrow(); + }); + expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1); + }); + + it("counts field accesses on, and arguments of, a released wrapper", function () { + var point = new android.graphics.Point(1, 2); + __releaseNativeCounterpart(point); + var before = runtime.getWrapperLifetimeStats().releasedAccesses; expect(function () { - new java.lang.Object().hashCode.call({}); + return point.x; + }).toThrowError(/no corresponding Java object/); + expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before + 1); + + // Resolving an overload looks the argument up too, so one call can count more than once. + expect(function () { + java.lang.String.valueOf(point); }).toThrow(); - expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBe(before.releasedAccesses + 1); + expect(runtime.getWrapperLifetimeStats().releasedAccesses).toBeGreaterThan(before + 1); }); it("reports counters as own properties whatever Object.prototype defines", function () { diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 7811ab8b8..ae99e715d 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -528,12 +528,6 @@ void CallbackHandlers::CallJavaMethod(const Local &caller, const string ss << "No java object found on which to call \"" << methodName << "\" method. It is possible your Javascript object is not linked with the corresponding Java class. Try passing context(this) to the constructor function."; } else { - // A wrapper whose link is gone, not any object a method was called on. - auto receiver = ObjectManager::UnwrapProxy(caller); - if (receiver->IsObject() && - ObjectManager::IsJsRuntimeObject(receiver.As())) { - objectManager->CountReleasedAccess(); - } ss << "Failed calling " << methodName << " on a " << className << " instance. The JavaScript instance no longer has available Java instance counterpart."; } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index f2e3d0aea..dddf212fe 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -107,6 +107,9 @@ JniLocalRef ObjectManager::GetJavaObjectByJsObject( const Local& object) { JSInstanceInfo* jsInstanceInfo = GetJSInstanceInfo(object); if (jsInstanceInfo == nullptr) { + if (IsReleasedWrapper(object)) { + m_lifetimeStats.releasedAccesses++; + } return JniLocalRef(); } try { @@ -292,6 +295,25 @@ bool ObjectManager::IsJsRuntimeObject(const v8::Local& object) { internalFieldCount == V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT; } +void ObjectManager::MarkLinkReleased(const Local& object) { + object->SetInternalField(static_cast(MetadataNodeKeys::JsInfo), Null(m_isolate)); +} + +bool ObjectManager::IsReleasedWrapper(const Local& object) { + auto target = UnwrapProxy(object); + if (!target->IsObject() || !HasMetadataField(target.As())) { + return false; + } + auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); + auto field = target.As()->GetInternalField(jsInfoIdx).As(); + if (!field->IsUndefined()) { + return field->IsNull(); + } + auto prototype = target.As()->GetPrototype(); + return prototype->IsObject() && HasMetadataField(prototype.As()) && + prototype.As()->GetInternalField(jsInfoIdx).As()->IsNull(); +} + jweak ObjectManager::GetJavaObjectByID(uint32_t javaObjectID) { jweak obj = m_cache(javaObjectID); @@ -769,8 +791,7 @@ void ObjectManager::ReleaseCollectedWrapper(int javaObjectID) { m_lifetimeStats.collected++; Persistent* po = state->target; if (state->linked) { - auto object = po->Get(m_isolate); - object->SetInternalField(static_cast(MetadataNodeKeys::JsInfo), Undefined(m_isolate)); + MarkLinkReleased(po->Get(m_isolate)); } m_idToObject.Erase(javaObjectID); po->Reset(); @@ -903,7 +924,6 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { throw NativeScriptException("Trying to release a non native object!"); } - auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); auto javaObjectID = LinkedIdOf(owner); JEnv env; @@ -919,7 +939,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { state->linked = false; } - owner->SetInternalField(jsInfoIdx, Undefined(m_isolate)); + MarkLinkReleased(owner); // Every alias of the link is cleared with it. Local aliasesValue; @@ -931,7 +951,7 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { Local alias; if (aliases->Get(context, i).ToLocal(&alias) && alias->IsObject() && IsJsRuntimeObject(alias.As())) { - alias.As()->SetInternalField(jsInfoIdx, Undefined(m_isolate)); + MarkLinkReleased(alias.As()); } } } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index fbf5adeef..5a2f03a4a 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -131,6 +131,10 @@ class ObjectManager { return LinkedIdOf(object) != -1; } + // Whether object, seen through any Proxy and the TypeScript layout, is a wrapper whose + // link was released or whose Java object was collected. + static bool IsReleasedWrapper(const v8::Local& object); + /* * The innermost target of a Proxy chain; any other value is returned as is. * A revoked Proxy anywhere in the chain yields null. Internal fields and @@ -160,9 +164,6 @@ class ObjectManager { const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; } - // JS called a method on a wrapper whose link is gone. - void CountReleasedAccess() { m_lifetimeStats.releasedAccesses++; } - private: static void InitializeJNI(); @@ -261,6 +262,9 @@ class ObjectManager { void ReleaseCollectedWrapper(int javaObjectID); + // A link that is gone leaves null in JsInfo; a link never made leaves undefined. + void MarkLinkReleased(const v8::Local& object); + // Drops id's registrations on both sides if Java has collected its object. bool ReleaseIfCollected(int javaObjectID); From 90741e134db19d264b1737bc1b31e117c1bc0662 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:10:54 -0300 Subject: [PATCH 5/6] fix(runtime): read wrapperLifetime even when another config key is malformed AppConfig reads the whole package.json inside one try, so a malformed key read earlier (a non-object "security", a non-boolean "discardUncaughtJsExceptions") ended the read before "wrapperLifetime" and left the mode at its default without any log. wrapperLifetime is now read first; its reader never throws. A read that stops early now logs a warning in every build instead of printing the stack trace only in debuggable ones. getWrapperLifetimeStats() also loses a null check that could never hold: Runtime::GetObjectManager throws rather than returning null. --- test-app/runtime/src/main/cpp/NsBuiltinModules.cpp | 6 +----- test-app/runtime/src/main/java/com/tns/AppConfig.java | 10 +++++++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 490fc5620..247d5eee6 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -163,11 +163,7 @@ void GetConfigCallback(const FunctionCallbackInfo& info) { void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - ObjectManager* objectManager = Runtime::GetObjectManager(isolate); - if (objectManager == nullptr) { - return; - } - const WrapperLifetimeStats& stats = objectManager->GetLifetimeStats(); + const WrapperLifetimeStats& stats = Runtime::GetObjectManager(isolate)->GetLifetimeStats(); Local context = isolate->GetCurrentContext(); Local result = Object::New(isolate); auto set = [&](const char* name, uint64_t value) { diff --git a/test-app/runtime/src/main/java/com/tns/AppConfig.java b/test-app/runtime/src/main/java/com/tns/AppConfig.java index 149501a07..22e41bb02 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -66,6 +66,12 @@ public AppConfig(File appDir) { try { rootObject = FileSystem.readJSONFile(packageInfo); if (rootObject != null) { + // First, and never throwing: a malformed key further down ends + // the whole read. + if (rootObject.has(WrapperLifetimeKey)) { + readWrapperLifetime(rootObject.opt(WrapperLifetimeKey)); + } + // Parse security configuration if (rootObject.has(SecurityKey)) { JSONObject securityObject = rootObject.getJSONObject(SecurityKey); @@ -108,9 +114,6 @@ public AppConfig(File appDir) { Log.w("JS", String.format("Unknown uncaughtErrorPolicy \"%s\" - expected \"report\" or \"throw\". The default \"report\" will be used.", policy)); } } - if (rootObject.has(WrapperLifetimeKey)) { - readWrapperLifetime(rootObject.opt(WrapperLifetimeKey)); - } if (rootObject.has(AndroidKey)) { JSONObject androidObject = rootObject.getJSONObject(AndroidKey); if (androidObject.has(KnownKeys.V8FlagsKey.getName())) { @@ -156,6 +159,7 @@ public AppConfig(File appDir) { } } } catch (Exception e) { + Log.w("JS", "Could not read the app config past a malformed value; the keys read after it keep their defaults: " + e); if (com.tns.Runtime.isDebuggable()) { e.printStackTrace(); } From f1710ebfc0c9767e23a586034b07124f4a5539d1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:10:54 -0300 Subject: [PATCH 6/6] docs(runtime): explain wrapper lifetime scope and what resurrections counts scope was documented as a key with no word on what it selects. And resurrections counts every finalizer pass, at least two per wrapper JS dropped and one per major GC for a wrapper whose object Java holds, which is not what iOS's counter of the same name means. --- docs/ns-builtin-modules.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 57dd6e1a6..38b609829 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -165,7 +165,10 @@ iOS reads: A value that is not an object, or an unknown `mode` or `scope`, logs a warning and keeps the default. `"rooted"` is iOS-only: it reads native retain counts, -which Java does not have. +which Java does not have. `scope` chooses which wrappers a mode other than +`"resurrecting"` applies to, `"extended"` the instances of JS-extended classes +and `"all"` every wrapper; `"resurrecting"` applies to every wrapper whatever +the scope. `"resurrecting"` (the default) keeps a collected wrapper while Java may still hold its object. The first collection resurrects it and makes the Java side @@ -180,7 +183,7 @@ every build on cold paths only: | counter | counts | |---|---| -| `resurrections` | finalizer callbacks that kept a collected wrapper until the Java side says whether its object is still alive | +| `resurrections` | finalizer passes that kept a collected wrapper until the Java side says whether its object is still alive. Every pass counts, so a wrapper JS dropped counts at least twice (once to weaken the Java side, once more to check whether Java collected the object) and one whose object Java holds counts again on every major GC. Unlike iOS's counter of the same name, it is not a number of wrappers native code kept alive | | `weakened` | Java objects held weakly because their wrapper was collected | | `collected` | wrappers released because Java had collected their object | | `releasedExplicitly` | links released through `__releaseNativeCounterpart` |