diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index c2d66a5e4..38b609829 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,47 @@ 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. `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 +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 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` | +| `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 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..cfb068329 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -0,0 +1,141 @@ +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, 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); + + // 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 () { + 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).toBeGreaterThan(before + 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") { + 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..247d5eee6 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,36 @@ 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(); + const WrapperLifetimeStats& stats = Runtime::GetObjectManager(isolate)->GetLifetimeStats(); + Local context = isolate->GetCurrentContext(); + Local result = Object::New(isolate); + auto set = [&](const char* name, uint64_t value) { + (void) result->CreateDataProperty(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 +251,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 +263,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..dddf212fe 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -106,30 +106,39 @@ 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) { + if (IsReleasedWrapper(object)) { + m_lifetimeStats.releasedAccesses++; } + 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 +153,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; @@ -286,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); @@ -589,6 +617,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 +775,7 @@ void ObjectManager::FlushFinalizedBatch() { state->queued = false; if (weakened) { state->javaWeakened = true; + m_lifetimeStats.weakened++; } } }; @@ -758,10 +788,10 @@ 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); - object->SetInternalField(static_cast(MetadataNodeKeys::JsInfo), Undefined(m_isolate)); + MarkLinkReleased(po->Get(m_isolate)); } m_idToObject.Erase(javaObjectID); po->Reset(); @@ -894,13 +924,13 @@ 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; 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. @@ -909,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; @@ -921,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 469a18898..5a2f03a4a 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 { @@ -130,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 @@ -157,6 +162,8 @@ class ObjectManager { enum class MetadataNodeKeys { JsInfo, CallSuper, Metadata, END }; + const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; } + private: static void InitializeJNI(); @@ -197,6 +204,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); @@ -250,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); 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..3ad20078c --- /dev/null +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -0,0 +1,61 @@ +#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, or + // called a method on one whose link was released. + 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..22e41bb02 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; @@ -62,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); @@ -149,12 +159,47 @@ 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(); } } } + 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()) {