From e8b9a481e30fc915d6151984b04ce844c474b289 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 13:51:34 -0300 Subject: [PATCH 01/20] feat(runtime): canary wrapper lifetime mode Adds "wrapperLifetime": { "mode": "canary" }, the resurrection-free model the iOS runtime (NativeScript/ios#561) and the Node-API runtimes share. A wrapper in scope is a phantom-weak canary that dies with its JS references. A masking setter/deleter/definer interceptor mirrors its JS properties into a state object that lives until Java collects the object; a canary built later gets them back. When a canary dies, the Java object table holds an object with state through a watched weak reference and releases the others; a daemon thread on the references' queue reports Java collections, and the state is let go of on the runtime's thread. JS-extended instances (extend(), interface implementations, instances Java constructed) keep a record from registration, so Java can still call into JS after their canary died: the runtime rebuilds the canary with the instance's prototype, implementation object, internal fields and state. Scope "extended" (default) makes canaries of JS-extended instances only; other wrappers keep the resurrecting lifetime. "all" covers every wrapper of a Java object. ns:runtime gains getWrapperClassCounts() and canary counters. --- docs/ns-builtin-modules.md | 54 ++- test-app/app/src/main/assets/app/mainpage.js | 1 + .../main/assets/app/tests/testNsRuntime.js | 2 +- .../assets/app/tests/testWrapperLifetime.js | 5 +- .../app/tests/testWrapperLifetimeModes.js | 356 ++++++++++++++++ test-app/runtime/CMakeLists.txt | 1 + .../runtime/src/main/cpp/CallbackHandlers.cpp | 7 +- .../runtime/src/main/cpp/MetadataNode.cpp | 10 + .../runtime/src/main/cpp/NsBuiltinModules.cpp | 34 +- test-app/runtime/src/main/cpp/ObjectIdIndex.h | 20 + .../runtime/src/main/cpp/ObjectManager.cpp | 397 +++++++++++++++++- test-app/runtime/src/main/cpp/ObjectManager.h | 94 ++++- test-app/runtime/src/main/cpp/Runtime.cpp | 3 +- .../runtime/src/main/cpp/WrapperLifetime.cpp | 8 +- .../runtime/src/main/cpp/WrapperLifetime.h | 17 + .../src/main/cpp/WrapperLifetimeCanary.cpp | 266 ++++++++++++ .../src/main/cpp/WrapperLifetimeCanary.h | 74 ++++ .../runtime/src/main/cpp/com_tns_Runtime.cpp | 10 + .../runtime/src/main/cpp/js/ns-runtime.js | 4 +- .../src/main/java/com/tns/AppConfig.java | 2 +- .../src/main/java/com/tns/ObjectTable.java | 90 +++- .../src/main/java/com/tns/Runtime.java | 28 +- .../java/com/tns/WrapperLifetimeWatcher.java | 77 ++++ 23 files changed, 1537 insertions(+), 23 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js create mode 100644 test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp create mode 100644 test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h create mode 100644 test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 38b609829..bd16623f5 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -104,6 +104,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. | +| `getWrapperClassCounts()` | Per Java class name, the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). | | `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` @@ -118,7 +119,7 @@ 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"` | +| `wrapperLifetimeMode` | `"resurrecting"` \| `"canary"` | 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 @@ -160,7 +161,7 @@ top-level `"wrapperLifetime"` object of the app's `package.json`, the same key iOS reads: ```json -{ "wrapperLifetime": { "mode": "resurrecting", "scope": "extended" } } +{ "wrapperLifetime": { "mode": "canary", "scope": "all" } } ``` A value that is not an object, or an unknown `mode` or `scope`, logs a warning @@ -188,6 +189,55 @@ every build on cold paths only: | `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 | +| `canaryStates` | `"canary"` only: state objects created to hold JS properties | +| `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object | +| `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Other wrappers have no handler | +| `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object | + +In `"canary"` mode, `weakened` counts objects held weakly because their +canary died while they had JS state, and `collected` counts canaries whose +object had none, which Java no longer holds for JS. + +`"canary"` is the resurrection-free model the iOS runtime and the Node-API +runtimes share. A wrapper in scope is a canary: a phantom-weak JS object that +dies with its JS references. + +- **State.** A masking named interceptor (a setter, a deleter and a definer, + nothing that runs on reads) mirrors every JS property written to a canary + into a separate state object and lets V8 apply the write to the canary too, + so reads cost what they cost on a plain object. A write that resolves to a + Java field, another inherited accessor or a read-only property is not state. + The state lives until Java collects the object; a canary built later for the + same object gets its properties back, attributes, accessors and symbol keys + included. +- **Java's side.** While a canary is alive, Java holds its object strongly. + When it dies, Java holds an object with state weakly and releases any other. + A thread watching those weak references tells the runtime when Java collects + an object, and its state is let go of on the runtime's thread. +- **JS-extended instances** (`extend()`, interface implementations, Java + objects of those classes) keep a record from the moment they are registered, + whether or not JS wrote to them, so that Java can still call into JS after + their canary died: the runtime builds a new canary with the instance's + prototype, implementation object and state. +- **Scope.** `"extended"` (default) makes canaries of JS-extended instances + only; every other wrapper keeps the `"resurrecting"` lifetime, so its JS + properties still survive while Java holds its object. `"all"` makes every + Java object's wrapper a canary, Java arrays included. Array buffers backed by + Java buffers keep the `"resurrecting"` lifetime in both. + +What this trades: nothing JS references is released under it, and the state of +an object Java holds keeps everything it references. So state that references +its own object (a closure over `this`, `this.onTap = this.onTap.bind(this)`, +a `WeakMap` value naming it) keeps the object alive, through Java, for as long +as the cycle lasts; break such back references with a `WeakRef`. +`getWrapperClassCounts()` shows which classes grow across a repeated journey. +Other limits, as on iOS: `Object.freeze`, `seal` and `preventExtensions` throw +on a canary; index-keyed properties are not mirrored and die with the canary; +a write through an object whose prototype is a canary lands on that object. +A canary built after another died is a new JS object, which `===` cannot tell +because nothing kept the old one, but which keys `WeakMap`, `WeakSet`, +`WeakRef` and `FinalizationRegistry` entries separately. +`__releaseNativeCounterpart` drops the object's state with its link. Remote-module security (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) is **not** part of this surface. Those diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 87b389ffc..32b35a6dd 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -61,6 +61,7 @@ require("./tests/stringConversionTests"); require("./tests/testsForTypescript"); require("./tests/testGC"); require("./tests/testWrapperLifetime"); +require("./tests/testWrapperLifetimeModes"); 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 cc3ef6da4..53f84fcaf 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", "getWrapperLifetimeStats", "setConfig"]); + expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperClassCounts", "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 index cfb068329..350f9965f 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -21,7 +21,7 @@ describe("Wrapper lifetime", function () { }); it("reports the configured mode and scope (" + mode + "/" + scope + ")", function () { - expect(["resurrecting"]).toContain(mode); + expect(["resurrecting", "canary"]).toContain(mode); expect(["extended", "all"]).toContain(scope); }); @@ -37,7 +37,8 @@ describe("Wrapper lifetime", function () { it("exposes numeric counters", function () { var stats = runtime.getWrapperLifetimeStats(); expect(Object.keys(stats).sort()).toEqual( - ["collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); + ["canaryInterceptedWrites", "canaryNativeDeaths", "canaryRebuilds", "canaryStates", + "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); Object.keys(stats).forEach(function (key) { expect(typeof stats[key]).toBe("number"); }); diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js new file mode 100644 index 000000000..987e285cd --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -0,0 +1,356 @@ +describe("Wrapper lifetime modes", function () { + var runtime = require("ns:runtime"); + var mode = runtime.getConfig("wrapperLifetimeMode"); + var scope = runtime.getConfig("wrapperLifetimeScope"); + var canary = mode === "canary"; + var Holder = com.tns.tests.WrapperHolder; + + function stats() { + return runtime.getWrapperLifetimeStats(); + } + + 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(); + } + + // Lets JS drop every wrapper nothing references, and Java collect every object nothing + // but a weak entry holds. + function collectBoth() { + gc(); + crossIntoJava(); + collectJava(); + gc(); + crossIntoJava(); + } + + // Collects until predicate() holds; the watcher reports Java's collections from its own + // thread, so their effect lands on a later event loop turn. + function eventually(predicate, done, message) { + var deadline = Date.now() + 10000; + (function poll() { + collectBoth(); + collectJava(); + if (predicate()) { + done(); + return; + } + if (Date.now() > deadline) { + done.fail(message); + return; + } + setTimeout(poll, 50); + })(); + } + + afterEach(function () { + Holder.held = null; + }); + + it("runs in the configured mode (" + mode + "/" + scope + ")", function () { + expect(["resurrecting", "canary"]).toContain(mode); + }); + + it("keeps own-property semantics for JS properties on a Java object", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.a = 1; + Object.defineProperty(runnable, "hidden", { value: 2, enumerable: false, writable: true, configurable: true }); + expect(Object.keys(runnable)).toEqual(["a"]); + expect("a" in runnable).toBe(true); + expect(Object.prototype.hasOwnProperty.call(runnable, "hidden")).toBe(true); + expect(Object.getOwnPropertyDescriptor(runnable, "a")).toEqual({ value: 1, writable: true, enumerable: true, configurable: true }); + expect(delete runnable.a).toBe(true); + expect("a" in runnable).toBe(false); + runnable.a = 3; + expect(runnable.a).toBe(3); + }); + + it("keeps the JS state of a Java-held extended object and the Java objects it references", function () { + var rebuilds = stats().canaryRebuilds; + (function () { + var runnable = new java.lang.Runnable({ + run: function () { + this.ran = (this.ran || 0) + 1; + } + }); + runnable.tag = "kept"; + runnable.child = new java.lang.StringBuilder("child"); + Holder.held = runnable; + })(); + collectBoth(); + collectJava(); + + var runnable = Holder.held; + expect(runnable.tag).toBe("kept"); + if (canary) { + expect(runnable.child.toString()).toBe("child"); + } else { + // Weakened with the holder's wrapper, and collected by Java under it. + expect(function () { + runnable.child.toString(); + }).toThrowError(/no longer has available Java instance counterpart/); + } + runnable.run(); + expect(runnable.ran).toBe(1); + if (canary) { + expect(stats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + }); + + it("lets Java call into a JS-implemented object whose wrapper was collected", function () { + var task = (function () { + var callable = new java.util.concurrent.Callable({ + call: function () { + return "answer:" + this.answer; + } + }); + callable.answer = 42; + return new java.util.concurrent.FutureTask(callable); + })(); + collectBoth(); + collectJava(); + + task.run(); + expect(task.get()).toBe("answer:42"); + }); + + it("hands an extend() instance's state to Java calls after its wrapper was collected", function () { + var Described = java.lang.Object.extend({ + toString: function () { + return "described:" + this.label; + } + }); + (function () { + var described = new Described(); + described.label = "first"; + Holder.held = described; + })(); + collectBoth(); + collectJava(); + + expect(java.lang.String.valueOf(Holder.held)).toBe("described:first"); + Holder.held.label = "second"; + collectBoth(); + expect(java.lang.String.valueOf(Holder.held)).toBe("described:second"); + }); + + it("keeps the state of an extended object Java constructed", function () { + var Made = java.lang.Object.extend({ + toString: function () { + return "made:" + this.value; + } + }); + (function () { + var made = new Made().getClass().newInstance(); + made.value = 7; + Holder.held = made; + })(); + collectBoth(); + collectJava(); + + expect(java.lang.String.valueOf(Holder.held)).toBe("made:7"); + }); + + it("keeps the state a TypeScript-style subclass sets in its constructor", function () { + var Greeter = (function (_super) { + __extends(Greeter, _super); + function Greeter(name) { + var _this = _super.call(this) || this; + _this.name = name; + return __native(_this); + } + Greeter.prototype.toString = function () { + return "hello " + this.name; + }; + return Greeter; + })(java.lang.Object); + (function () { + Holder.held = new Greeter("ts"); + })(); + collectBoth(); + collectJava(); + + expect(java.lang.String.valueOf(Holder.held)).toBe("hello ts"); + }); + + // Under "resurrecting" the child's Java object is weakened with the holder's wrapper + // and Java collects it (testWrapperLifetime.js); a canary's state keeps it. + it("keeps the Java objects a Java-held canary's JS properties reference", function () { + if (!canary) { + return; + } + (function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.child = new java.lang.StringBuilder("child"); + Holder.held = runnable; + })(); + gc(); + crossIntoJava(); + collectJava(); + + expect(Holder.held.child.toString()).toBe("child"); + }); + + it("hands back a property that shadows a prototype member on a new wrapper", function () { + (function () { + var runnable = new java.lang.Runnable({ + run: function () { + return "prototype"; + } + }); + runnable.run = function () { + return "shadow"; + }; + Holder.held = runnable; + })(); + collectBoth(); + + expect(Holder.held.run()).toBe("shadow"); + delete Holder.held.run; + expect(Holder.held.run()).toBe("prototype"); + }); + + it("hands back non-enumerable, read-only, accessor and symbol-keyed properties with their attributes", function () { + var symbol = Symbol("key"); + (function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + Object.defineProperty(runnable, "fixed", { value: 1, writable: false, enumerable: true, configurable: false }); + Object.defineProperty(runnable, "hidden", { value: 2, writable: true, enumerable: false, configurable: true }); + Object.defineProperty(runnable, "doubled", { + get: function () { + return this.fixed * 2; + }, + enumerable: true, + configurable: true + }); + runnable[symbol] = "symbol"; + Holder.held = runnable; + })(); + collectBoth(); + + var runnable = Holder.held; + expect(Object.getOwnPropertyDescriptor(runnable, "fixed")).toEqual({ value: 1, writable: false, enumerable: true, configurable: false }); + expect(Object.getOwnPropertyDescriptor(runnable, "hidden")).toEqual({ value: 2, writable: true, enumerable: false, configurable: true }); + expect(runnable.doubled).toBe(2); + expect(runnable[symbol]).toBe("symbol"); + }); + + it("writes Java fields through to Java without making them JS state", function () { + var states = stats().canaryStates; + var point = new android.graphics.Point(1, 2); + point.x = 5; + expect(point.x).toBe(5); + expect(Object.keys(point)).not.toContain("x"); + expect(stats().canaryStates).toBe(states); + }); + + it("refuses to freeze a canary", function () { + if (!canary) { + return; + } + var runnable = new java.lang.Runnable({ run: function () {} }); + expect(function () { + Object.freeze(runnable); + }).toThrow(); + }); + + it("leaves plain wrappers outside the extended scope without forwarding", function () { + if (!canary || scope !== "extended") { + return; + } + var writes = stats().canaryInterceptedWrites; + var plain = new java.lang.StringBuilder(); + plain.tag = 1; + expect(stats().canaryInterceptedWrites).toBe(writes); + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.tag = 1; + expect(stats().canaryInterceptedWrites).toBe(writes + 1); + }); + + it("lets Java collect an extended object only JS referenced", function (done) { + var ref = (function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.tag = "state"; + return new java.lang.ref.WeakReference(runnable); + })(); + var deaths = stats().canaryNativeDeaths; + eventually(function () { + return ref.get() === null && (!canary || stats().canaryNativeDeaths > deaths); + }, done, "the Java object or its state stayed alive"); + }); + + // The contract: the state is rooted until Java collects the object, so state that + // references its own object keeps it alive. Break such back references with a WeakRef. + it("keeps an extended object whose JS state references it", function () { + if (!canary) { + return; + } + var ref = (function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.self = runnable; + return new java.lang.ref.WeakReference(runnable); + })(); + collectBoth(); + collectJava(); + collectBoth(); + + expect(ref.get()).not.toBe(null); + __releaseNativeCounterpart(ref.get()); + }); + + it("lets an explicitly released extended object's state go", function () { + if (!canary) { + return; + } + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.tag = "released"; + Holder.held = runnable; + __releaseNativeCounterpart(runnable); + runnable = null; + collectBoth(); + + var again = Holder.held; + expect(again.tag).toBeUndefined(); + }); + + it("counts live wrappers, canaries and states per Java class", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.tag = 1; + var counts = runtime.getWrapperClassCounts(); + var names = Object.keys(counts).filter(function (name) { + return counts[name].wrappers > 0; + }); + expect(names.length).toBeGreaterThan(0); + var entry = counts[runnable.getClass().getName()]; + expect(entry).toBeDefined(); + expect(entry.wrappers).toBeGreaterThan(0); + if (canary) { + expect(entry.canaries).toBeGreaterThan(0); + expect(entry.states).toBeGreaterThan(0); + } else { + expect(entry.canaries).toBe(0); + expect(entry.states).toBe(0); + } + }); + + it("counts canary activity", function () { + var before = stats(); + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.tag = 1; + var after = stats(); + if (canary) { + expect(after.canaryStates).toBe(before.canaryStates + 1); + expect(after.canaryInterceptedWrites).toBe(before.canaryInterceptedWrites + 1); + } else { + expect(after.canaryStates).toBe(before.canaryStates); + expect(after.canaryInterceptedWrites).toBe(before.canaryInterceptedWrites); + } + }); +}); diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 28b8eaa4d..117b355f8 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -232,6 +232,7 @@ add_library( src/main/cpp/V8StringConstants.cpp src/main/cpp/WeakRef.cpp src/main/cpp/WrapperLifetime.cpp + src/main/cpp/WrapperLifetimeCanary.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/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index ae99e715d..6e5633dbb 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -236,7 +236,12 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j int javaObjectID = objectManager->GenerateNewObjectID(); - objectManager->Link(jsObject, javaObjectID, nullptr); + // Java calls into JS through an extended class's or an interface implementation's + // instance; a plain class constructed from JS is a plain wrapper. + objectManager->Link(jsObject, javaObjectID, nullptr, + !implementationObject.IsEmpty() || isInterface + ? ObjectManager::LinkKind::kExtended + : ObjectManager::LinkKind::kPlain); // resolve constructor const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName, diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 5891a2741..8e06fb6af 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -1,4 +1,5 @@ #include "MetadataNode.h" +#include "WrapperLifetimeCanary.h" #include "RuntimeState.h" #include "NativeScriptAssert.h" #include "Constants.h" @@ -171,6 +172,8 @@ Local MetadataNode::GetOrCreateArrayObjectTemplate(Isolate* isol arrayObjectTemplate->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); arrayObjectTemplate->SetHandler(IndexedPropertyHandlerConfiguration( ArrayIndexedPropertyGetterCallback, ArrayIndexedPropertySetterCallback)); + WrapperLifetimeCanary::ConfigureInstanceTemplate( + arrayObjectTemplate, WrapperLifetimeCanary::TemplateKind::kPlain); cache->ArrayObjectTemplate = new Persistent(isolate, arrayObjectTemplate); @@ -1357,6 +1360,11 @@ Local MetadataNode::GetConstructorFunctionTemplate(Isolate* is } ctorFuncTemplate->SetClassName(v8::String::NewFromUtf8(isolate, finalName.c_str()).ToLocalChecked()); ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); + // An interface's constructor builds implementations, which Java calls into. + WrapperLifetimeCanary::ConfigureInstanceTemplate( + ctorFuncTemplate->InstanceTemplate(), + isInterface ? WrapperLifetimeCanary::TemplateKind::kExtended + : WrapperLifetimeCanary::TemplateKind::kPlain); Local baseCtorFunc; Local baseFuncTemplate; @@ -2310,6 +2318,8 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfoInstanceTemplate()->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); + WrapperLifetimeCanary::ConfigureInstanceTemplate( + extendFuncTemplate->InstanceTemplate(), WrapperLifetimeCanary::TemplateKind::kExtended); auto context = isolate->GetCurrentContext(); auto extendFunc = extendFuncTemplate->GetFunction(context).ToLocalChecked(); diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 247d5eee6..230f3c2cc 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -175,6 +175,32 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { set("collected", stats.collected); set("releasedExplicitly", stats.releasedExplicitly); set("releasedAccesses", stats.releasedAccesses); + set("canaryStates", stats.canaryStates); + set("canaryNativeDeaths", stats.canaryNativeDeaths); + set("canaryInterceptedWrites", stats.canaryInterceptedWrites); + set("canaryRebuilds", stats.canaryRebuilds); + info.GetReturnValue().Set(result); +} + +void GetWrapperClassCountsCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + ObjectManager* objectManager = Runtime::GetObjectManager(isolate); + if (objectManager == nullptr) { + return; + } + Local context = isolate->GetCurrentContext(); + Local result = Object::New(isolate); + for (const auto& [name, counts] : objectManager->GetWrapperClassCounts()) { + Local entry = Object::New(isolate); + auto set = [&](const char* key, uint64_t value) { + (void) entry->Set(context, ArgConverter::ConvertToV8String(isolate, key), + Number::New(isolate, static_cast(value))); + }; + set("wrappers", counts.wrappers); + set("canaries", counts.canaries); + set("states", counts.states); + (void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name), entry); + } info.GetReturnValue().Set(result); } @@ -251,11 +277,14 @@ MaybeLocal NsModuleBinding(Local context) { MaybeLocal NsRuntimeBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - Local setConfig, getConfig, escapeException, getWrapperLifetimeStats; + Local setConfig, getConfig, escapeException, getWrapperLifetimeStats, + getWrapperClassCounts; if (!v8::Function::New(context, SetConfigCallback).ToLocal(&setConfig) || !v8::Function::New(context, GetConfigCallback).ToLocal(&getConfig) || !v8::Function::New(context, GetWrapperLifetimeStatsCallback) .ToLocal(&getWrapperLifetimeStats) || + !v8::Function::New(context, GetWrapperClassCountsCallback) + .ToLocal(&getWrapperClassCounts) || !Interop::CreateEscapeException(context).ToLocal(&escapeException) || !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "setConfig"), setConfig) .FromMaybe(false) || @@ -266,6 +295,9 @@ MaybeLocal NsRuntimeBinding(Local context) { .FromMaybe(false) || !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "getWrapperLifetimeStats"), getWrapperLifetimeStats) + .FromMaybe(false) || + !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "getWrapperClassCounts"), + getWrapperClassCounts) .FromMaybe(false)) { return MaybeLocal(); } diff --git a/test-app/runtime/src/main/cpp/ObjectIdIndex.h b/test-app/runtime/src/main/cpp/ObjectIdIndex.h index 9966e6944..fbe95520e 100644 --- a/test-app/runtime/src/main/cpp/ObjectIdIndex.h +++ b/test-app/runtime/src/main/cpp/ObjectIdIndex.h @@ -96,6 +96,26 @@ class ObjectIdIndex { } } + // Calls f on every entry. f must not insert or erase. + template + void ForEach(F&& f) const { + for (const auto& chunk : m_chunks) { + if (chunk == nullptr) { + continue; + } + for (const auto& leaf : chunk->leaves) { + if (leaf == nullptr) { + continue; + } + for (T* entry : leaf->slots) { + if (entry != nullptr) { + f(entry); + } + } + } + } + } + // Empties the index, then calls f on every entry it held. template void DrainAll(F&& f) { diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index dddf212fe..1d75bf6d1 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -13,6 +13,7 @@ #include "Util.h" #include "V8GlobalHelpers.h" #include "V8StringConstants.h" +#include "WrapperLifetimeCanary.h" #include "include/v8.h" using namespace v8; @@ -79,6 +80,14 @@ void ObjectManager::InitializeJNI() { env.GetMethodID(runtimeClass, "releaseIfCollected", "(I)Z"); NS_CHECK(RELEASE_IF_COLLECTED_METHOD_ID != nullptr); + PROCESS_CANARY_BATCH_METHOD_ID = + env.GetMethodID(runtimeClass, "processCanaryBatch", "([II[II)V"); + NS_CHECK(PROCESS_CANARY_BATCH_METHOD_ID != nullptr); + + STRENGTHEN_INSTANCE_METHOD_ID = + env.GetMethodID(runtimeClass, "strengthenInstance", "(I)Z"); + NS_CHECK(STRENGTHEN_INSTANCE_METHOD_ID != nullptr); + JAVA_LANG_CLASS = env.FindClass("java/lang/Class"); NS_CHECK(JAVA_LANG_CLASS != nullptr); @@ -101,6 +110,15 @@ void ObjectManager::Init(Isolate* isolate) { jsWrapperFuncTemplate->GetFunction(context).ToLocalChecked(); m_poJsWrapperFunc = new Persistent(isolate, jsWrapperFunc); m_jsWrapperTemplate.Reset(isolate, jsWrapperFuncTemplate->InstanceTemplate()); + + if (WrapperLifetimeCanary::Enabled()) { + auto canaryTemplate = ObjectTemplate::New(isolate); + canaryTemplate->SetInternalFieldCount(static_cast(MetadataNodeKeys::END)); + WrapperLifetimeCanary::ConfigureInstanceTemplate( + canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended); + m_canaryTemplate.Reset(isolate, canaryTemplate); + isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); + } } JniLocalRef ObjectManager::GetJavaObjectByJsObject( @@ -375,7 +393,7 @@ Local ObjectManager::GetJsObjectByJavaObject(int javaObjectID) { auto state = m_idToObject.Find(javaObjectID); if (state == nullptr) { - return handleScope.Escape(Local()); + return handleScope.Escape(RebuildCanary(javaObjectID)); } return handleScope.Escape(JsObjectFor(state)); @@ -505,6 +523,12 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, MetadataNode* node) { auto isolate = m_isolate; + // A JS-extended instance's canary starts from its record, not from its class. + auto rebuilt = RebuildCanary(javaObjectID); + if (!rebuilt.IsEmpty()) { + return rebuilt; + } + if (node == nullptr) { node = MetadataNode::GetOrCreate(className); } @@ -525,7 +549,7 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, * Link the JavaScript object and it's java counterpart with an ID */ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, - jclass clazz) { + jclass clazz, LinkKind kind) { if (!IsJsRuntimeObject(object)) { string errMsg("Trying to link invalid 'this' to a Java object"); throw NativeScriptException(errMsg); @@ -538,9 +562,16 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, auto state = new ObjectWeakCallbackState(this, javaObjectID, clazz, isolate, object); - // subscribe for JS GC event - state->target->SetWeak(state, JSObjectFinalizerStatic, - WeakCallbackType::kFinalizer); + // Array buffers carry no Metadata field and cannot hold the canary handlers. + state->canary = WrapperLifetimeCanary::InScope(kind == LinkKind::kExtended) && + HasMetadataField(object); + if (state->canary) { + state->target->SetWeak(state, CanaryDiedStatic, WeakCallbackType::kParameter); + } else { + // subscribe for JS GC event + state->target->SetWeak(state, JSObjectFinalizerStatic, + WeakCallbackType::kFinalizer); + } SetJsInfo(object, javaObjectID); @@ -549,6 +580,336 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, // wrapper's Java object. NS_DCHECK(inserted); (void) inserted; + + if (state->canary) { + AdoptCanary(object, javaObjectID, kind); + } +} + +void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObjectID, + LinkKind kind) { + CanaryRecord* record = FindCanaryRecord(javaObjectID); + if (record == nullptr) { + if (kind != LinkKind::kExtended) { + return; + } + // Java calls into JS through this object for as long as it lives, so the + // record is made now, not at the first write: a canary built later needs + // the prototype and fields this one was registered with. + auto isolate = m_isolate; + auto created = std::make_unique(); + created->extended = true; + created->prototype.Reset(isolate, object->GetPrototype()); + created->callSuper.Reset( + isolate, object->GetInternalField(static_cast(MetadataNodeKeys::CallSuper)).As()); + created->metadata.Reset( + isolate, object->GetInternalField(static_cast(MetadataNodeKeys::Metadata)).As()); + Local implementationObject; + if (V8GetPrivateValue(isolate, object, V8StringConstants::GetImplementationObject(isolate), + implementationObject) && + !implementationObject.IsEmpty()) { + created->implementationObject.Reset(isolate, implementationObject); + } + m_canaryRecords.emplace(javaObjectID, std::move(created)); + return; + } + EnsureJavaStrong(javaObjectID, record); + if (!record->state.IsEmpty()) { + auto context = m_isolate->GetCurrentContext(); + if (context.IsEmpty()) { + context = Runtime::GetRuntime(m_isolate)->GetContext(); + } + WrapperLifetimeCanary::CopyOwnProperties(m_isolate, context, + record->state.Get(m_isolate), object); + } +} + +ObjectManager::CanaryRecord* ObjectManager::FindCanaryRecord(int javaObjectID) { + if (m_canaryRecords.empty()) { + return nullptr; + } + auto it = m_canaryRecords.find(javaObjectID); + return it != m_canaryRecords.end() ? it->second.get() : nullptr; +} + +void ObjectManager::EraseCanaryRecord(int javaObjectID) { + m_canaryRecords.erase(javaObjectID); +} + +bool ObjectManager::EnsureJavaStrong(int javaObjectID, CanaryRecord* record) { + if (!record->javaWeak) { + return true; + } + JEnv env; + AssertIsolateLocked(); + bool alive = env.CallBooleanMethod(m_javaRuntimeObject, STRENGTHEN_INSTANCE_METHOD_ID, + javaObjectID) == JNI_TRUE; + if (!alive) { + // Collected; the watcher's report has not arrived yet. + EraseCanaryRecord(javaObjectID); + return false; + } + record->javaWeak = false; + return true; +} + +Local ObjectManager::RebuildCanary(int javaObjectID) { + CanaryRecord* record = FindCanaryRecord(javaObjectID); + if (record == nullptr || !record->extended) { + return Local(); + } + auto isolate = m_isolate; + EscapableHandleScope handleScope(isolate); + if (!EnsureJavaStrong(javaObjectID, record)) { + return handleScope.Escape(Local()); + } + auto context = isolate->GetCurrentContext(); + Local canary; + if (!m_canaryTemplate.Get(isolate)->NewInstance(context).ToLocal(&canary)) { + return handleScope.Escape(Local()); + } + Local prototype = record->prototype.Get(isolate); + if (!prototype.IsEmpty() && (prototype->IsObject() || prototype->IsNull())) { + (void) canary->SetPrototype(context, prototype); + } + canary->SetInternalField(static_cast(MetadataNodeKeys::CallSuper), + record->callSuper.Get(isolate)); + canary->SetInternalField(static_cast(MetadataNodeKeys::Metadata), + record->metadata.Get(isolate)); + if (!record->implementationObject.IsEmpty()) { + V8SetPrivateValue(isolate, canary, V8StringConstants::GetImplementationObject(isolate), + record->implementationObject.Get(isolate)); + } + m_lifetimeStats.canaryRebuilds++; + Link(canary, javaObjectID, record->clazz, LinkKind::kExtended); + return handleScope.Escape(canary); +} + +ObjectManager::ObjectWeakCallbackState* ObjectManager::CanaryOf(const Local& holder) { + if (!HasMetadataField(holder)) { + return nullptr; + } + int id = LinkedIdOf(holder); + if (id == -1) { + return nullptr; + } + auto state = m_idToObject.Find(id); + // A `super` object shares its owner's id but is not the canary. + if (state == nullptr || !state->canary || !state->linked || *state->target != holder) { + return nullptr; + } + return state; +} + +bool ObjectManager::IsCanary(const Local& holder) { + return CanaryOf(holder) != nullptr; +} + +bool ObjectManager::ExistingCanaryState(const Local& holder, Local* out) { + auto state = CanaryOf(holder); + if (state == nullptr) { + return false; + } + CanaryRecord* record = FindCanaryRecord(state->javaObjectID); + if (record == nullptr || record->state.IsEmpty()) { + return false; + } + *out = record->state.Get(m_isolate); + return true; +} + +bool ObjectManager::CanaryStateForWrite(const Local& holder, Local* out) { + if (ExistingCanaryState(holder, out)) { + return true; + } + auto state = CanaryOf(holder); + if (state == nullptr) { + return false; + } + int id = state->javaObjectID; + // Allocated before the record is looked up: a collection it starts runs the + // canary callbacks, which read the records. + Local fresh = Object::New(m_isolate, Null(m_isolate), nullptr, nullptr, 0); + CanaryRecord* record = FindCanaryRecord(id); + if (record == nullptr) { + auto created = std::make_unique(); + record = created.get(); + m_canaryRecords.emplace(id, std::move(created)); + } + record->state.Reset(m_isolate, fresh); + m_lifetimeStats.canaryStates++; + *out = fresh; + return true; +} + +void ObjectManager::CanaryDiedStatic( + const WeakCallbackInfo& data) { + ObjectWeakCallbackState* state = data.GetParameter(); + ObjectManager* thisPtr = state->thisPtr; + state->handle.Reset(); + uint32_t id = state->javaObjectID; + if (thisPtr->m_idToObject.Find(id) == state) { + thisPtr->m_idToObject.Erase(id); + } + if (state->linked) { + if (CanaryRecord* record = thisPtr->FindCanaryRecord(id)) { + if (state->objectClazz != nullptr) { + record->clazz = state->objectClazz; + } + } + thisPtr->m_pendingCanaryDeaths.push_back(static_cast(id)); + } + delete state; +} + +void ObjectManager::CanaryGCEpilogue(Isolate* isolate, GCType type, GCCallbackFlags flags, + void* data) { + auto thisPtr = static_cast(data); + if (!thisPtr->m_pendingCanaryDeaths.empty()) { + // Same as the finalizers': the next JS<->Java crossing flushes; this task + // covers a thread that goes idle first. + constexpr double kIdleFlushDelayMs = 4; + thisPtr->ScheduleFinalizedBatchFlush(kIdleFlushDelayMs); + } +} + +bool ObjectManager::FlushCanaryDeaths() { + ReleaseCollectedCanaryStates(); + if (m_pendingCanaryDeaths.empty()) { + return true; + } + if (!m_deathInboxOpen) { + auto runtime = Runtime::GetRuntime(m_isolate); + m_deathInboxRuntimeId = runtime->GetId(); + WrapperLifetimeCanary::OpenDeathInbox(m_deathInboxRuntimeId, runtime->GetEventLoop()); + m_deathInboxOpen = true; + } + auto deaths = std::move(m_pendingCanaryDeaths); + m_pendingCanaryDeaths.clear(); + std::sort(deaths.begin(), deaths.end()); + deaths.erase(std::unique(deaths.begin(), deaths.end()), deaths.end()); + + std::vector weaken; + std::vector release; + for (jint id : deaths) { + if (m_idToObject.Find(id) != nullptr) { + // A new canary was built since: the Java side stays strong. + continue; + } + CanaryRecord* record = FindCanaryRecord(id); + if (record == nullptr) { + release.push_back(id); + } else if (!record->javaWeak) { + weaken.push_back(id); + } + } + if (weaken.empty() && release.empty()) { + return true; + } + + JEnv env; + JNIEnv* raw = env; + auto toJava = [raw](const std::vector& ids) -> jintArray { + if (ids.empty()) { + return nullptr; + } + auto count = static_cast(ids.size()); + jintArray array = raw->NewIntArray(count); + if (array != nullptr) { + raw->SetIntArrayRegion(array, 0, count, ids.data()); + } + return array; + }; + JniLocalRef weakenArray(toJava(weaken)); + JniLocalRef releaseArray(toJava(release)); + bool failed = (!weaken.empty() && weakenArray.IsNull()) || + (!release.empty() && releaseArray.IsNull()); + if (!failed) { + AssertIsolateLocked(); + raw->CallVoidMethod(m_javaRuntimeObject, PROCESS_CANARY_BATCH_METHOD_ID, + (jintArray) weakenArray, static_cast(weaken.size()), + (jintArray) releaseArray, static_cast(release.size())); + failed = raw->ExceptionCheck(); + } + if (failed) { + if (raw->ExceptionCheck()) { + raw->ExceptionDescribe(); + raw->ExceptionClear(); + } + m_pendingCanaryDeaths.insert(m_pendingCanaryDeaths.end(), deaths.begin(), deaths.end()); + return false; + } + + m_lifetimeStats.collected += release.size(); + if (!weaken.empty()) { + std::vector results(weaken.size()); + raw->GetIntArrayRegion((jintArray) weakenArray, 0, static_cast(weaken.size()), + results.data()); + for (size_t i = 0; i < weaken.size(); i++) { + if (results[i] < 0) { + // Never registered (a failed construction), or already collected. + EraseCanaryRecord(weaken[i]); + continue; + } + if (CanaryRecord* record = FindCanaryRecord(weaken[i])) { + record->javaWeak = true; + m_lifetimeStats.weakened++; + } + } + } + return true; +} + +std::map ObjectManager::GetWrapperClassCounts() { + std::map counts; + std::unordered_map names; + auto nameOf = [&names](jclass clazz) -> const std::string& { + auto it = names.find(clazz); + if (it != names.end()) { + return it->second; + } + std::string name = clazz != nullptr ? GetClassName(clazz) : std::string(""); + std::replace(name.begin(), name.end(), '/', '.'); + return names.emplace(clazz, std::move(name)).first->second; + }; + m_idToObject.ForEach([&](ObjectWeakCallbackState* state) { + if (!state->linked) { + return; + } + ClassCounts& entry = counts[nameOf(state->objectClazz)]; + entry.wrappers++; + if (state->canary) { + entry.canaries++; + } + }); + for (const auto& [id, record] : m_canaryRecords) { + if (record->state.IsEmpty()) { + continue; + } + jclass clazz = record->clazz; + if (auto live = m_idToObject.Find(id)) { + clazz = live->objectClazz; + } + counts[nameOf(clazz)].states++; + } + return counts; +} + +void ObjectManager::ReleaseCollectedCanaryStates() { + if (!m_deathInboxOpen) { + return; + } + for (int id : WrapperLifetimeCanary::TakeCollected(m_deathInboxRuntimeId)) { + // A live canary keeps its object strongly held, so Java cannot have + // collected an object that has one. + if (m_idToObject.Find(id) != nullptr) { + continue; + } + if (FindCanaryRecord(id) != nullptr) { + EraseCanaryRecord(id); + m_lifetimeStats.canaryNativeDeaths++; + } + } } bool ObjectManager::CloneLink(const Local& src, @@ -671,7 +1032,8 @@ bool ObjectManager::ScheduleFinalizedBatchFlush(double delayMs) { void ObjectManager::FlushFinalizedBatch() { m_flushScheduled = false; m_flushBackingOff = false; - if (m_pendingWeaken.empty() && m_pendingCheck.empty()) { + if (m_pendingWeaken.empty() && m_pendingCheck.empty() && + m_pendingCanaryDeaths.empty() && !m_deathInboxOpen) { return; } // A failed Java->JS call returns with its exception pending: JNI may not be used until it @@ -682,6 +1044,15 @@ void ObjectManager::FlushFinalizedBatch() { } HandleScope handleScope(m_isolate); + if (!FlushCanaryDeaths()) { + constexpr double kRetryDelayMs = 100; + m_flushBackingOff = ScheduleFinalizedBatchFlush(kRetryDelayMs); + return; + } + if (m_pendingWeaken.empty() && m_pendingCheck.empty()) { + return; + } + auto weaken = std::move(m_pendingWeaken); auto check = std::move(m_pendingCheck); m_pendingWeaken.clear(); @@ -810,6 +1181,16 @@ void ObjectManager::ReleaseAllRegistered() { m_pendingWeaken.clear(); m_pendingCheck.clear(); + m_pendingCanaryDeaths.clear(); + if (WrapperLifetimeCanary::Enabled()) { + m_isolate->RemoveGCEpilogueCallback(CanaryGCEpilogue, this); + if (m_deathInboxOpen) { + WrapperLifetimeCanary::CloseDeathInbox(m_deathInboxRuntimeId); + m_deathInboxOpen = false; + } + } + m_canaryRecords.clear(); + m_canaryTemplate.Reset(); auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); @@ -931,6 +1312,8 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { env.CallVoidMethod(m_javaRuntimeObject, RELEASE_NATIVE_INSTANCE_METHOD_ID, javaObjectID); m_lifetimeStats.releasedExplicitly++; + // Java no longer knows the id, so nothing could rebuild a canary from it. + EraseCanaryRecord(javaObjectID); // The registration outlives the link: it is dropped by the finalizer once // the wrapper is collected. @@ -968,3 +1351,5 @@ jmethodID ObjectManager::MAKE_INSTANCE_STRONG_METHOD_ID = nullptr; jmethodID ObjectManager::PROCESS_FINALIZED_BATCH_METHOD_ID = nullptr; jmethodID ObjectManager::RELEASE_NATIVE_INSTANCE_METHOD_ID = nullptr; jmethodID ObjectManager::RELEASE_IF_COLLECTED_METHOD_ID = nullptr; +jmethodID ObjectManager::PROCESS_CANARY_BATCH_METHOD_ID = nullptr; +jmethodID ObjectManager::STRENGTHEN_INSTANCE_METHOD_ID = nullptr; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 5a2f03a4a..b71a14f1d 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -2,6 +2,7 @@ #define OBJECTMANAGER_H_ #include +#include #include #include #include @@ -67,7 +68,8 @@ class ObjectManager { // rely on the delayed flush task. void FlushFinalizedBatchIfPending() { if (!m_flushBackingOff && - (!m_pendingWeaken.empty() || !m_pendingCheck.empty())) { + (!m_pendingWeaken.empty() || !m_pendingCheck.empty() || + !m_pendingCanaryDeaths.empty())) { FlushFinalizedBatch(); } } @@ -95,8 +97,12 @@ class ObjectManager { v8::Local CreateJSWrapper(jint javaObjectID, int classIndex, jobject instance); + // What a link's object is: Java calls into JS through an extended one (a + // JS-extended class's or an interface implementation's instance). + enum class LinkKind { kPlain, kExtended }; + void Link(const v8::Local& object, uint32_t javaObjectID, - jclass clazz); + jclass clazz, LinkKind kind = LinkKind::kPlain); void ReleaseNativeCounterpart(v8::Local& object); @@ -164,6 +170,29 @@ class ObjectManager { const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; } + // Canary mode (WrapperLifetimeCanary), for its write handlers. holder is a + // live canary: an object this manager linked as one, not yet released. + bool IsCanary(const v8::Local& holder); + // The state object of a canary that has one. + bool ExistingCanaryState(const v8::Local& holder, v8::Local* out); + // The state object of a canary, created on its first write. + bool CanaryStateForWrite(const v8::Local& holder, v8::Local* out); + void CountCanaryWrite() { m_lifetimeStats.canaryInterceptedWrites++; } + // Lets go of the state of objects Java reported collected. Runtime thread. + void ReleaseCollectedCanaryStates(); + + struct ClassCounts { + // Linked wrappers, canaries included. + uint64_t wrappers = 0; + // Live canaries. + uint64_t canaries = 0; + // Canary state objects, alive until Java collects their object. + uint64_t states = 0; + }; + + // Per Java class name (dotted), for ns:runtime's getWrapperClassCounts(). + std::map GetWrapperClassCounts(); + private: static void InitializeJNI(); @@ -197,6 +226,26 @@ class ObjectManager { // Handed back to JS while queued: the wrapper is reachable again, so the flush must // leave the Java side alone and let a later collection queue it anew. bool reacquired = false; + // A canary: a phantom handle, and no resurrection. + bool canary = false; + }; + + // Canary mode: what outlives the canaries of one Java object id, until Java + // collects the object. Its handles are reset only on the runtime's thread. + struct CanaryRecord { + // The object's JS properties; empty until the first write. + v8::Global state; + // JS-extended instances: what a canary built later starts from, as the + // first canary had it once registered. + bool extended = false; + v8::Global prototype; + v8::Global callSuper; + v8::Global metadata; + v8::Global implementationObject; + // The link's class, taken from the last canary (a global ref the class caches own). + jclass clazz = nullptr; + // The Java object table holds the object through a watched weak reference. + bool javaWeak = false; }; using JSInstanceInfo = ObjectWeakCallbackState; @@ -246,6 +295,45 @@ class ObjectManager { static void JSObjectFinalizerStatic( const v8::WeakCallbackInfo& data); + // A canary died: first-pass phantom callback, C++ bookkeeping only. + static void CanaryDiedStatic( + const v8::WeakCallbackInfo& data); + + static void CanaryGCEpilogue(v8::Isolate* isolate, v8::GCType type, + v8::GCCallbackFlags flags, void* data); + + // Registers a new canary: creates an extended instance's record, and + // hydrates a canary for an object that already has state. + void AdoptCanary(const v8::Local& object, uint32_t javaObjectID, + LinkKind kind); + + // The live canary state of holder, or null. + ObjectWeakCallbackState* CanaryOf(const v8::Local& holder); + + CanaryRecord* FindCanaryRecord(int javaObjectID); + + // A new canary for a JS-extended instance whose canary died; empty when id + // has no extended record or Java collected the object meanwhile. + v8::Local RebuildCanary(int javaObjectID); + + // Has the Java object table hold record's object strongly again; false (and + // the record dropped) when Java collected it. + bool EnsureJavaStrong(int javaObjectID, CanaryRecord* record); + + void EraseCanaryRecord(int javaObjectID); + + // Settles canaries collected since the last flush: Java holds the objects + // with records weakly and releases the others. False if the JNI call failed; + // the ids are queued again. + bool FlushCanaryDeaths(); + + std::unordered_map> m_canaryRecords; + std::vector m_pendingCanaryDeaths; + // Template of a canary rebuilt for a JS-extended instance. + v8::Persistent m_canaryTemplate; + bool m_deathInboxOpen = false; + int m_deathInboxRuntimeId = -1; + void JSObjectFinalizer(v8::Isolate* isolate, ObjectWeakCallbackState* callbackState); @@ -320,6 +408,8 @@ class ObjectManager { static jmethodID RELEASE_NATIVE_INSTANCE_METHOD_ID; static jmethodID RELEASE_IF_COLLECTED_METHOD_ID; + static jmethodID PROCESS_CANARY_BATCH_METHOD_ID; + static jmethodID STRENGTHEN_INSTANCE_METHOD_ID; v8::Persistent* m_poJsWrapperFunc; v8::Persistent m_jsWrapperTemplate; diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 4200895b5..3a5fa8fa4 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -737,7 +737,8 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, implementationObject->GetIdentityHash()); jclass clazz = env.FindClass(jniName); - m_objectManager->Link(jsInstance, javaObjectID, clazz); + m_objectManager->Link(jsInstance, javaObjectID, clazz, + ObjectManager::LinkKind::kExtended); } jint Runtime::GenerateNewObjectId(JNIEnv* env, jobject obj) { diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.cpp b/test-app/runtime/src/main/cpp/WrapperLifetime.cpp index ebb340e7b..1651d9c5d 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.cpp @@ -8,6 +8,8 @@ const char* WrapperLifetimeModeName(WrapperLifetimeMode mode) { switch (mode) { case WrapperLifetimeMode::kResurrecting: return "resurrecting"; + case WrapperLifetimeMode::kCanary: + return "canary"; } return "resurrecting"; } @@ -19,9 +21,9 @@ const char* WrapperLifetimeScopeName(WrapperLifetimeScope scope) { 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::wrapperLifetimeMode = mode == WrapperLifetimeModeName(WrapperLifetimeMode::kCanary) + ? WrapperLifetimeMode::kCanary + : WrapperLifetimeMode::kResurrecting; detail::wrapperLifetimeScope = scope == "all" ? WrapperLifetimeScope::kAll : WrapperLifetimeScope::kExtended; }); diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.h b/test-app/runtime/src/main/cpp/WrapperLifetime.h index 3ad20078c..c4c697efe 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -14,9 +14,17 @@ enum class WrapperLifetimeMode { // 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, + // Phantom callbacks, no resurrection: a wrapper in scope is a canary that + // dies with its JS references. Its JS properties are mirrored into a state + // object that lives until Java collects the object, and a canary built later + // for the same object gets them back (WrapperLifetimeCanary). + kCanary, }; enum class WrapperLifetimeScope { + // Canaries are instances Java can call into JS through: JS-extended + // classes and interface implementations. Other wrappers keep the + // resurrecting lifetime. kExtended, kAll, }; @@ -54,6 +62,15 @@ struct WrapperLifetimeStats { // 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; + // "canary" only: state objects created to hold JS properties. + uint64_t canaryStates = 0; + // "canary" only: state objects let go of because Java collected the object. + uint64_t canaryNativeDeaths = 0; + // "canary" only: writes to canaries the write handler saw. + uint64_t canaryInterceptedWrites = 0; + // "canary" only: canaries built anew for a JS-extended instance whose + // previous canary died while Java kept the object. + uint64_t canaryRebuilds = 0; }; } // namespace tns diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp new file mode 100644 index 000000000..f4d0ba814 --- /dev/null +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -0,0 +1,266 @@ +#include "WrapperLifetimeCanary.h" + +#include +#include +#include + +#include "EventLoop.h" +#include "ObjectManager.h" +#include "Runtime.h" + +using namespace v8; + +namespace tns { + +namespace { + +// Set while this thread copies properties between a canary and its state, so +// the handlers let those defines through. The copy runs no JS, so only its own +// defines reach a handler on this thread meanwhile. +thread_local bool copyingProperties_ = false; + +Local DescriptorField(Isolate* isolate, Local context, Local descriptor, + const char* name) { + Local value; + return descriptor + ->Get(context, String::NewFromUtf8(isolate, name).ToLocalChecked()) + .ToLocal(&value) + ? value + : Local(Undefined(isolate)); +} + +bool HasOwn(Local context, Local state, Local property) { + return state->HasOwnProperty(context, property).FromMaybe(false); +} + +// The object of `holder`'s prototype chain, `holder` included, with a real own +// `property`, interceptors skipped; empty if there is none. +Local OwnerOf(Local context, Local holder, Local property) { + Local object = holder; + while (!object->HasRealNamedProperty(context, property).FromMaybe(false)) { + Local prototype = object->GetPrototype(); + if (!prototype->IsObject()) { + return Local(); + } + object = prototype.As(); + } + return object; +} + +ObjectManager* ObjectManagerOf(Isolate* isolate) { + Runtime* runtime = Runtime::GetRuntime(isolate); + return runtime != nullptr ? runtime->GetObjectManager() : nullptr; +} + +// The handlers mirror: each copies its write into the state and declines, so +// V8 also applies it to the canary, where reads find a real own property and +// never call into C++. There is no getter, query, enumerator or descriptor +// callback for the same reason. The handlers are masking, so they also see +// names the prototype chain has. After the setter declines, V8 adds a new name +// to the canary without calling the definer, so the setter itself decides what +// becomes state. V8 calls the setter only when the canary is the receiver. +Intercepted Setter(Local property, Local value, + const PropertyCallbackInfo& info) { + // v8::Object::DefineOwnProperty reaches the setter, not the definer. + if (copyingProperties_) { + return Intercepted::kNo; + } + Isolate* isolate = info.GetIsolate(); + Local holder = info.Holder(); + ObjectManager* objectManager = ObjectManagerOf(isolate); + if (objectManager == nullptr || !objectManager->IsCanary(holder)) { + return Intercepted::kNo; + } + objectManager->CountCanaryWrite(); + Local context = isolate->GetCurrentContext(); + Local state; + if (objectManager->ExistingCanaryState(holder, &state) && HasOwn(context, state, property)) { + // Own on the state means own on the canary: a rewrite of a JS property. + if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + (void)state->Set(context, property, value); + } + return Intercepted::kNo; + } + // Searches the prototype chain too: absent there means a new name. + PropertyAttribute attributes; + if (holder->GetRealNamedPropertyAttributes(context, property).To(&attributes)) { + // V8 rejects a write to a read-only property and runs an accessor's setter: + // a Java field's (an accessor on its class's prototype), a JS one's, or one + // defined on the canary, which runs with the canary as `this` and so + // mirrors whatever it writes. None is state. + if ((attributes & ReadOnly) != 0) { + return Intercepted::kNo; + } + Local owner = OwnerOf(context, holder, property); + if (owner.IsEmpty()) { + return Intercepted::kNo; + } + Maybe accessor = owner->HasRealNamedCallbackProperty(context, property); + if (accessor.IsNothing() || accessor.FromJust()) { + return Intercepted::kNo; + } + } + if (!objectManager->CanaryStateForWrite(holder, &state)) { + return Intercepted::kNo; + } + if (!HasOwn(context, state, property)) { + (void)state->CreateDataProperty(context, property, value); + } else if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + (void)state->Set(context, property, value); + } + return Intercepted::kNo; +} + +Intercepted Deleter(Local property, const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + ObjectManager* objectManager = ObjectManagerOf(isolate); + Local state; + if (objectManager != nullptr && objectManager->ExistingCanaryState(info.Holder(), &state)) { + (void)state->Delete(isolate->GetCurrentContext(), property); + } + return Intercepted::kNo; +} + +// Object.defineProperty, define-semantics class fields and `super.x = v` on a +// receiver that lacks `x` reach here. +Intercepted Definer(Local property, const PropertyDescriptor& descriptor, + const PropertyCallbackInfo& info) { + if (copyingProperties_) { + return Intercepted::kNo; + } + Isolate* isolate = info.GetIsolate(); + ObjectManager* objectManager = ObjectManagerOf(isolate); + if (objectManager == nullptr || !objectManager->IsCanary(info.Holder())) { + return Intercepted::kNo; + } + objectManager->CountCanaryWrite(); + Local state; + if (objectManager->CanaryStateForWrite(info.Holder(), &state)) { + (void)state->DefineProperty(isolate->GetCurrentContext(), property, + const_cast(descriptor)); + } + return Intercepted::kNo; +} + +// Reports from WrapperLifetimeWatcher's thread for one runtime. +struct DeathInbox { + std::vector ids; + std::weak_ptr loop; + bool drainPosted = false; +}; + +std::mutex inboxesMutex_; +std::unordered_map inboxes_; + +void DrainOnRuntimeThread(int runtimeId) { + Runtime* runtime = Runtime::GetCurrentRuntime(); + if (runtime == nullptr || runtime->GetId() != runtimeId) { + return; + } + Isolate* isolate = runtime->GetIsolate(); + Locker locker(isolate); + Isolate::Scope isolateScope(isolate); + HandleScope handleScope(isolate); + runtime->GetObjectManager()->ReleaseCollectedCanaryStates(); +} + +} // namespace + +void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate, + TemplateKind kind) { + if (!InScope(kind == TemplateKind::kExtended)) { + return; + } + instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( + nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, Local(), + PropertyHandlerFlags::kNone)); +} + +void WrapperLifetimeCanary::CopyOwnProperties(Isolate* isolate, Local context, + Local from, Local to) { + HandleScope scope(isolate); + TryCatch tc(isolate); + bool wasCopying = copyingProperties_; + copyingProperties_ = true; + Local names; + if (from->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES, + IndexFilter::kSkipIndices, KeyConversionMode::kConvertToString) + .ToLocal(&names)) { + for (uint32_t i = 0; i < names->Length(); i++) { + Local name; + if (!names->Get(context, i).ToLocal(&name) || !name->IsName()) { + continue; + } + Local key = name.As(); + if (!from->HasRealNamedCallbackProperty(context, key).FromMaybe(true)) { + PropertyAttribute attributes; + Local value; + if (from->GetRealNamedPropertyAttributes(context, key).To(&attributes) && + from->GetRealNamedProperty(context, key).ToLocal(&value)) { + (void)to->DefineOwnProperty(context, key, value, attributes); + } + continue; + } + Local descriptorValue; + if (!from->GetOwnPropertyDescriptor(context, key).ToLocal(&descriptorValue) || + !descriptorValue->IsObject()) { + continue; + } + Local descriptor = descriptorValue.As(); + PropertyDescriptor accessor(DescriptorField(isolate, context, descriptor, "get"), + DescriptorField(isolate, context, descriptor, "set")); + accessor.set_enumerable( + DescriptorField(isolate, context, descriptor, "enumerable")->BooleanValue(isolate)); + accessor.set_configurable( + DescriptorField(isolate, context, descriptor, "configurable")->BooleanValue(isolate)); + (void)to->DefineProperty(context, key, accessor); + } + } + copyingProperties_ = wasCopying; +} + +void WrapperLifetimeCanary::OpenDeathInbox(int runtimeId, const std::shared_ptr& loop) { + std::lock_guard lock(inboxesMutex_); + inboxes_[runtimeId].loop = loop; +} + +void WrapperLifetimeCanary::CloseDeathInbox(int runtimeId) { + std::lock_guard lock(inboxesMutex_); + inboxes_.erase(runtimeId); +} + +void WrapperLifetimeCanary::NotifyCollected(int runtimeId, const int* ids, int count) { + std::shared_ptr loop; + { + std::lock_guard lock(inboxesMutex_); + auto it = inboxes_.find(runtimeId); + if (it == inboxes_.end()) { + return; + } + DeathInbox& inbox = it->second; + inbox.ids.insert(inbox.ids.end(), ids, ids + count); + if (inbox.drainPosted) { + return; + } + loop = inbox.loop.lock(); + inbox.drainPosted = loop != nullptr; + } + // Without a loop, or with the post dropped at shutdown, the next settle of + // collected canaries drains the inbox. + if (loop != nullptr) { + loop->PostInternal([runtimeId]() { DrainOnRuntimeThread(runtimeId); }); + } +} + +std::vector WrapperLifetimeCanary::TakeCollected(int runtimeId) { + std::vector ids; + std::lock_guard lock(inboxesMutex_); + auto it = inboxes_.find(runtimeId); + if (it != inboxes_.end()) { + ids.swap(it->second.ids); + it->second.drainPosted = false; + } + return ids; +} + +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h new file mode 100644 index 000000000..5b01c6ab4 --- /dev/null +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h @@ -0,0 +1,74 @@ +#ifndef WRAPPERLIFETIMECANARY_H_ +#define WRAPPERLIFETIMECANARY_H_ + +#include +#include + +#include "WrapperLifetime.h" +#include "v8.h" + +namespace tns { + +class EventLoop; + +// The canary wrapper lifetime mode (WrapperLifetimeMode::kCanary). +// +// A Java object's wrapper in scope is a canary: a phantom-weak JS object that +// dies with its JS references. A masking named interceptor with only a setter, +// deleter and definer mirrors every JS property written to a canary into a +// state object and then declines, so the property also lands on the canary and +// reads never leave V8. Writes that resolve to an inherited accessor (a Java +// field, a JS getter/setter) or a read-only property are not state. A canary +// built later for the same object gets the state's properties copied back. +// The state object is the source of truth. +// +// ObjectManager owns the records (state, and for JS-extended instances what a +// new canary needs: prototype, internal fields, implementation object). A +// record lives until Java collects its object, which +// com.tns.WrapperLifetimeWatcher reports from its own thread. It cannot be +// rooted only once the canary dies instead: a state reachable only through the +// canary is garbage in the same collection. The cost is that state referencing +// its own canary (a closure over `this`) keeps the canary, and through the +// Java object table its Java object, alive: the contract iOS documents too. +class WrapperLifetimeCanary { + public: + enum class TemplateKind { + // Instances may be JS-extended (extend(), interface implementations). + kExtended, + // Instances are plain wrappers: canaries only under scope "all". + kPlain, + }; + + static bool Enabled() { + return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary; + } + + // Whether a wrapper linked as `extended` is a canary. + static bool InScope(bool extended) { + return Enabled() && + (extended || GetWrapperLifetimeScope() == WrapperLifetimeScope::kAll); + } + + // Installs the write handlers on an instance template whose instances may be + // canaries. No-op unless the mode is canary and kind is in scope. + static void ConfigureInstanceTemplate(v8::Local instanceTemplate, + TemplateKind kind); + + // Copies `from`'s own string- and symbol-keyed properties onto `to`, with + // their attributes, the handlers of both set aside. + static void CopyOwnProperties(v8::Isolate* isolate, v8::Local context, + v8::Local from, v8::Local to); + + // Routes Java's reports of collected watched objects to runtimeId's thread. + // Registered by the runtime's thread, before its first watched object. + static void OpenDeathInbox(int runtimeId, const std::shared_ptr& loop); + static void CloseDeathInbox(int runtimeId); + // Any thread. + static void NotifyCollected(int runtimeId, const int* ids, int count); + // The runtime's thread: the ids reported since the last call. + static std::vector TakeCollected(int runtimeId); +}; + +} // namespace tns + +#endif /* WRAPPERLIFETIMECANARY_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 df36a92ef..c8adb6c14 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -1,5 +1,6 @@ #include "V8StringConstants.h" #include "Runtime.h" +#include "WrapperLifetimeCanary.h" #include "NativeScriptException.h" #include "CallbackHandlers.h" #include "ArgConverter.h" @@ -479,3 +480,12 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_invokeNonvirtualNative(JNIEnv* } return objectResult; } + +extern "C" JNIEXPORT void Java_com_tns_Runtime_notifyCanaryObjectsCollected(JNIEnv* env, jclass, jint runtimeId, jintArray ids, jint count) { + if (count <= 0) { + return; + } + std::vector values(count); + env->GetIntArrayRegion(ids, 0, count, values.data()); + WrapperLifetimeCanary::NotifyCollected(runtimeId, values.data(), count); +} 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 b72da8630..473ff9f7f 100644 --- a/test-app/runtime/src/main/cpp/js/ns-runtime.js +++ b/test-app/runtime/src/main/cpp/js/ns-runtime.js @@ -6,11 +6,13 @@ // per-isolate) are defined and validated on the native side, so this file // stays a thin, frozen surface. -const { setConfig, getConfig, escapeException, getWrapperLifetimeStats } = binding; +const { setConfig, getConfig, escapeException, getWrapperLifetimeStats, getWrapperClassCounts } = + binding; const { ObjectFreeze } = primordials; exports.setConfig = setConfig; exports.getConfig = getConfig; exports.escapeException = escapeException; exports.getWrapperLifetimeStats = getWrapperLifetimeStats; +exports.getWrapperClassCounts = getWrapperClassCounts; 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 22e41bb02..3195cf81d 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -174,7 +174,7 @@ private void readWrapperLifetime(Object config) { JSONObject object = (JSONObject) config; Object mode = object.opt(KnownKeys.WrapperLifetimeMode.getName()); if (mode != null) { - if ("resurrecting".equals(mode)) { + if ("resurrecting".equals(mode) || "canary".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\"."); diff --git a/test-app/runtime/src/main/java/com/tns/ObjectTable.java b/test-app/runtime/src/main/java/com/tns/ObjectTable.java index eec847e5b..a403c114b 100644 --- a/test-app/runtime/src/main/java/com/tns/ObjectTable.java +++ b/test-app/runtime/src/main/java/com/tns/ObjectTable.java @@ -1,5 +1,6 @@ package com.tns; +import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; /** @@ -221,6 +222,76 @@ void remove(int id) { } } + /** remove for ids[0..count), under one lock. */ + void remove(int[] ids, int count) { + if (count == 0) { + return; + } + synchronized (this) { + for (int i = 0; i < count; i++) { + removeLocked(ids[i]); + } + } + } + + /** + * The canary of each of ids[0..count) died while its object has JS state: hold the + * object through a WatchedRef queued on queue. Overwrites the id of every entry that is + * gone, or whose object was already collected (and is removed), with NO_ID. + */ + void weakenWatched(int[] ids, int count, int runtimeId, ReferenceQueue queue) { + if (count == 0) { + return; + } + synchronized (this) { + for (int i = 0; i < count; i++) { + int id = ids[i]; + Leaf leaf = leafFor(id); + Object value = leaf == null ? null : leaf.values[id & LEAF_MASK]; + if (value == null) { + ids[i] = NO_ID; + } else if (value instanceof WeakRef) { + if (((WeakRef) value).get() == null) { + removeLocked(id); + ids[i] = NO_ID; + } + } else { + leaf.values[id & LEAF_MASK] = new WatchedRef(value, queue, runtimeId, id); + } + } + } + } + + /** Holds id's object strongly again; false if there is no entry or it was collected. */ + boolean strengthen(int id) { + synchronized (this) { + Leaf leaf = leafFor(id); + Object value = leaf == null ? null : leaf.values[id & LEAF_MASK]; + if (!(value instanceof WeakRef)) { + return value != null; + } + Object referent = ((WeakRef) value).get(); + if (referent == null) { + removeLocked(id); + return false; + } + leaf.values[id & LEAF_MASK] = referent; + return true; + } + } + + /** Removes ref's entry if ref is still the entry for its id. */ + boolean removeWatched(WatchedRef ref) { + synchronized (this) { + Leaf leaf = leafFor(ref.id); + if (leaf == null || leaf.values[ref.id & LEAF_MASK] != ref) { + return false; + } + removeLocked(ref.id); + return true; + } + } + private void removeLocked(int id) { Leaf leaf = leafFor(id); int i = id & LEAF_MASK; @@ -246,10 +317,27 @@ int size() { // Distinguishes the table's own weak entries from a registered object that happens to be // a WeakReference. - private static final class WeakRef extends WeakReference { + private static class WeakRef extends WeakReference { WeakRef(Object referent) { super(referent); } + + WeakRef(Object referent, ReferenceQueue queue) { + super(referent, queue); + } + } + + // A weak entry whose object still has JS state (the canary wrapper lifetime mode): + // WrapperLifetimeWatcher reports its collection to the runtime that owns the state. + static final class WatchedRef extends WeakRef { + final int runtimeId; + final int id; + + WatchedRef(Object referent, ReferenceQueue queue, int runtimeId, int id) { + super(referent, queue); + this.runtimeId = runtimeId; + this.id = id; + } } private Leaf leafFor(int id) { 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 28ea30570..ce5946ada 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -313,7 +313,7 @@ private static synchronized void indexRuntime(int runtimeId, Runtime runtime) { runtimesById = index; } - private static Runtime runtimeForId(int runtimeId) { + static Runtime runtimeForId(int runtimeId) { Runtime[] index = runtimesById; if (runtimeId >= 0 && runtimeId < index.length) { return index[runtimeId]; @@ -1284,6 +1284,32 @@ private void processFinalizedBatch(int[] weaken, int weakenCount, int[] check, i } } + // The canary wrapper lifetime mode settles the canaries collected since the last batch: + // objects with JS state are held weakly and watched, the others are released. Overwrites + // the id of every object that is already gone with -1. + @RuntimeCallable + private void processCanaryBatch(int[] weaken, int weakenCount, int[] release, int releaseCount) { + objectTable.weakenWatched(weaken, weakenCount, runtimeId, WrapperLifetimeWatcher.queue()); + objectTable.remove(release, releaseCount); + if (logger.isEnabled()) { + logger.write("processCanaryBatch weakened=" + weakenCount + " released=" + releaseCount); + } + } + + // A canary is rebuilt for an object the canary mode held weakly. + @RuntimeCallable + private boolean strengthenInstance(int javaObjectID) { + return objectTable.strengthen(javaObjectID); + } + + boolean removeWatched(ObjectTable.WatchedRef ref) { + return objectTable.removeWatched(ref); + } + + // From WrapperLifetimeWatcher's thread: ids[0..count) of the runtime's watched objects + // were collected. Thread-safe; the runtime lets go of their JS state on its own thread. + static native void notifyCanaryObjectsCollected(int runtimeId, int[] ids, int count); + @RuntimeCallable private Object getJavaObjectByID(int javaObjectID) throws Exception { if (logger.isEnabled()) { diff --git a/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java b/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java new file mode 100644 index 000000000..cbf518ba9 --- /dev/null +++ b/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java @@ -0,0 +1,77 @@ +package com.tns; + +import android.util.Log; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.util.Arrays; + +/** + * Reports the collection of Java objects whose JS state the canary wrapper lifetime mode + * keeps (ObjectTable.WatchedRef) to the runtime that owns the state. One daemon thread for + * the process, started with the first watched object; it only removes the cleared entries + * and passes their ids on, never touching a runtime's V8 state. + */ +final class WrapperLifetimeWatcher { + private static ReferenceQueue queue; + + private WrapperLifetimeWatcher() { + } + + static synchronized ReferenceQueue queue() { + if (queue == null) { + queue = new ReferenceQueue<>(); + Thread thread = new Thread(WrapperLifetimeWatcher::run, "NativeScript lifetime watcher"); + thread.setDaemon(true); + thread.start(); + } + return queue; + } + + private static void run() { + ReferenceQueue watched = queue(); + int[] ids = new int[64]; + while (true) { + Reference next; + try { + next = watched.remove(); + } catch (InterruptedException e) { + return; + } + // Every reference collected so far, grouped by consecutive runtime. + int runtimeId = -1; + int count = 0; + for (; next != null; next = watched.poll()) { + if (!(next instanceof ObjectTable.WatchedRef)) { + continue; + } + ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next; + if (ref.runtimeId != runtimeId) { + notify(runtimeId, ids, count); + runtimeId = ref.runtimeId; + count = 0; + } + Runtime runtime = Runtime.runtimeForId(ref.runtimeId); + if (runtime == null || !runtime.removeWatched(ref)) { + continue; + } + if (count == ids.length) { + ids = Arrays.copyOf(ids, count * 2); + } + ids[count++] = ref.id; + } + notify(runtimeId, ids, count); + } + } + + private static void notify(int runtimeId, int[] ids, int count) { + if (count == 0) { + return; + } + try { + Runtime.notifyCanaryObjectsCollected(runtimeId, ids, count); + } catch (Throwable t) { + Log.w("JS", "Failed to report collected objects to runtime " + runtimeId, t); + } + } +} From e3d8b6788b2355cd518c22cdedca7bebccd261e6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 14:36:31 -0300 Subject: [PATCH 02/20] fix(runtime): canary review fixes - Remove the canary GC epilogue callback only if it was added: a bootstrap that fails before ObjectManager::Init unwinds through ReleaseAllRegistered. - Resolve a fresh Java->JS argument again under the lock in canary mode: a settle may have released its id after another thread wrapped and dropped the object. - Send every recorded id to the weakening batch, and treat a failed batch's ids as weak: Java may have weakened some before failing. - Stop AdoptCanary once its record is gone. - Keep the lifetime watcher alive across a failure to report. - Stop CallJSMethodNative overwriting a constructed instance's class with a local ref of com.tns.Runtime's class; registration already records the instance's class. - Docs: where states are let go of, what weakened counts, which wrappers refuse freeze, and class names. --- docs/ns-builtin-modules.md | 14 +++-- .../runtime/src/main/cpp/ArgConverter.cpp | 5 +- .../runtime/src/main/cpp/ObjectManager.cpp | 23 ++++++-- test-app/runtime/src/main/cpp/ObjectManager.h | 5 +- test-app/runtime/src/main/cpp/Runtime.cpp | 7 --- .../java/com/tns/WrapperLifetimeWatcher.java | 55 +++++++++++-------- 6 files changed, 68 insertions(+), 41 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index bd16623f5..ce8c3d15e 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -104,7 +104,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. | -| `getWrapperClassCounts()` | Per Java class name, the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). | +| `getWrapperClassCounts()` | Per Java class name (`` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). | | `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` @@ -195,8 +195,9 @@ every build on cold paths only: | `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object | In `"canary"` mode, `weakened` counts objects held weakly because their -canary died while they had JS state, and `collected` counts canaries whose -object had none, which Java no longer holds for JS. +canary died while they had a record (JS state, or a JS-extended instance), +and `collected` counts canaries whose object had none, which Java no longer +holds for JS. `"canary"` is the resurrection-free model the iOS runtime and the Node-API runtimes share. A wrapper in scope is a canary: a phantom-weak JS object that @@ -213,7 +214,9 @@ dies with its JS references. - **Java's side.** While a canary is alive, Java holds its object strongly. When it dies, Java holds an object with state weakly and releases any other. A thread watching those weak references tells the runtime when Java collects - an object, and its state is let go of on the runtime's thread. + an object, and its state is let go of under the isolate's lock: on the + runtime's thread, or on a thread calling in under + `enableMultithreadedJavascript`. - **JS-extended instances** (`extend()`, interface implementations, Java objects of those classes) keep a record from the moment they are registered, whether or not JS wrote to them, so that Java can still call into JS after @@ -232,7 +235,8 @@ a `WeakMap` value naming it) keeps the object alive, through Java, for as long as the cycle lasts; break such back references with a `WeakRef`. `getWrapperClassCounts()` shows which classes grow across a repeated journey. Other limits, as on iOS: `Object.freeze`, `seal` and `preventExtensions` throw -on a canary; index-keyed properties are not mirrored and die with the canary; +on a canary, and on any wrapper built from a template that carries the write +handler (every wrapper under `"all"`, released ones included); index-keyed properties are not mirrored and die with the canary; a write through an object whose prototype is a canary lands on that object. A canary built after another died is a new JS object, which `===` cannot tell because nothing kept the old one, but which keys `WeakMap`, `WeakSet`, diff --git a/test-app/runtime/src/main/cpp/ArgConverter.cpp b/test-app/runtime/src/main/cpp/ArgConverter.cpp index 20b8bf52a..1e2f39438 100644 --- a/test-app/runtime/src/main/cpp/ArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/ArgConverter.cpp @@ -1,4 +1,5 @@ #include "ArgConverter.h" +#include "WrapperLifetimeCanary.h" #include "JniLocalRef.h" #include "ObjectManager.h" #include "Util.h" @@ -150,7 +151,9 @@ void ArgConverter::ConvertJavaArgsToJsArgs(Isolate* isolate, JNIEnv* env, const // hint Java read without the isolate lock, or -1) and the class index above. auto hintedObjectID = static_cast(bits); auto classIndex = static_cast((bits >> 32) & 0x7fffffff); - if ((bits & JavaCallArgs::FreshArg) != 0 && + // In canary mode a settle may have released a fresh id whose canary another + // thread made and dropped before this call took the lock: resolve it again. + if ((bits & JavaCallArgs::FreshArg) != 0 && !WrapperLifetimeCanary::Enabled() && !objectManager->HasJsObject(hintedObjectID)) { JniLocalRef arg(env->GetObjectArrayElement(args.refs, i)); jsArg = objectManager->CreateJSWrapper(hintedObjectID, classIndex, arg); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 1d75bf6d1..7864417bf 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -118,6 +118,7 @@ void ObjectManager::Init(Isolate* isolate) { canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended); m_canaryTemplate.Reset(isolate, canaryTemplate); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); + m_canaryEpilogueAdded = true; } } @@ -613,7 +614,9 @@ void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObject m_canaryRecords.emplace(javaObjectID, std::move(created)); return; } - EnsureJavaStrong(javaObjectID, record); + if (!EnsureJavaStrong(javaObjectID, record)) { + return; + } if (!record->state.IsEmpty()) { auto context = m_isolate->GetCurrentContext(); if (context.IsEmpty()) { @@ -796,10 +799,10 @@ bool ObjectManager::FlushCanaryDeaths() { // A new canary was built since: the Java side stays strong. continue; } - CanaryRecord* record = FindCanaryRecord(id); - if (record == nullptr) { + // Weakening is idempotent: an id a failed batch already weakened is sent again. + if (FindCanaryRecord(id) == nullptr) { release.push_back(id); - } else if (!record->javaWeak) { + } else { weaken.push_back(id); } } @@ -836,6 +839,13 @@ bool ObjectManager::FlushCanaryDeaths() { raw->ExceptionDescribe(); raw->ExceptionClear(); } + // Java may have weakened some of them before failing: a canary rebuilt + // meanwhile must make its object strong again. + for (jint id : weaken) { + if (CanaryRecord* record = FindCanaryRecord(id)) { + record->javaWeak = true; + } + } m_pendingCanaryDeaths.insert(m_pendingCanaryDeaths.end(), deaths.begin(), deaths.end()); return false; } @@ -1182,8 +1192,11 @@ void ObjectManager::ReleaseAllRegistered() { m_pendingWeaken.clear(); m_pendingCheck.clear(); m_pendingCanaryDeaths.clear(); - if (WrapperLifetimeCanary::Enabled()) { + if (m_canaryEpilogueAdded) { m_isolate->RemoveGCEpilogueCallback(CanaryGCEpilogue, this); + m_canaryEpilogueAdded = false; + } + if (WrapperLifetimeCanary::Enabled()) { if (m_deathInboxOpen) { WrapperLifetimeCanary::CloseDeathInbox(m_deathInboxRuntimeId); m_deathInboxOpen = false; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index b71a14f1d..8b24c84b7 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -178,7 +178,9 @@ class ObjectManager { // The state object of a canary, created on its first write. bool CanaryStateForWrite(const v8::Local& holder, v8::Local* out); void CountCanaryWrite() { m_lifetimeStats.canaryInterceptedWrites++; } - // Lets go of the state of objects Java reported collected. Runtime thread. + // Lets go of the state of objects Java reported collected. Under the + // isolate's Locker: the runtime's thread, or a thread calling in under + // enableMultithreadedJavascript. void ReleaseCollectedCanaryStates(); struct ClassCounts { @@ -332,6 +334,7 @@ class ObjectManager { // Template of a canary rebuilt for a JS-extended instance. v8::Persistent m_canaryTemplate; bool m_deathInboxOpen = false; + bool m_canaryEpilogueAdded = false; int m_deathInboxRuntimeId = -1; void JSObjectFinalizer(v8::Isolate* isolate, diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 3a5fa8fa4..ea5ff7549 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -662,13 +662,6 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, throw NativeScriptException(ss.str()); } - if (isConstructor) { - DEBUG_WRITE( - "CallJSMethodNative: Updating linked instance with its real class"); - jclass instanceClass = env.GetObjectClass(obj); - m_objectManager->SetJavaClass(jsObject, instanceClass); - } - DEBUG_WRITE("CallJSMethodNative called jsObject=%d", jsObject->GetIdentityHash()); diff --git a/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java b/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java index cbf518ba9..01ee3ecc6 100644 --- a/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java +++ b/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java @@ -38,30 +38,41 @@ private static void run() { } catch (InterruptedException e) { return; } - // Every reference collected so far, grouped by consecutive runtime. - int runtimeId = -1; - int count = 0; - for (; next != null; next = watched.poll()) { - if (!(next instanceof ObjectTable.WatchedRef)) { - continue; - } - ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next; - if (ref.runtimeId != runtimeId) { - notify(runtimeId, ids, count); - runtimeId = ref.runtimeId; - count = 0; - } - Runtime runtime = Runtime.runtimeForId(ref.runtimeId); - if (runtime == null || !runtime.removeWatched(ref)) { - continue; - } - if (count == ids.length) { - ids = Arrays.copyOf(ids, count * 2); - } - ids[count++] = ref.id; + try { + ids = drain(watched, next, ids); + } catch (Throwable t) { + // The only watcher: losing it would leak every later collected object's state. + Log.w("JS", "Wrapper lifetime watcher failed to report collected objects", t); + } + } + } + + // Reports next and every reference already queued behind it; returns the id buffer to reuse. + private static int[] drain(ReferenceQueue watched, Reference next, int[] ids) { + // Every reference collected so far, grouped by consecutive runtime. + int runtimeId = -1; + int count = 0; + for (; next != null; next = watched.poll()) { + if (!(next instanceof ObjectTable.WatchedRef)) { + continue; + } + ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next; + if (ref.runtimeId != runtimeId) { + notify(runtimeId, ids, count); + runtimeId = ref.runtimeId; + count = 0; + } + Runtime runtime = Runtime.runtimeForId(ref.runtimeId); + if (runtime == null || !runtime.removeWatched(ref)) { + continue; + } + if (count == ids.length) { + ids = Arrays.copyOf(ids, count * 2); } - notify(runtimeId, ids, count); + ids[count++] = ref.id; } + notify(runtimeId, ids, count); + return ids; } private static void notify(int runtimeId, int[] ids, int count) { From 632bee06e12f284cb467dd9d07ca89a8f2183ec4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 15:28:30 -0300 Subject: [PATCH 03/20] test(runtime): a plain Java-held object keeps its canary state under scope all --- .../app/tests/testWrapperLifetimeModes.js | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js index 987e285cd..6f7dc818d 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -198,6 +198,29 @@ describe("Wrapper lifetime modes", function () { expect(Holder.held.child.toString()).toBe("child"); }); + // Under scope "all" a plain wrapper is a canary too: its state is rebuilt onto a + // wrapper made the usual way, and it keeps what it references (#2126's over-release). + it("keeps the state of a Java-held plain object and the Java objects it references, under scope all", function () { + if (!canary || scope !== "all") { + return; + } + var states = stats().canaryStates; + (function () { + var holder = new java.lang.StringBuilder("holder"); + holder.tag = "plain"; + holder.child = new java.lang.StringBuilder("child"); + Holder.held = holder; + })(); + expect(stats().canaryStates).toBe(states + 1); + collectBoth(); + collectJava(); + + var holder = Holder.held; + expect(holder.toString()).toBe("holder"); + expect(holder.tag).toBe("plain"); + expect(holder.child.toString()).toBe("child"); + }); + it("hands back a property that shadows a prototype member on a new wrapper", function () { (function () { var runnable = new java.lang.Runnable({ From 22810fcb761d4f8345c9ea4e383bd5880a3f977a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 15:36:29 -0300 Subject: [PATCH 04/20] docs(runtime): canary state is let go of before Java finalizes the object --- docs/ns-builtin-modules.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index ce8c3d15e..928491e57 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -234,7 +234,10 @@ its own object (a closure over `this`, `this.onTap = this.onTap.bind(this)`, a `WeakMap` value naming it) keeps the object alive, through Java, for as long as the cycle lasts; break such back references with a `WeakRef`. `getWrapperClassCounts()` shows which classes grow across a repeated journey. -Other limits, as on iOS: `Object.freeze`, `seal` and `preventExtensions` throw +Java reports a watched object's collection through a `WeakReference`, which +is cleared before finalization, so a JS-implemented method a `finalize()` +reaches finds a new canary without the object's state. Other limits, as on +iOS: `Object.freeze`, `seal` and `preventExtensions` throw on a canary, and on any wrapper built from a template that carries the write handler (every wrapper under `"all"`, released ones included); index-keyed properties are not mirrored and die with the canary; a write through an object whose prototype is a canary lands on that object. From 81c5e0f00e06823c0682d818740fd15152f367af Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 18:59:06 -0300 Subject: [PATCH 05/20] fix(runtime): report wrapper class counts as own properties --- test-app/runtime/src/main/cpp/NsBuiltinModules.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 230f3c2cc..c91f705df 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -193,13 +193,14 @@ void GetWrapperClassCountsCallback(const FunctionCallbackInfo& info) { for (const auto& [name, counts] : objectManager->GetWrapperClassCounts()) { Local entry = Object::New(isolate); auto set = [&](const char* key, uint64_t value) { - (void) entry->Set(context, ArgConverter::ConvertToV8String(isolate, key), - Number::New(isolate, static_cast(value))); + (void) entry->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, key), + Number::New(isolate, static_cast(value))); }; set("wrappers", counts.wrappers); set("canaries", counts.canaries); set("states", counts.states); - (void) result->Set(context, ArgConverter::ConvertToV8String(isolate, name), entry); + // A class name such as "__proto__" must stay an own property. + (void) result->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, name), entry); } info.GetReturnValue().Set(result); } From 22045de3659dda329605a35893d904dba60916eb Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 19:07:24 -0300 Subject: [PATCH 06/20] test(runtime): give the polling native-death spec a timeout past its deadline eventually() polls for up to 10 s; under Jasmine's default 5 s timeout a slow collection failed the spec on the timeout instead of its own deadline. --- .../app/src/main/assets/app/tests/testWrapperLifetimeModes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js index 6f7dc818d..81412e7b6 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -307,7 +307,7 @@ describe("Wrapper lifetime modes", function () { eventually(function () { return ref.get() === null && (!canary || stats().canaryNativeDeaths > deaths); }, done, "the Java object or its state stayed alive"); - }); + }, 20000); // The contract: the state is rooted until Java collects the object, so state that // references its own object keeps it alive. Break such back references with a WeakRef. From cbc0bee38206e3cb05e7105c0bf1fd1520e3e7f2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 07/20] fix(runtime): drop a Java call into an object Java no longer registers A Java->JS call on an object that was registered once but that Java has let go of since threw "Cannot find object id": Java clears a weak reference before it finalizes the object, so a finalize() that calls a JS-implemented method (a canary's watched reference, or a resurrecting wrapper's weakened one) ended the rest of the finalizer, and a Java callback into an object whose link was released threw the same way. Such calls have no target, and like the other Java->JS calls without one they are now logged and dropped, with the primitive default for a primitive return: in CallJSMethodNative when the caller passed an id, and in the posted single-threaded path when the binding had stamped one. A call on an object that was never registered (a superclass constructor calling an override before initInstance) still throws. --- .../app/tests/testWrapperLifetimeModes.js | 39 +++++++++++++++++++ .../com/tns/tests/FinalizeCallsOverride.java | 24 ++++++++++++ test-app/runtime/src/main/cpp/Runtime.cpp | 14 +++++++ .../src/main/java/com/tns/Runtime.java | 10 ++++- 4 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 test-app/app/src/main/java/com/tns/tests/FinalizeCallsOverride.java diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js index 81412e7b6..398256b35 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -309,6 +309,45 @@ describe("Wrapper lifetime modes", function () { }, done, "the Java object or its state stayed alive"); }, 20000); + it("drops a call finalize() makes into a JS-implemented method", function (done) { + var Finalizable = com.tns.tests.FinalizeCallsOverride; + var Override = Finalizable.extend({ + onFinalize: function () { + return 7; + } + }); + Finalizable.failure = null; + var finalized = Finalizable.finalized; + (function () { + var instance = new Override(); + instance.tag = "state"; + })(); + var deadline = Date.now() + 10000; + (function poll() { + // No runFinalization(): the finalizer needs the isolate this thread would hold. + gc(); + crossIntoJava(); + java.lang.Runtime.getRuntime().gc(); + if (Finalizable.finalized > finalized) { + var failure = Finalizable.failure; + expect(failure === null ? null : String(failure)).toBe(null); + if (canary) { + expect(Finalizable.lastResult).toBe(0); + } else { + // The resurrected wrapper may still be linked when Java finalizes. + expect([0, 7]).toContain(Finalizable.lastResult); + } + done(); + return; + } + if (Date.now() > deadline) { + done.fail("Java did not finalize the object"); + return; + } + setTimeout(poll, 50); + })(); + }, 20000); + // The contract: the state is rooted until Java collects the object, so state that // references its own object keeps it alive. Break such back references with a WeakRef. it("keeps an extended object whose JS state references it", function () { diff --git a/test-app/app/src/main/java/com/tns/tests/FinalizeCallsOverride.java b/test-app/app/src/main/java/com/tns/tests/FinalizeCallsOverride.java new file mode 100644 index 000000000..c6e454b1f --- /dev/null +++ b/test-app/app/src/main/java/com/tns/tests/FinalizeCallsOverride.java @@ -0,0 +1,24 @@ +package com.tns.tests; + +// finalize() calls a method a JS subclass overrides. Java clears its weak references to an +// object before finalizing it, so the runtime no longer knows the object by then. +public class FinalizeCallsOverride { + public static volatile int finalized; + public static volatile int lastResult = -1; + public static volatile Throwable failure; + + public int onFinalize() { + return -2; + } + + @Override + protected void finalize() throws Throwable { + try { + lastResult = onFinalize(); + } catch (Throwable t) { + failure = t; + } + finalized++; + super.finalize(); + } +} diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index ea5ff7549..ecc13559c 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -645,8 +645,22 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, jsObject = m_objectManager->GetLinkedJsObjectByJavaObject(javaObjectID); } if (jsObject.IsEmpty() && javaObject != nullptr) { + auto registeredAs = javaObjectID; javaObjectID = m_objectManager->FindObjectId(javaObject); if (javaObjectID == -1) { + if (registeredAs != -1) { + // Registered once, and Java has let go of it since (cleared its weak + // reference before finalizing it, or released its link). Dropped, not + // thrown: the caller is often a framework callback. Runtime.java + // defaults a primitive return. + __android_log_print( + ANDROID_LOG_WARN, "Warning", + "NativeScript discarding call to \"%s\": an instance of %s is no " + "longer registered with runtime id=%d", + ArgConverter::jstringToString(methodName).c_str(), + m_objectManager->GetClassName(javaObject).c_str(), m_id); + return nullptr; + } throw NativeScriptException("Cannot find object id for an instance of " + m_objectManager->GetClassName(javaObject)); } 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 ce5946ada..ccb36db41 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1719,6 +1719,7 @@ private Object dispatchCallJSMethodNative(final Object javaObject, int objectIdH final Object[] arr = new Object[3]; final boolean isCtor = isConstructor; + final boolean wasRegistered = objectIdHint != ObjectTable.NO_ID; Runnable r = new Runnable() { @Override @@ -1729,7 +1730,14 @@ public void run() { try { javaObjectID = resolveJavaObjectID(javaObject, methodName); } catch (NativeScriptException e) { - arr[2] = e; + if (wasRegistered) { + // As in native CallJSMethodNative: Java let go of a + // registered object, so there is nothing to call. + logDiscardedCall(methodName, describeInstance(javaObject) + + " is no longer registered with runtime id=" + getRuntimeId()); + } else { + arr[2] = e; + } return; } final PackagedArgs packagedArgs = packageArgs(tmpArgs); From 5cb827de02ed20dc9a3709fdcf7aecfe8ba1ee68 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 08/20] perf(runtime): keep the fresh-argument fast path in single-threaded canary mode The fast path that wraps an argument Java registered for the call without looking it up again was off for all of canary mode, because a canary settle can release a fresh id whose canary JS made and dropped before the conversion. Under enableMultithreadedJavascript another thread can do that before the call takes the isolate lock, so the path stays off there. On a single thread only JS the call itself runs (the method lookup) can, and the call now notices: ObjectManager counts the settles that released ids, the call records the count once it has settled what was pending, and a fresh id is trusted only while the count is unchanged. The runtime passes its multithreaded-JS flag to native at init for this. --- test-app/runtime/src/main/cpp/ArgConverter.cpp | 13 +++++++++---- test-app/runtime/src/main/cpp/ArgConverter.h | 2 ++ test-app/runtime/src/main/cpp/ObjectManager.cpp | 3 +++ test-app/runtime/src/main/cpp/ObjectManager.h | 13 +++++++++++++ test-app/runtime/src/main/cpp/Runtime.cpp | 2 ++ test-app/runtime/src/main/cpp/Runtime.h | 1 + test-app/runtime/src/main/cpp/com_tns_Runtime.cpp | 5 +++-- test-app/runtime/src/main/java/com/tns/Runtime.java | 4 ++-- 8 files changed, 35 insertions(+), 8 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ArgConverter.cpp b/test-app/runtime/src/main/cpp/ArgConverter.cpp index 1e2f39438..30f4ae86d 100644 --- a/test-app/runtime/src/main/cpp/ArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/ArgConverter.cpp @@ -151,10 +151,15 @@ void ArgConverter::ConvertJavaArgsToJsArgs(Isolate* isolate, JNIEnv* env, const // hint Java read without the isolate lock, or -1) and the class index above. auto hintedObjectID = static_cast(bits); auto classIndex = static_cast((bits >> 32) & 0x7fffffff); - // In canary mode a settle may have released a fresh id whose canary another - // thread made and dropped before this call took the lock: resolve it again. - if ((bits & JavaCallArgs::FreshArg) != 0 && !WrapperLifetimeCanary::Enabled() && - !objectManager->HasJsObject(hintedObjectID)) { + // In canary mode a settle may have released a fresh id whose canary JS made + // and dropped meanwhile: another thread's before this call took the lock + // (multithreaded JS), or one on this thread since the call started (JS run + // by the method lookup). Such an id is resolved again. + bool freshIdExact = (bits & JavaCallArgs::FreshArg) != 0 && + (!WrapperLifetimeCanary::Enabled() || + (!objectManager->MultithreadedJavascript() && + objectManager->CanaryReleaseCount() == args.canaryReleasesAtStart)); + if (freshIdExact && !objectManager->HasJsObject(hintedObjectID)) { JniLocalRef arg(env->GetObjectArrayElement(args.refs, i)); jsArg = objectManager->CreateJSWrapper(hintedObjectID, classIndex, arg); } else if (hintedObjectID != -1) { diff --git a/test-app/runtime/src/main/cpp/ArgConverter.h b/test-app/runtime/src/main/cpp/ArgConverter.h index 95d4fe294..868c13df2 100644 --- a/test-app/runtime/src/main/cpp/ArgConverter.h +++ b/test-app/runtime/src/main/cpp/ArgConverter.h @@ -26,6 +26,8 @@ struct JavaCallArgs { // Set once every argument has a JS value, so each object Java registered for this // call (FreshArg) has a wrapper and nothing is left to release if the call fails. mutable bool converted = false; + // ObjectManager::CanaryReleaseCount() once the call settled what was pending. + mutable uint64_t canaryReleasesAtStart = 0; // Set in an object argument's packed value when Java registered the object for this // call; the low half is then its exact id and the next 31 bits its class index. diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 7864417bf..6dfc84b83 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -827,6 +827,9 @@ bool ObjectManager::FlushCanaryDeaths() { JniLocalRef releaseArray(toJava(release)); bool failed = (!weaken.empty() && weakenArray.IsNull()) || (!release.empty() && releaseArray.IsNull()); + if (!release.empty()) { + m_canaryReleaseCount++; + } if (!failed) { AssertIsolateLocked(); raw->CallVoidMethod(m_javaRuntimeObject, PROCESS_CANARY_BATCH_METHOD_ID, diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 8b24c84b7..f81faf478 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -74,6 +74,15 @@ class ObjectManager { } } + // enableMultithreadedJavascript: Java may call in from threads other than + // the runtime's own. + void SetMultithreadedJavascript(bool value) { m_multithreadedJavascript = value; } + bool MultithreadedJavascript() const { return m_multithreadedJavascript; } + + // Canary settles that released Java ids. A Java object registered for a + // call keeps its id while this does not move, on a single JS thread. + uint64_t CanaryReleaseCount() const { return m_canaryReleaseCount; } + // Whether a wrapper was ever created for this id and not yet collected. bool HasJsObject(int javaObjectID) const { return m_idToObject.Find(javaObjectID) != nullptr; @@ -393,6 +402,10 @@ class ObjectManager { bool m_useGlobalRefs; + bool m_multithreadedJavascript = false; + + uint64_t m_canaryReleaseCount = 0; + static jclass JAVA_LANG_CLASS; static jmethodID GET_NAME_METHOD_ID; diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index ecc13559c..0bdf170b9 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -265,6 +265,7 @@ void Runtime::Init(JNIEnv* env, jstring filesPath, jstring nativeLibDir, ? UncaughtErrorPolicy::Throw : UncaughtErrorPolicy::Report; ConfigureWrapperLifetime(options.wrapperLifetimeMode, options.wrapperLifetimeScope); + m_objectManager->SetMultithreadedJavascript(options.multithreadedJavascript); DEBUG_WRITE("Initializing Telerik NativeScript"); @@ -637,6 +638,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, DEBUG_WRITE("CallJSMethodNative called javaObjectID=%d", javaObjectID); m_objectManager->FlushFinalizedBatchIfPending(); + args.canaryReleasesAtStart = m_objectManager->CanaryReleaseCount(); // javaObjectID may be a hint read without the isolate lock; resolve it exactly when it // does not name a linked wrapper. diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 762bfc76c..178894eb6 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -143,6 +143,7 @@ class Runtime { std::string uncaughtErrorPolicy; std::string wrapperLifetimeMode; std::string wrapperLifetimeScope; + bool multithreadedJavascript; }; 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/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index c8adb6c14..5a578dac9 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -96,7 +96,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 wrapperLifetimeMode, jstring wrapperLifetimeScope, 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, jboolean multithreadedJavascript, jstring callingDir, jint maxLogcatObjectSize, jboolean forceLog) { JEnv::EntryScope envScope(_env); try { Runtime::StartupOptions options{ @@ -106,7 +106,8 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jo discardUncaughtJsExceptions == JNI_TRUE, ArgConverter::jstringToString(uncaughtErrorPolicy), ArgConverter::jstringToString(wrapperLifetimeMode), - ArgConverter::jstringToString(wrapperLifetimeScope)}; + ArgConverter::jstringToString(wrapperLifetimeScope), + multithreadedJavascript == JNI_TRUE}; 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/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index ccb36db41..2ead5a216 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -39,7 +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 wrapperLifetimeMode, String wrapperLifetimeScope, boolean multithreadedJavascript, String callingDir, int maxLogcatObjectSize, boolean forceLog); private native void runModule(int runtimeId, String filePath) throws NativeScriptException; @@ -810,7 +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(), + appConfig.getWrapperLifetimeMode(), appConfig.getWrapperLifetimeScope(), multithreadedJavascript, callingJsDir, appConfig.getMaxLogcatObjectSize(), forceConsoleLog); if (logger.isEnabled()) { From c1863dd2893286032c835089158e079ceaeab860 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 09/20] fix(runtime): keep canary state reachable through watcher and call failures - The watcher thread returned on InterruptedException, ending the only thread that reports Java's collections for good; it now keeps going. - A throw partway through a drain lost the ids whose table entries it had already removed, so their state was never let go of; the ids gathered so far are now reported on the way out. - After a failed call, ReleaseUnwrappedArgs removed the Java entry of a fresh argument that had no wrapper, even when JS had meanwhile wrapped it (another thread under multithreaded JS, or the method lookup) and left a canary record: the record's state was then never released. Such an id is now left to the settle that owns it. getWrapperClassCounts() also loses a null check that could never hold. --- .../runtime/src/main/cpp/NsBuiltinModules.cpp | 6 +-- .../runtime/src/main/cpp/ObjectManager.cpp | 4 +- .../java/com/tns/WrapperLifetimeWatcher.java | 43 +++++++++++-------- 3 files changed, 28 insertions(+), 25 deletions(-) diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index c91f705df..a542afe1a 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -184,13 +184,9 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { void GetWrapperClassCountsCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - ObjectManager* objectManager = Runtime::GetObjectManager(isolate); - if (objectManager == nullptr) { - return; - } Local context = isolate->GetCurrentContext(); Local result = Object::New(isolate); - for (const auto& [name, counts] : objectManager->GetWrapperClassCounts()) { + for (const auto& [name, counts] : Runtime::GetObjectManager(isolate)->GetWrapperClassCounts()) { Local entry = Object::New(isolate); auto set = [&](const char* key, uint64_t value) { (void) entry->CreateDataProperty(context, ArgConverter::ConvertToV8String(isolate, key), diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 6dfc84b83..f419b56fa 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -427,7 +427,9 @@ void ObjectManager::ReleaseUnwrappedArgs(const JavaCallArgs& args) { continue; } auto javaObjectID = static_cast(values[i]); - if (HasJsObject(javaObjectID)) { + // A canary record means JS wrapped the id meanwhile (another thread, or + // the method lookup); its settle owns the Java entry, which may hold state. + if (HasJsObject(javaObjectID) || FindCanaryRecord(javaObjectID) != nullptr) { continue; } raw->CallVoidMethod(m_javaRuntimeObject, RELEASE_NATIVE_INSTANCE_METHOD_ID, diff --git a/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java b/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java index 01ee3ecc6..779748f39 100644 --- a/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java +++ b/test-app/runtime/src/main/java/com/tns/WrapperLifetimeWatcher.java @@ -36,7 +36,8 @@ private static void run() { try { next = watched.remove(); } catch (InterruptedException e) { - return; + // The only watcher: it outlives any interrupt. + continue; } try { ids = drain(watched, next, ids); @@ -52,26 +53,30 @@ private static int[] drain(ReferenceQueue watched, Reference next, in // Every reference collected so far, grouped by consecutive runtime. int runtimeId = -1; int count = 0; - for (; next != null; next = watched.poll()) { - if (!(next instanceof ObjectTable.WatchedRef)) { - continue; - } - ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next; - if (ref.runtimeId != runtimeId) { - notify(runtimeId, ids, count); - runtimeId = ref.runtimeId; - count = 0; - } - Runtime runtime = Runtime.runtimeForId(ref.runtimeId); - if (runtime == null || !runtime.removeWatched(ref)) { - continue; - } - if (count == ids.length) { - ids = Arrays.copyOf(ids, count * 2); + try { + for (; next != null; next = watched.poll()) { + if (!(next instanceof ObjectTable.WatchedRef)) { + continue; + } + ObjectTable.WatchedRef ref = (ObjectTable.WatchedRef) next; + if (ref.runtimeId != runtimeId) { + notify(runtimeId, ids, count); + runtimeId = ref.runtimeId; + count = 0; + } + Runtime runtime = Runtime.runtimeForId(ref.runtimeId); + if (runtime == null || !runtime.removeWatched(ref)) { + continue; + } + if (count == ids.length) { + ids = Arrays.copyOf(ids, count * 2); + } + ids[count++] = ref.id; } - ids[count++] = ref.id; + } finally { + // Ids already removed from their table are reported nowhere else. + notify(runtimeId, ids, count); } - notify(runtimeId, ids, count); return ids; } From 532d6813f9f9a36f6737c92fc976c3b73696fb5e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 10/20] docs(runtime): canary limits: finalize() calls, prototypes, #private, a cycle - A call a finalize() makes into a JS-implemented method is dropped with a warning; it does not find a new canary. - A prototype set later on a canary is not state and is not restored. - Native #private fields are branded on the canary and do not carry over. - Under "extended", a resurrecting plain wrapper whose JS property references a JS-extended object that references the wrapper's object back from Java keeps the canary alive for good. --- docs/ns-builtin-modules.md | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 928491e57..06045800f 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -234,13 +234,26 @@ its own object (a closure over `this`, `this.onTap = this.onTap.bind(this)`, a `WeakMap` value naming it) keeps the object alive, through Java, for as long as the cycle lasts; break such back references with a `WeakRef`. `getWrapperClassCounts()` shows which classes grow across a repeated journey. -Java reports a watched object's collection through a `WeakReference`, which -is cleared before finalization, so a JS-implemented method a `finalize()` -reaches finds a new canary without the object's state. Other limits, as on +Under `"extended"` the same goes for a plain wrapper, which keeps the +`"resurrecting"` lifetime: a JS property on it that references a JS-extended +object whose Java side references the plain wrapper's object back (a JS +`adapter` property on a `ViewPager` wrapper, where the adapter's observer +references the `ViewPager`) keeps the canary, and so both Java objects, alive +for good, because the resurrected wrapper lives as long as Java holds its +object. Keep such references off native views' JS properties. +Java clears a watched object's `WeakReference` before it finalizes the object, +so a call a `finalize()` makes into a JS-implemented method has no object to +run on: it is dropped with a warning in the log (a primitive return gets its +type's default value), as is a Java call into an object whose link was +released. Other limits, as on iOS: `Object.freeze`, `seal` and `preventExtensions` throw on a canary, and on any wrapper built from a template that carries the write handler (every wrapper under `"all"`, released ones included); index-keyed properties are not mirrored and die with the canary; -a write through an object whose prototype is a canary lands on that object. +a write through an object whose prototype is a canary lands on that object; +a prototype set later with `Object.setPrototypeOf` or `__proto__` is not +state, and a rebuilt canary has the prototype it was built with (V8 reports +no prototype change to the handler). Native `#private` fields are branded on +the canary and do not carry over. A canary built after another died is a new JS object, which `===` cannot tell because nothing kept the old one, but which keys `WeakMap`, `WeakSet`, `WeakRef` and `FinalizationRegistry` entries separately. From 396d6e0566c7ec6b3b1d9b34453c4d4cb53b55f9 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:21:51 -0300 Subject: [PATCH 11/20] fix(runtime): canary write handlers find no runtime instead of throwing ObjectManagerOf looked the runtime up with Runtime::GetRuntime, which throws when the isolate has none, so its null check never held and a missing runtime would have thrown a C++ exception out of a V8 interceptor with nothing to catch it. It now uses TryGetRuntime, and the handlers decline as their null checks intended. --- test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index f4d0ba814..eba13aec1 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -47,8 +47,9 @@ Local OwnerOf(Local context, Local holder, Local return object; } +// Null rather than a throw: nothing would catch it on the way out of V8. ObjectManager* ObjectManagerOf(Isolate* isolate) { - Runtime* runtime = Runtime::GetRuntime(isolate); + Runtime* runtime = Runtime::TryGetRuntime(isolate); return runtime != nullptr ? runtime->GetObjectManager() : nullptr; } From 1ae82ea7bd2e250edbcb78595c8e0db2363d0c11 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 23:39:19 -0300 Subject: [PATCH 12/20] perf(runtime): cheaper canary write handlers - The write handlers get their ObjectManager from the handler data instead of a thread-local and an isolate lookup, find the canary once per write, and reach its record through a pointer cached on the wrapper's registration (cleared when the record is erased and at teardown). A state made only of writable, enumerable, configurable data properties answers a rewrite with one lookup. - A write that resolves to a Java instance field runs the field's setter from the handler: class prototypes keep their instance fields' accessor data under a private key, so V8 does not look the name up again. Field accessors are non-configurable, so the table never goes stale. - A plain state is hydrated into a rebuilt canary with data defines. Phone (SM-G780G, release build, medians): an existing-name expando write on a canary 308 -> 235 ns, a new name 630 -> 487 ns, a Java field write one level up 748 -> 615 ns; under "all" a plain wrapper's expando write 309 -> 237 ns and field write 584 -> 478 ns. --- .../runtime/src/main/cpp/MetadataNode.cpp | 86 +++++++++-- test-app/runtime/src/main/cpp/MetadataNode.h | 15 ++ .../runtime/src/main/cpp/ObjectManager.cpp | 53 ++++++- test-app/runtime/src/main/cpp/ObjectManager.h | 39 +++++ .../src/main/cpp/WrapperLifetimeCanary.cpp | 138 ++++++++++++------ .../src/main/cpp/WrapperLifetimeCanary.h | 12 +- 6 files changed, 281 insertions(+), 62 deletions(-) diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 8e06fb6af..a1e1d3ed2 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -173,7 +173,8 @@ Local MetadataNode::GetOrCreateArrayObjectTemplate(Isolate* isol arrayObjectTemplate->SetHandler(IndexedPropertyHandlerConfiguration( ArrayIndexedPropertyGetterCallback, ArrayIndexedPropertySetterCallback)); WrapperLifetimeCanary::ConfigureInstanceTemplate( - arrayObjectTemplate, WrapperLifetimeCanary::TemplateKind::kPlain); + arrayObjectTemplate, WrapperLifetimeCanary::TemplateKind::kPlain, + Runtime::GetObjectManager(isolate)); cache->ArrayObjectTemplate = new Persistent(isolate, arrayObjectTemplate); @@ -614,6 +615,17 @@ void MetadataNode::StaticFieldSetterCallback(Local property, Local } } +void MetadataNode::SetInstanceField(Isolate* isolate, const Local& thiz, + const Local& value, FieldCallbackData* fieldData) { + auto &fieldCallbackMetadata = fieldData->metadata; + if (fieldCallbackMetadata.getIsFinal()) { + stringstream ss; + ss << "You are trying to set \"" << fieldCallbackMetadata.getName() << "\" which is a final field! Final fields can only be read."; + throw NativeScriptException(ss.str()); + } + CallbackHandlers::SetJavaField(isolate, thiz, value, fieldData); +} + void MetadataNode::FieldAccessorSetterCallback(const FunctionCallbackInfo& info) { auto value = info[0]; try { @@ -632,17 +644,38 @@ void MetadataNode::FieldAccessorSetterCallback(const FunctionCallbackInfo return; } - if (fieldCallbackMetadata.getIsFinal()) { - stringstream ss; - ss << "You are trying to set \"" << fieldCallbackMetadata.getName() << "\" which is a final field! Final fields can only be read."; - string exceptionMessage = ss.str(); + SetInstanceField(info.GetIsolate(), thiz, value, fieldCallbackData); + info.GetReturnValue().Set(value); + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception e) { + stringstream ss; + ss << "Error: c++ exception: " << e.what() << endl; + NativeScriptException nsEx(ss.str()); + nsEx.ReThrowToV8(); + } catch (...) { + NativeScriptException nsEx(std::string("Error: c++ exception!")); + nsEx.ReThrowToV8(); + } +} - throw NativeScriptException(exceptionMessage); - } else { - auto isolate = info.GetIsolate(); - CallbackHandlers::SetJavaField(isolate, thiz, value, fieldCallbackData); - info.GetReturnValue().Set(value); - } +bool MetadataNode::TrySetInstanceField(Isolate* isolate, Local context, + Local fieldTableKey, Local owner, + Local receiver, Local property, + Local value) { + Local table; + if (!owner->GetPrivate(context, fieldTableKey).ToLocal(&table) || !table->IsObject()) { + return false; + } + Local entry; + if (!table.As()->GetRealNamedProperty(context, property).ToLocal(&entry) || + !entry->IsExternal()) { + return false; + } + auto fieldData = static_cast( + entry.As()->Value(v8::kExternalPointerTypeTagDefault)); + try { + SetInstanceField(isolate, receiver, value, fieldData); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -654,6 +687,7 @@ void MetadataNode::FieldAccessorSetterCallback(const FunctionCallbackInfo NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } + return true; } void MetadataNode::PropertyAccessorGetterCallback(const FunctionCallbackInfo& info) { @@ -807,6 +841,12 @@ class MetadataNode::PrototypeTemplateFiller { NewNonConstructor(isolate, MetadataNode::FieldAccessorSetterCallback, fieldData), PropertyAttribute::DontDelete); m_addedNames.insert(name); + m_fields.emplace_back(name, fieldInfo); + } + + // The instance fields installed, in order. + const std::vector>& Fields() const { + return m_fields; } void FillPrototypeProperty(Isolate* isolate, const std::string& name, @@ -829,6 +869,7 @@ class MetadataNode::PrototypeTemplateFiller { private: Local m_protoTemplate; std::unordered_set m_addedNames; + std::vector> m_fields; }; void MetadataNode::SetInstanceMembers( @@ -1364,7 +1405,8 @@ Local MetadataNode::GetConstructorFunctionTemplate(Isolate* is WrapperLifetimeCanary::ConfigureInstanceTemplate( ctorFuncTemplate->InstanceTemplate(), isInterface ? WrapperLifetimeCanary::TemplateKind::kExtended - : WrapperLifetimeCanary::TemplateKind::kPlain); + : WrapperLifetimeCanary::TemplateKind::kPlain, + Runtime::GetObjectManager(isolate)); Local baseCtorFunc; Local baseFuncTemplate; @@ -1401,6 +1443,23 @@ Local MetadataNode::GetConstructorFunctionTemplate(Isolate* is auto context = isolate->GetCurrentContext(); auto ctorFunc = ctorFuncTemplate->GetFunction(context).ToLocalChecked(); + if (WrapperLifetimeCanary::Enabled() && !protoFiller.Fields().empty()) { + // For the canary write handler, which runs a field's setter itself. + auto fieldTableKey = Runtime::GetObjectManager(isolate)->InstanceFieldTableKey(); + Local prototype; + if (!fieldTableKey.IsEmpty() && + ctorFunc->Get(context, V8StringConstants::GetPrototype(isolate)).ToLocal(&prototype) && + prototype->IsObject()) { + auto table = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); + for (const auto& [name, fieldData] : protoFiller.Fields()) { + (void) table->CreateDataProperty( + context, NewMemberName(isolate, name), + External::New(isolate, fieldData, v8::kExternalPointerTypeTagDefault)); + } + (void) prototype.As()->SetPrivate(context, fieldTableKey, table); + } + } + auto origin = Constants::APP_ROOT_FOLDER_PATH + node->m_name; auto wrappedCtorFunc = Wrap(isolate, ctorFunc, node->m_treeNode->name, origin, true /* isCtorFunc */); @@ -2319,7 +2378,8 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfoInstanceTemplate()->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); WrapperLifetimeCanary::ConfigureInstanceTemplate( - extendFuncTemplate->InstanceTemplate(), WrapperLifetimeCanary::TemplateKind::kExtended); + extendFuncTemplate->InstanceTemplate(), WrapperLifetimeCanary::TemplateKind::kExtended, + Runtime::GetObjectManager(isolate)); auto context = isolate->GetCurrentContext(); auto extendFunc = extendFuncTemplate->GetFunction(context).ToLocalChecked(); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index 89272bca7..e60e44570 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -37,6 +37,18 @@ namespace tns { class MetadataNode { public: + /* + * Canary mode: runs the Java instance field setter the class prototype + * `owner` carries for `property`, as a write through `receiver` would. + * False, and nothing done, when owner carries no runtime-installed field + * accessor for property. Field accessors are non-configurable, so one + * found on owner is still the runtime's. + */ + static bool TrySetInstanceField(v8::Isolate* isolate, v8::Local context, + v8::Local fieldTableKey, + v8::Local owner, v8::Local receiver, + v8::Local property, v8::Local value); + static void Init(v8::Isolate* isolate); static void BuildMetadata(const std::string& filesPath); @@ -207,6 +219,9 @@ class MetadataNode { static void FieldAccessorGetterCallback(const v8::FunctionCallbackInfo& info); static void FieldAccessorSetterCallback(const v8::FunctionCallbackInfo& info); + // Throws NativeScriptException. + static void SetInstanceField(v8::Isolate* isolate, const v8::Local& thiz, + const v8::Local& value, FieldCallbackData* fieldData); static void StaticFieldGetterCallback(v8::Local property, const v8::PropertyCallbackInfo& info); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index f419b56fa..a22d0e3ef 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -115,8 +115,9 @@ void ObjectManager::Init(Isolate* isolate) { auto canaryTemplate = ObjectTemplate::New(isolate); canaryTemplate->SetInternalFieldCount(static_cast(MetadataNodeKeys::END)); WrapperLifetimeCanary::ConfigureInstanceTemplate( - canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended); + canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended, this); m_canaryTemplate.Reset(isolate, canaryTemplate); + m_instanceFieldTableKey.Reset(isolate, Private::New(isolate)); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); m_canaryEpilogueAdded = true; } @@ -586,6 +587,7 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, if (state->canary) { AdoptCanary(object, javaObjectID, kind); + state->record = FindCanaryRecord(javaObjectID); } } @@ -624,8 +626,8 @@ void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObject if (context.IsEmpty()) { context = Runtime::GetRuntime(m_isolate)->GetContext(); } - WrapperLifetimeCanary::CopyOwnProperties(m_isolate, context, - record->state.Get(m_isolate), object); + WrapperLifetimeCanary::CopyOwnProperties(this, context, record->state.Get(m_isolate), object, + !record->stateNotPlain); } } @@ -638,6 +640,9 @@ ObjectManager::CanaryRecord* ObjectManager::FindCanaryRecord(int javaObjectID) { } void ObjectManager::EraseCanaryRecord(int javaObjectID) { + if (auto live = m_idToObject.Find(javaObjectID)) { + live->record = nullptr; + } m_canaryRecords.erase(javaObjectID); } @@ -741,12 +746,52 @@ bool ObjectManager::CanaryStateForWrite(const Local& holder, Localrecord = record; record->state.Reset(m_isolate, fresh); m_lifetimeStats.canaryStates++; *out = fresh; return true; } +ObjectManager::CanaryHandle* ObjectManager::CanaryOfInstance(const Local& holder) { + int id = LinkedIdOf(holder); + if (id == -1) { + return nullptr; + } + auto state = m_idToObject.Find(id); + // A `super` object shares its owner's id but is not the canary. + if (state == nullptr || !state->canary || !state->linked || *state->target != holder) { + return nullptr; + } + return state; +} + +Local ObjectManager::StateOf(CanaryHandle* canary) { + CanaryRecord* record = canary->record; + return record != nullptr && !record->state.IsEmpty() ? record->state.Get(m_isolate) + : Local(); +} + +bool ObjectManager::StateIsPlain(CanaryHandle* canary) { + return canary->record == nullptr || !canary->record->stateNotPlain; +} + +void ObjectManager::SetStateNotPlain(CanaryHandle* canary) { + if (canary->record != nullptr) { + canary->record->stateNotPlain = true; + } +} + +Local ObjectManager::StateForWrite(CanaryHandle* canary) { + Local existing = StateOf(canary); + if (!existing.IsEmpty()) { + return existing; + } + Local state; + return CanaryStateForWrite(Local::New(m_isolate, *canary->target), &state) ? state + : Local(); +} + void ObjectManager::CanaryDiedStatic( const WeakCallbackInfo& data) { ObjectWeakCallbackState* state = data.GetParameter(); @@ -1207,8 +1252,10 @@ void ObjectManager::ReleaseAllRegistered() { m_deathInboxOpen = false; } } + m_idToObject.ForEach([](ObjectWeakCallbackState* state) { state->record = nullptr; }); m_canaryRecords.clear(); m_canaryTemplate.Reset(); + m_instanceFieldTableKey.Reset(); auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index f81faf478..34b5c1ee4 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -187,6 +187,37 @@ class ObjectManager { // The state object of a canary, created on its first write. bool CanaryStateForWrite(const v8::Local& holder, v8::Local* out); void CountCanaryWrite() { m_lifetimeStats.canaryInterceptedWrites++; } + + // What the write handlers need of one live canary. + private: + struct ObjectWeakCallbackState; + + public: + using CanaryHandle = ObjectWeakCallbackState; + // holder's live canary registration, or null. holder must be an instance of + // a template with the canary handlers (it has the Metadata field). + CanaryHandle* CanaryOfInstance(const v8::Local& holder); + // The canary's state object, empty if it has none yet. + v8::Local StateOf(CanaryHandle* canary); + // Whether every property of the canary's state is a writable, enumerable, + // configurable data property: only a define can make one otherwise. + bool StateIsPlain(CanaryHandle* canary); + void SetStateNotPlain(CanaryHandle* canary); + // The canary's state object, created on its first write. + v8::Local StateForWrite(CanaryHandle* canary); + + // Set while the runtime copies properties between a canary and its state, so + // the handlers let those defines through. The copy runs no JS, and only the + // thread holding the isolate's lock touches this. + // Canary mode: the private key under which a class prototype keeps its + // instance field accessors' data (MetadataNode::TrySetInstanceField); empty + // in other modes. + v8::Local InstanceFieldTableKey() { + return m_instanceFieldTableKey.Get(m_isolate); + } + + bool CopyingCanaryProperties() const { return m_copyingCanaryProperties; } + void SetCopyingCanaryProperties(bool copying) { m_copyingCanaryProperties = copying; } // Lets go of the state of objects Java reported collected. Under the // isolate's Locker: the runtime's thread, or a thread calling in under // enableMultithreadedJavascript. @@ -207,6 +238,8 @@ class ObjectManager { private: static void InitializeJNI(); + struct CanaryRecord; + // The registration of one linked Java object id, reached from the wrapper's JsInfo // field through m_idToObject. struct ObjectWeakCallbackState { @@ -239,6 +272,8 @@ class ObjectManager { bool reacquired = false; // A canary: a phantom handle, and no resurrection. bool canary = false; + // A canary's record, cached; EraseCanaryRecord clears it. + CanaryRecord* record = nullptr; }; // Canary mode: what outlives the canaries of one Java object id, until Java @@ -257,6 +292,8 @@ class ObjectManager { jclass clazz = nullptr; // The Java object table holds the object through a watched weak reference. bool javaWeak = false; + // A define reached the state with an accessor or non-default attributes. + bool stateNotPlain = false; }; using JSInstanceInfo = ObjectWeakCallbackState; @@ -342,9 +379,11 @@ class ObjectManager { std::vector m_pendingCanaryDeaths; // Template of a canary rebuilt for a JS-extended instance. v8::Persistent m_canaryTemplate; + bool m_copyingCanaryProperties = false; bool m_deathInboxOpen = false; bool m_canaryEpilogueAdded = false; int m_deathInboxRuntimeId = -1; + v8::Persistent m_instanceFieldTableKey; void JSObjectFinalizer(v8::Isolate* isolate, ObjectWeakCallbackState* callbackState); diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index eba13aec1..ee73d56b4 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -5,6 +5,8 @@ #include #include "EventLoop.h" +#include "MetadataNode.h" +#include "NativeScriptAssert.h" #include "ObjectManager.h" #include "Runtime.h" @@ -14,11 +16,6 @@ namespace tns { namespace { -// Set while this thread copies properties between a canary and its state, so -// the handlers let those defines through. The copy runs no JS, so only its own -// defines reach a handler on this thread meanwhile. -thread_local bool copyingProperties_ = false; - Local DescriptorField(Isolate* isolate, Local context, Local descriptor, const char* name) { Local value; @@ -47,10 +44,34 @@ Local OwnerOf(Local context, Local holder, Local return object; } -// Null rather than a throw: nothing would catch it on the way out of V8. -ObjectManager* ObjectManagerOf(Isolate* isolate) { - Runtime* runtime = Runtime::TryGetRuntime(isolate); - return runtime != nullptr ? runtime->GetObjectManager() : nullptr; +ObjectManager* ObjectManagerOf(Local data) { + return static_cast( + data.As()->Value(v8::kExternalPointerTypeTagDefault)); +} + +// Mirrors a write of a name the state already has; false if the state lacks it. +bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* canary, + Local context, Local state, Local property, + Local value) { + if (!objectManager->StateIsPlain(canary)) { + if (!HasOwn(context, state, property)) { + return false; + } + if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + (void)state->Set(context, property, value); + } + return true; + } + // A null-prototype object of data properties: one lookup answers both + // whether it is own and whether it is writable. + PropertyAttribute attributes; + if (!state->GetRealNamedPropertyAttributes(context, property).To(&attributes)) { + return false; + } + if ((attributes & ReadOnly) == 0) { + (void)state->Set(context, property, value); + } + return true; } // The handlers mirror: each copies its write into the state and declines, so @@ -62,24 +83,23 @@ ObjectManager* ObjectManagerOf(Isolate* isolate) { // becomes state. V8 calls the setter only when the canary is the receiver. Intercepted Setter(Local property, Local value, const PropertyCallbackInfo& info) { + ObjectManager* objectManager = ObjectManagerOf(info.Data()); // v8::Object::DefineOwnProperty reaches the setter, not the definer. - if (copyingProperties_) { + if (objectManager->CopyingCanaryProperties()) { return Intercepted::kNo; } - Isolate* isolate = info.GetIsolate(); Local holder = info.Holder(); - ObjectManager* objectManager = ObjectManagerOf(isolate); - if (objectManager == nullptr || !objectManager->IsCanary(holder)) { + ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(holder); + if (canary == nullptr) { return Intercepted::kNo; } objectManager->CountCanaryWrite(); + Isolate* isolate = info.GetIsolate(); Local context = isolate->GetCurrentContext(); - Local state; - if (objectManager->ExistingCanaryState(holder, &state) && HasOwn(context, state, property)) { - // Own on the state means own on the canary: a rewrite of a JS property. - if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { - (void)state->Set(context, property, value); - } + Local state = objectManager->StateOf(canary); + // Own on the state means own on the canary: a rewrite of a JS property. + if (!state.IsEmpty() && + RewriteState(objectManager, canary, context, state, property, value)) { return Intercepted::kNo; } // Searches the prototype chain too: absent there means a new name. @@ -96,15 +116,27 @@ Intercepted Setter(Local property, Local value, if (owner.IsEmpty()) { return Intercepted::kNo; } + // A Java field's setter runs from here, sparing V8 a second lookup. + if (owner != holder && + MetadataNode::TrySetInstanceField(isolate, context, objectManager->InstanceFieldTableKey(), + owner, holder, property, value)) { + return Intercepted::kYes; + } Maybe accessor = owner->HasRealNamedCallbackProperty(context, property); if (accessor.IsNothing() || accessor.FromJust()) { return Intercepted::kNo; } } - if (!objectManager->CanaryStateForWrite(holder, &state)) { - return Intercepted::kNo; - } - if (!HasOwn(context, state, property)) { + if (state.IsEmpty()) { + state = objectManager->StateForWrite(canary); + if (state.IsEmpty()) { + return Intercepted::kNo; + } + (void)state->CreateDataProperty(context, property, value); + } else if (objectManager->StateIsPlain(canary)) { + // RewriteState found the name absent from the state. + (void)state->CreateDataProperty(context, property, value); + } else if (!HasOwn(context, state, property)) { (void)state->CreateDataProperty(context, property, value); } else if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { (void)state->Set(context, property, value); @@ -113,11 +145,14 @@ Intercepted Setter(Local property, Local value, } Intercepted Deleter(Local property, const PropertyCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - ObjectManager* objectManager = ObjectManagerOf(isolate); - Local state; - if (objectManager != nullptr && objectManager->ExistingCanaryState(info.Holder(), &state)) { - (void)state->Delete(isolate->GetCurrentContext(), property); + ObjectManager* objectManager = ObjectManagerOf(info.Data()); + ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(info.Holder()); + if (canary == nullptr) { + return Intercepted::kNo; + } + Local state = objectManager->StateOf(canary); + if (!state.IsEmpty()) { + (void)state->Delete(info.GetIsolate()->GetCurrentContext(), property); } return Intercepted::kNo; } @@ -126,18 +161,24 @@ Intercepted Deleter(Local property, const PropertyCallbackInfo& i // receiver that lacks `x` reach here. Intercepted Definer(Local property, const PropertyDescriptor& descriptor, const PropertyCallbackInfo& info) { - if (copyingProperties_) { + ObjectManager* objectManager = ObjectManagerOf(info.Data()); + if (objectManager->CopyingCanaryProperties()) { return Intercepted::kNo; } - Isolate* isolate = info.GetIsolate(); - ObjectManager* objectManager = ObjectManagerOf(isolate); - if (objectManager == nullptr || !objectManager->IsCanary(info.Holder())) { + ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(info.Holder()); + if (canary == nullptr) { return Intercepted::kNo; } objectManager->CountCanaryWrite(); - Local state; - if (objectManager->CanaryStateForWrite(info.Holder(), &state)) { - (void)state->DefineProperty(isolate->GetCurrentContext(), property, + Local state = objectManager->StateForWrite(canary); + if (!state.IsEmpty()) { + bool plain = descriptor.has_value() && descriptor.has_writable() && descriptor.writable() && + descriptor.has_enumerable() && descriptor.enumerable() && + descriptor.has_configurable() && descriptor.configurable(); + if (!plain) { + objectManager->SetStateNotPlain(canary); + } + (void)state->DefineProperty(info.GetIsolate()->GetCurrentContext(), property, const_cast(descriptor)); } return Intercepted::kNo; @@ -168,21 +209,27 @@ void DrainOnRuntimeThread(int runtimeId) { } // namespace void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local instanceTemplate, - TemplateKind kind) { + TemplateKind kind, + ObjectManager* objectManager) { if (!InScope(kind == TemplateKind::kExtended)) { return; } + NS_CHECK(objectManager != nullptr); + Isolate* isolate = Isolate::GetCurrent(); instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( - nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, Local(), + nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, + External::New(isolate, objectManager, v8::kExternalPointerTypeTagDefault), PropertyHandlerFlags::kNone)); } -void WrapperLifetimeCanary::CopyOwnProperties(Isolate* isolate, Local context, - Local from, Local to) { +void WrapperLifetimeCanary::CopyOwnProperties(ObjectManager* objectManager, + Local context, Local from, + Local to, bool plain) { + Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); TryCatch tc(isolate); - bool wasCopying = copyingProperties_; - copyingProperties_ = true; + bool wasCopying = objectManager->CopyingCanaryProperties(); + objectManager->SetCopyingCanaryProperties(true); Local names; if (from->GetPropertyNames(context, KeyCollectionMode::kOwnOnly, PropertyFilter::ALL_PROPERTIES, IndexFilter::kSkipIndices, KeyConversionMode::kConvertToString) @@ -193,6 +240,13 @@ void WrapperLifetimeCanary::CopyOwnProperties(Isolate* isolate, Local c continue; } Local key = name.As(); + if (plain) { + Local value; + if (from->Get(context, key).ToLocal(&value)) { + (void)to->CreateDataProperty(context, key, value); + } + continue; + } if (!from->HasRealNamedCallbackProperty(context, key).FromMaybe(true)) { PropertyAttribute attributes; Local value; @@ -217,7 +271,7 @@ void WrapperLifetimeCanary::CopyOwnProperties(Isolate* isolate, Local c (void)to->DefineProperty(context, key, accessor); } } - copyingProperties_ = wasCopying; + objectManager->SetCopyingCanaryProperties(wasCopying); } void WrapperLifetimeCanary::OpenDeathInbox(int runtimeId, const std::shared_ptr& loop) { diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h index 5b01c6ab4..840319f54 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h @@ -10,6 +10,7 @@ namespace tns { class EventLoop; +class ObjectManager; // The canary wrapper lifetime mode (WrapperLifetimeMode::kCanary). // @@ -52,12 +53,15 @@ class WrapperLifetimeCanary { // Installs the write handlers on an instance template whose instances may be // canaries. No-op unless the mode is canary and kind is in scope. static void ConfigureInstanceTemplate(v8::Local instanceTemplate, - TemplateKind kind); + TemplateKind kind, ObjectManager* objectManager); // Copies `from`'s own string- and symbol-keyed properties onto `to`, with - // their attributes, the handlers of both set aside. - static void CopyOwnProperties(v8::Isolate* isolate, v8::Local context, - v8::Local from, v8::Local to); + // their attributes, the handlers of both set aside. `plain` promises that + // every property of `from` is a writable, enumerable, configurable data + // property. + static void CopyOwnProperties(ObjectManager* objectManager, v8::Local context, + v8::Local from, v8::Local to, + bool plain); // Routes Java's reports of collected watched objects to runtimeId's thread. // Registered by the runtime's thread, before its first watched object. From 815a7df7a2aab6e455ca857a46d57db8e370c5a7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 01:20:22 -0300 Subject: [PATCH 13/20] perf(runtime): rebuild a canary by cloning a shell of its first registration A JS-extended object's canary record kept the first canary's prototype, CallSuper and Metadata fields and implementation object as four Globals, and every rebuild made a new object from a template shared by all classes, then set its prototype, internal fields and implementation object one by one. The record now keeps one shell instead: an unlinked instance of the template the object was constructed from, with the first canary's prototype, internal fields and implementation object, built when the object is registered. A rebuild clones the shell, links the clone and copies the state's properties onto it as before. The shell is never a canary and never reaches JS, so nothing a canary picked up later (JS properties, #private brands, its JsInfo link) is copied. The extend(), interface and Java-constructed (createJSInstanceNative) paths pass their instance template to Link for this. Measured on a phone for a dead-canary Java->JS call into an interface implementation, the steps a rebuild no longer takes cost NewInstance 0.44 us, SetPrototype 1.5 us, internal fields plus the implementation-object private 1.2 us. Registering an extended object now builds its shell up front (NewInstance, a SetPrototype for an interface implementation, the fields and the private) whether or not it is ever rebuilt; that cost was not measured. A clone has its shell's map, so rebuilt canaries of one object share a map with each other and with the first canary instead of forming a family of their own off the shared template. Adding the state's properties should then follow the transitions the first rebuild made rather than create maps (hydration was measured at 6.0 us for 4 properties, dominated by map creation behind an interface implementation's per-instance prototype); that is expected, not measured. --- .../app/tests/testWrapperLifetimeModes.js | 101 ++++++++++++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 6 +- .../runtime/src/main/cpp/CallbackHandlers.h | 3 +- .../runtime/src/main/cpp/MetadataNode.cpp | 37 ++++--- test-app/runtime/src/main/cpp/MetadataNode.h | 10 +- .../runtime/src/main/cpp/ObjectManager.cpp | 90 +++++++++------- test-app/runtime/src/main/cpp/ObjectManager.h | 26 +++-- test-app/runtime/src/main/cpp/Runtime.cpp | 5 +- .../src/main/cpp/WrapperLifetimeCanary.h | 6 +- 9 files changed, 212 insertions(+), 72 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js index 398256b35..d93deb238 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -158,6 +158,107 @@ describe("Wrapper lifetime modes", function () { expect(java.lang.String.valueOf(Holder.held)).toBe("made:7"); }); + it("rebuilds an interface implementation with its prototype, Java methods and state", function () { + var rebuilds = stats().canaryRebuilds; + // Nothing the methods' closures reach may hold the object: that would keep it alive. + var planted = (function () { + var runnable = new java.lang.Runnable({ + run: function () { + this.ran = (this.ran || 0) + 1; + } + }); + runnable.tag = "kept"; + runnable.dropped = true; + delete runnable.dropped; + Holder.held = runnable; + return { prototype: Object.getPrototypeOf(runnable), thread: new java.lang.Thread(runnable) }; + })(); + collectBoth(); + collectJava(); + + // Java calls into the object while no canary is alive. + planted.thread.run(); + var runnable = Holder.held; + if (canary) { + expect(stats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + expect(Object.getPrototypeOf(runnable)).toBe(planted.prototype); + expect(runnable instanceof java.lang.Runnable).toBe(true); + expect(Object.keys(runnable).sort()).toEqual(["ran", "tag"]); + expect(runnable.ran).toBe(1); + expect(typeof runnable.hashCode()).toBe("number"); + expect(runnable.equals(Holder.held)).toBe(true); + runnable.run(); + expect(runnable.ran).toBe(2); + }); + + it("rebuilds an extend() instance with its class, super calls and state, more than once", function () { + var Described = java.lang.Object.extend({ + toString: function () { + return "described:" + this.label; + }, + superString: function () { + return this.super.toString(); + } + }); + var rebuilds = stats().canaryRebuilds; + var prototype = (function () { + var described = new Described(); + described.label = "first"; + Holder.held = described; + return Object.getPrototypeOf(described); + })(); + collectBoth(); + collectJava(); + + var described = Holder.held; + expect(Object.getPrototypeOf(described)).toBe(prototype); + expect(described instanceof Described).toBe(true); + expect(described.toString()).toBe("described:first"); + expect(described.superString()).toContain("@"); + expect(described.superString()).not.toContain("described:"); + described.label = "second"; + described.extra = 1; + delete described.extra; + described = null; + collectBoth(); + collectJava(); + + described = Holder.held; + if (canary) { + expect(stats().canaryRebuilds).toBeGreaterThan(rebuilds + 1); + } + expect(Object.getPrototypeOf(described)).toBe(prototype); + expect(Object.keys(described)).toEqual(["label"]); + expect(java.lang.String.valueOf(described)).toBe("described:second"); + }); + + it("rebuilds an extended object Java constructed with its class", function () { + var Made = java.lang.Object.extend({ + toString: function () { + return "made:" + this.value; + } + }); + var rebuilds = stats().canaryRebuilds; + var prototype = (function () { + var made = new Made().getClass().newInstance(); + made.value = 7; + Holder.held = made; + return Object.getPrototypeOf(made); + })(); + collectBoth(); + collectJava(); + + var made = Holder.held; + if (canary) { + expect(stats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + expect(Object.getPrototypeOf(made)).toBe(prototype); + expect(made instanceof Made).toBe(true); + expect(made.toString()).toBe("made:7"); + expect(typeof made.hashCode()).toBe("number"); + }); + it("keeps the state a TypeScript-style subclass sets in its constructor", function () { var Greeter = (function (_super) { __extends(Greeter, _super); diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 6e5633dbb..55edb2c0e 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -214,7 +214,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j bool isInterface, const std::string &baseClassName, uint64_t defaultOverrides, - const vector *contentMemberNames) { + const vector *contentMemberNames, + Local instanceTemplate) { bool success; DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str()); @@ -241,7 +242,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j objectManager->Link(jsObject, javaObjectID, nullptr, !implementationObject.IsEmpty() || isInterface ? ObjectManager::LinkKind::kExtended - : ObjectManager::LinkKind::kPlain); + : ObjectManager::LinkKind::kPlain, + instanceTemplate); // resolve constructor const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName, diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.h b/test-app/runtime/src/main/cpp/CallbackHandlers.h index 6f507dcf5..fff974218 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -42,7 +42,8 @@ namespace tns { bool isInterface, const std::string &baseClassName = std::string(), uint64_t defaultOverrides = 0, - const std::vector *contentMemberNames = nullptr); + const std::vector *contentMemberNames = nullptr, + v8::Local instanceTemplate = v8::Local()); // Whether GetImplementedInterfaces would list any interface, without calling Java. static bool HasImplementedInterfaces(v8::Isolate *isolate, const v8::Local &implementationObject); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index a1e1d3ed2..74ce1fe75 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -198,7 +198,8 @@ MetadataNode::MetadataNode(MetadataTreeNode* treeNode) : } } -Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName) { +Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName, + Local* instanceTemplate) { Local extInstance; auto cacheData = GetCachedExtendedClassData(isolate, proxyClassName); @@ -217,7 +218,8 @@ Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectMana // Starts on the extended class's initial map, with its prototype, and without // running its constructor callback. auto context = Runtime::GetRuntime(isolate)->GetContext(); - if (cacheData.instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&extInstance)) { + *instanceTemplate = cacheData.instanceTemplate->Get(isolate); + if ((*instanceTemplate)->NewInstance(context).ToLocal(&extInstance)) { // V8 may copy instances from a cached instantiation of the template, which keeps the // prototype the class had then. This only matters if code reassigns the extended // class's `prototype` property, which nothing in the runtime or core does; consider @@ -347,6 +349,17 @@ Local MetadataNode::CreateWrapper(Isolate* isolate) { return handle_scope.Escape(obj); } +Local MetadataNode::GetInstanceTemplate(Isolate* isolate, InstanceData& data) { + if (data.instanceTemplate == nullptr) { + // Throws for a class missing at runtime, which has no template. + GetConstructorFunction(isolate); + auto cache = GetMetadataNodeCache(isolate); + auto ft = Local::New(isolate, *cache->CtorFuncCache.at(m_treeNode).ft); + data.instanceTemplate = new Persistent(isolate, ft->InstanceTemplate()); + } + return data.instanceTemplate->Get(isolate); +} + Local MetadataNode::CreateJSWrapper(Isolate* isolate, ObjectManager* objectManager) { Local obj; @@ -354,17 +367,11 @@ Local MetadataNode::CreateJSWrapper(Isolate* isolate, ObjectManager* obj obj = CreateArrayWrapper(isolate); } else { auto& data = GetInstanceData(isolate); - if (data.instanceTemplate == nullptr) { - // Throws for a class missing at runtime, which has no template. - GetConstructorFunction(isolate); - auto cache = GetMetadataNodeCache(isolate); - auto ft = Local::New(isolate, *cache->CtorFuncCache.at(m_treeNode).ft); - data.instanceTemplate = new Persistent(isolate, ft->InstanceTemplate()); - } + auto instanceTemplate = GetInstanceTemplate(isolate, data); // Starts on the class's initial map, with the constructor's prototype, and // without running the constructor callback. auto context = isolate->GetCurrentContext(); - if (data.instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&obj)) { + if (instanceTemplate->NewInstance(context).ToLocal(&obj)) { obj->SetInternalField(static_cast(ObjectManager::MetadataNodeKeys::Metadata), data.metadata->Get(isolate)); } @@ -1599,7 +1606,8 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn string fullClassName = extData->fullClassName; bool success = CallbackHandlers::RegisterInstance(isolate, thiz, fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides, - extData->contentMemberNames ? &*extData->contentMemberNames : nullptr); + extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, + extData->instanceTemplate.Get(isolate)); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -1667,7 +1675,11 @@ void MetadataNode::InterfaceConstructorCallback(const v8::FunctionCallbackInfoGetInstanceTemplate(isolate, node->GetInstanceData(isolate)) + : Local()); if (frame.check()) { frame.log("Interface constructor: " + node->m_name); @@ -2377,6 +2389,7 @@ void MetadataNode::ExtendMethodCallback(const v8::FunctionCallbackInfoInstanceTemplate()->SetInternalFieldCount(static_cast(ObjectManager::MetadataNodeKeys::END)); + extendedClassCallbackData->instanceTemplate.Reset(isolate, extendFuncTemplate->InstanceTemplate()); WrapperLifetimeCanary::ConfigureInstanceTemplate( extendFuncTemplate->InstanceTemplate(), WrapperLifetimeCanary::TemplateKind::kExtended, Runtime::GetObjectManager(isolate)); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index e60e44570..7acd8bbbc 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -67,7 +67,9 @@ class MetadataNode { static MetadataNode* GetNodeFromHandle(const v8::Local& value); - static v8::Local CreateExtendedJSWrapper(v8::Isolate* isolate, ObjectManager* objectManager, const std::string& proxyClassName); + // instanceTemplate receives the template the wrapper was made from. + static v8::Local CreateExtendedJSWrapper(v8::Isolate* isolate, ObjectManager* objectManager, const std::string& proxyClassName, + v8::Local* instanceTemplate); static v8::Local GetImplementationObject(v8::Isolate* isolate, const v8::Local& object); @@ -200,6 +202,10 @@ class MetadataNode { // This runtime's per-instance data for this node, created on first use. InstanceData& GetInstanceData(v8::Isolate* isolate); + // The instance template of a class's or interface's constructor; throws + // for a class missing at runtime. data is GetInstanceData(isolate). + v8::Local GetInstanceTemplate(v8::Isolate* isolate, InstanceData& data); + static void SetInstanceMetadata(v8::Isolate* isolate, v8::Local value, MetadataNode* node); static TypeMetadata* GetTypeMetadata(v8::Isolate* isolate, const v8::Local& value); @@ -319,11 +325,13 @@ class MetadataNode { ~ExtendedClassCallbackData() { implementationObject->Reset(); delete implementationObject; + instanceTemplate.Reset(); } MetadataNode* node; std::string extendedName; v8::Persistent* implementationObject; + v8::Persistent instanceTemplate; std::string fullClassName; uint64_t defaultOverrides = 0; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index a22d0e3ef..b03c14b25 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -112,11 +112,6 @@ void ObjectManager::Init(Isolate* isolate) { m_jsWrapperTemplate.Reset(isolate, jsWrapperFuncTemplate->InstanceTemplate()); if (WrapperLifetimeCanary::Enabled()) { - auto canaryTemplate = ObjectTemplate::New(isolate); - canaryTemplate->SetInternalFieldCount(static_cast(MetadataNodeKeys::END)); - WrapperLifetimeCanary::ConfigureInstanceTemplate( - canaryTemplate, WrapperLifetimeCanary::TemplateKind::kExtended, this); - m_canaryTemplate.Reset(isolate, canaryTemplate); m_instanceFieldTableKey.Reset(isolate, Private::New(isolate)); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); m_canaryEpilogueAdded = true; @@ -553,7 +548,7 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, * Link the JavaScript object and it's java counterpart with an ID */ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, - jclass clazz, LinkKind kind) { + jclass clazz, LinkKind kind, Local instanceTemplate) { if (!IsJsRuntimeObject(object)) { string errMsg("Trying to link invalid 'this' to a Java object"); throw NativeScriptException(errMsg); @@ -586,13 +581,13 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, (void) inserted; if (state->canary) { - AdoptCanary(object, javaObjectID, kind); + AdoptCanary(object, javaObjectID, kind, instanceTemplate); state->record = FindCanaryRecord(javaObjectID); } } void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObjectID, - LinkKind kind) { + LinkKind kind, Local instanceTemplate) { CanaryRecord* record = FindCanaryRecord(javaObjectID); if (record == nullptr) { if (kind != LinkKind::kExtended) { @@ -600,20 +595,12 @@ void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObject } // Java calls into JS through this object for as long as it lives, so the // record is made now, not at the first write: a canary built later needs - // the prototype and fields this one was registered with. - auto isolate = m_isolate; + // the prototype and fields this one was registered with. Allocated before + // the record exists: a collection it starts runs the canary callbacks. + Local shell = NewCanaryShell(object, instanceTemplate); auto created = std::make_unique(); - created->extended = true; - created->prototype.Reset(isolate, object->GetPrototype()); - created->callSuper.Reset( - isolate, object->GetInternalField(static_cast(MetadataNodeKeys::CallSuper)).As()); - created->metadata.Reset( - isolate, object->GetInternalField(static_cast(MetadataNodeKeys::Metadata)).As()); - Local implementationObject; - if (V8GetPrivateValue(isolate, object, V8StringConstants::GetImplementationObject(isolate), - implementationObject) && - !implementationObject.IsEmpty()) { - created->implementationObject.Reset(isolate, implementationObject); + if (!shell.IsEmpty()) { + created->shell.Reset(m_isolate, shell); } m_canaryRecords.emplace(javaObjectID, std::move(created)); return; @@ -631,6 +618,45 @@ void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObject } } +Local ObjectManager::NewCanaryShell(const Local& object, + Local instanceTemplate) { + auto isolate = m_isolate; + // Every extended link names its template; a record without a shell only + // loses the rebuild. + NS_DCHECK(!instanceTemplate.IsEmpty()); + if (instanceTemplate.IsEmpty()) { + return Local(); + } + EscapableHandleScope handleScope(isolate); + auto context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + context = Runtime::GetRuntime(isolate)->GetContext(); + } + Local shell; + if (!instanceTemplate->NewInstance(context).ToLocal(&shell)) { + return handleScope.Escape(Local()); + } + // An extend() instance already has its class's prototype; an interface + // implementation's is its own implementation object. + Local prototype = object->GetPrototype(); + if (!prototype->StrictEquals(shell->GetPrototype()) && + !shell->SetPrototype(context, prototype).FromMaybe(false)) { + return handleScope.Escape(Local()); + } + for (auto key : {MetadataNodeKeys::CallSuper, MetadataNodeKeys::Metadata}) { + shell->SetInternalField(static_cast(key), + object->GetInternalField(static_cast(key))); + } + Local implementationObject; + if (V8GetPrivateValue(isolate, object, V8StringConstants::GetImplementationObject(isolate), + implementationObject) && + !implementationObject.IsEmpty()) { + V8SetPrivateValue(isolate, shell, V8StringConstants::GetImplementationObject(isolate), + implementationObject); + } + return handleScope.Escape(shell); +} + ObjectManager::CanaryRecord* ObjectManager::FindCanaryRecord(int javaObjectID) { if (m_canaryRecords.empty()) { return nullptr; @@ -665,7 +691,7 @@ bool ObjectManager::EnsureJavaStrong(int javaObjectID, CanaryRecord* record) { Local ObjectManager::RebuildCanary(int javaObjectID) { CanaryRecord* record = FindCanaryRecord(javaObjectID); - if (record == nullptr || !record->extended) { + if (record == nullptr || record->shell.IsEmpty()) { return Local(); } auto isolate = m_isolate; @@ -673,23 +699,8 @@ Local ObjectManager::RebuildCanary(int javaObjectID) { if (!EnsureJavaStrong(javaObjectID, record)) { return handleScope.Escape(Local()); } - auto context = isolate->GetCurrentContext(); - Local canary; - if (!m_canaryTemplate.Get(isolate)->NewInstance(context).ToLocal(&canary)) { - return handleScope.Escape(Local()); - } - Local prototype = record->prototype.Get(isolate); - if (!prototype.IsEmpty() && (prototype->IsObject() || prototype->IsNull())) { - (void) canary->SetPrototype(context, prototype); - } - canary->SetInternalField(static_cast(MetadataNodeKeys::CallSuper), - record->callSuper.Get(isolate)); - canary->SetInternalField(static_cast(MetadataNodeKeys::Metadata), - record->metadata.Get(isolate)); - if (!record->implementationObject.IsEmpty()) { - V8SetPrivateValue(isolate, canary, V8StringConstants::GetImplementationObject(isolate), - record->implementationObject.Get(isolate)); - } + // Never a clone of a canary: that would copy its #private brands and JsInfo. + Local canary = record->shell.Get(isolate)->Clone(isolate); m_lifetimeStats.canaryRebuilds++; Link(canary, javaObjectID, record->clazz, LinkKind::kExtended); return handleScope.Escape(canary); @@ -1254,7 +1265,6 @@ void ObjectManager::ReleaseAllRegistered() { } m_idToObject.ForEach([](ObjectWeakCallbackState* state) { state->record = nullptr; }); m_canaryRecords.clear(); - m_canaryTemplate.Reset(); m_instanceFieldTableKey.Reset(); auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 34b5c1ee4..963094a08 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -110,8 +110,12 @@ class ObjectManager { // JS-extended class's or an interface implementation's instance). enum class LinkKind { kPlain, kExtended }; + // instanceTemplate is the template object was made from. Canary mode needs + // it for an extended link: the canaries built after the first one are + // copies of a fresh instance of it. void Link(const v8::Local& object, uint32_t javaObjectID, - jclass clazz, LinkKind kind = LinkKind::kPlain); + jclass clazz, LinkKind kind = LinkKind::kPlain, + v8::Local instanceTemplate = v8::Local()); void ReleaseNativeCounterpart(v8::Local& object); @@ -281,13 +285,10 @@ class ObjectManager { struct CanaryRecord { // The object's JS properties; empty until the first write. v8::Global state; - // JS-extended instances: what a canary built later starts from, as the - // first canary had it once registered. - bool extended = false; - v8::Global prototype; - v8::Global callSuper; - v8::Global metadata; - v8::Global implementationObject; + // JS-extended instances: a canary built later is a clone of this, with + // the first canary's prototype, internal fields and implementation object. + // Never linked, never handed to JS, and so never written. + v8::Global shell; // The link's class, taken from the last canary (a global ref the class caches own). jclass clazz = nullptr; // The Java object table holds the object through a watched weak reference. @@ -353,7 +354,12 @@ class ObjectManager { // Registers a new canary: creates an extended instance's record, and // hydrates a canary for an object that already has state. void AdoptCanary(const v8::Local& object, uint32_t javaObjectID, - LinkKind kind); + LinkKind kind, v8::Local instanceTemplate); + + // An unlinked instance of instanceTemplate with what object, a canary + // being registered, carries from its construction; empty on failure. + v8::Local NewCanaryShell(const v8::Local& object, + v8::Local instanceTemplate); // The live canary state of holder, or null. ObjectWeakCallbackState* CanaryOf(const v8::Local& holder); @@ -377,8 +383,6 @@ class ObjectManager { std::unordered_map> m_canaryRecords; std::vector m_pendingCanaryDeaths; - // Template of a canary rebuilt for a JS-extended instance. - v8::Persistent m_canaryTemplate; bool m_copyingCanaryProperties = false; bool m_deathInboxOpen = false; bool m_canaryEpilogueAdded = false; diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 0bdf170b9..096caaa50 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -727,8 +727,9 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, auto proxyClassName = m_objectManager->GetClassName(javaObject); DEBUG_WRITE("createJSInstanceNative class %s", proxyClassName.c_str()); + Local instanceTemplate; jsInstance = MetadataNode::CreateExtendedJSWrapper(isolate, m_objectManager, - proxyClassName); + proxyClassName, &instanceTemplate); if (jsInstance.IsEmpty()) { throw NativeScriptException( @@ -747,7 +748,7 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, jclass clazz = env.FindClass(jniName); m_objectManager->Link(jsInstance, javaObjectID, clazz, - ObjectManager::LinkKind::kExtended); + ObjectManager::LinkKind::kExtended, instanceTemplate); } jint Runtime::GenerateNewObjectId(JNIEnv* env, jobject obj) { diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h index 840319f54..5ac732fda 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h @@ -23,9 +23,9 @@ class ObjectManager; // built later for the same object gets the state's properties copied back. // The state object is the source of truth. // -// ObjectManager owns the records (state, and for JS-extended instances what a -// new canary needs: prototype, internal fields, implementation object). A -// record lives until Java collects its object, which +// ObjectManager owns the records (state, and for JS-extended instances a shell +// a new canary is cloned from: prototype, internal fields, implementation +// object). A record lives until Java collects its object, which // com.tns.WrapperLifetimeWatcher reports from its own thread. It cannot be // rooted only once the canary dies instead: a state reachable only through the // canary is garbage in the same collection. The cost is that state referencing From 79ffaa9a908b41f9b9b228ca2f1dc4660fe00fe2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 01:21:02 -0300 Subject: [PATCH 14/20] perf(runtime): rebuild a dead canary from the id Java passes with a call A Java->JS call, or a Java object handed to JS as a call argument, comes with an id Java read without the isolate lock (the binding's stamped id or an identity-index lookup). When that id named no live wrapper, native asked Java for the object's id again (findJavaObjectID, or getOrCreateJavaObjectID for an argument) and only then rebuilt the object's canary, which asks Java to hold the object strongly again (strengthenInstance): two upcalls. Ids are never reused, so an id with a canary record names that record's object. The canary is now rebuilt from the passed id directly, and strengthenInstance, which checks under the object table's lock that the object is still alive, is the only upcall left. When the object is gone (a call a finalize() makes) the rebuild comes back empty and the id is resolved as before, so such a call is still dropped with a warning. Measured on a phone, the id lookup this skips cost 0.64 us per dead-canary call into an interface implementation. --- .../app/tests/testWrapperLifetimeModes.js | 23 +++++++++++++++++++ .../runtime/src/main/cpp/ObjectManager.cpp | 5 +++- test-app/runtime/src/main/cpp/ObjectManager.h | 3 ++- test-app/runtime/src/main/cpp/Runtime.cpp | 2 +- 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js index d93deb238..114b53dd5 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -192,6 +192,29 @@ describe("Wrapper lifetime modes", function () { expect(runnable.ran).toBe(2); }); + it("hands Java-held extended objects whose canaries died to a JS callback", function () { + var list = (function () { + var list = new java.util.ArrayList(); + var ranks = [3, 1, 2]; + for (var i = 0; i < ranks.length; i++) { + var runnable = new java.lang.Runnable({ run: function () {} }); + runnable.rank = ranks[i]; + list.add(runnable); + } + return list; + })(); + collectBoth(); + collectJava(); + + var comparator = new java.util.Comparator({ + compare: function (a, b) { + return a.rank - b.rank; + } + }); + java.util.Collections.sort(list, comparator); + expect([list.get(0).rank, list.get(1).rank, list.get(2).rank]).toEqual([1, 2, 3]); + }); + it("rebuilds an extend() instance with its class, super calls and state, more than once", function () { var Described = java.lang.Object.extend({ toString: function () { diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index b03c14b25..3b83dd0d2 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -443,7 +443,10 @@ void ObjectManager::ReleaseUnwrappedArgs(const JavaCallArgs& args) { Local ObjectManager::GetLinkedJsObjectByJavaObject(int javaObjectID) { auto state = m_idToObject.Find(javaObjectID); - if (state == nullptr || !state->linked) { + if (state == nullptr) { + return RebuildCanary(javaObjectID); + } + if (!state->linked) { return Local(); } return JsObjectFor(state); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 963094a08..c988a5cc9 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -93,7 +93,8 @@ class ObjectManager { void ReleaseUnwrappedArgs(const JavaCallArgs& args); // As GetJsObjectByJavaObject, but empty once the wrapper's link to the Java object was - // released. + // released. Ids are never reused, so an id read without the isolate lock that names a + // dead canary's record still names that record's object. v8::Local GetLinkedJsObjectByJavaObject(int javaObjectID); v8::Local CreateJSWrapper(jint javaObjectID, diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 096caaa50..81b2f4c73 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -641,7 +641,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, args.canaryReleasesAtStart = m_objectManager->CanaryReleaseCount(); // javaObjectID may be a hint read without the isolate lock; resolve it exactly when it - // does not name a linked wrapper. + // names neither a linked wrapper nor a canary that can be rebuilt. Local jsObject; if (javaObjectID != -1) { jsObject = m_objectManager->GetLinkedJsObjectByJavaObject(javaObjectID); From 21788fcec9c1e3ed650afd64b504e626d54c986e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 01:22:24 -0300 Subject: [PATCH 15/20] perf(runtime): look a canary record up once per new wrapper Creating a wrapper for an id with no live one looked the id's canary record up to four times: GetJsObjectByJavaObject's rebuild attempt, CreateJSWrapperHelper's, AdoptCanary, and Link right after it. Under scope "all" every Java object with JS state has a record, so these are hash lookups on the path that hands Java objects to JS. CreateJSWrapperHelper now looks the record up once and passes it through the rebuild or the link; AdoptCanary returns the record the canary ends up with. GetOrCreateJSWrapper, and the argument conversion that resolves an id itself, go straight to CreateJSWrapper when no wrapper is registered, instead of trying a rebuild first and again inside it. --- .../runtime/src/main/cpp/ArgConverter.cpp | 5 +- .../runtime/src/main/cpp/ObjectManager.cpp | 62 +++++++++++++------ test-app/runtime/src/main/cpp/ObjectManager.h | 20 +++++- 3 files changed, 60 insertions(+), 27 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ArgConverter.cpp b/test-app/runtime/src/main/cpp/ArgConverter.cpp index 30f4ae86d..78a5e847f 100644 --- a/test-app/runtime/src/main/cpp/ArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/ArgConverter.cpp @@ -168,10 +168,7 @@ void ArgConverter::ConvertJavaArgsToJsArgs(Isolate* isolate, JNIEnv* env, const if (jsArg.IsEmpty()) { JniLocalRef arg(env->GetObjectArrayElement(args.refs, i)); auto javaObjectID = objectManager->GetOrCreateObjectId(arg); - jsArg = objectManager->GetJsObjectByJavaObject(javaObjectID); - if (jsArg.IsEmpty()) { - jsArg = objectManager->CreateJSWrapper(javaObjectID, classIndex, arg); - } + jsArg = objectManager->GetOrCreateJSWrapper(javaObjectID, classIndex, arg); } break; } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 3b83dd0d2..b64c2f2c2 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -463,12 +463,16 @@ Local ObjectManager::GetOrCreateJSWrapper(jobject object) { jlong packed = env.CallLongMethod( m_javaRuntimeObject, GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID, object); - auto javaObjectID = static_cast(packed); - auto wrapper = GetJsObjectByJavaObject(javaObjectID); - if (!wrapper.IsEmpty()) { - return wrapper; + return GetOrCreateJSWrapper(static_cast(packed), static_cast(packed >> 32), object); +} + +Local ObjectManager::GetOrCreateJSWrapper(jint javaObjectID, int classIndex, + jobject instance) { + // As GetJsObjectByJavaObject, then CreateJSWrapper, which rebuilds a canary itself. + if (auto state = m_idToObject.Find(javaObjectID)) { + return JsObjectFor(state); } - return CreateJSWrapper(javaObjectID, static_cast(packed >> 32), object); + return CreateJSWrapper(javaObjectID, classIndex, instance); } Local ObjectManager::CreateJSWrapper(jint javaObjectID, int classIndex, @@ -525,10 +529,16 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, MetadataNode* node) { auto isolate = m_isolate; - // A JS-extended instance's canary starts from its record, not from its class. - auto rebuilt = RebuildCanary(javaObjectID); - if (!rebuilt.IsEmpty()) { - return rebuilt; + // Nothing from here to the link runs JS or settles canaries, so the record + // stays valid. + CanaryRecord* record = FindCanaryRecord(javaObjectID); + if (record != nullptr && !record->shell.IsEmpty()) { + // A JS-extended instance's canary starts from its record, not from its class. + auto rebuilt = RebuildCanary(javaObjectID, record); + if (!rebuilt.IsEmpty()) { + return rebuilt; + } + record = FindCanaryRecord(javaObjectID); } if (node == nullptr) { @@ -542,7 +552,7 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, JEnv env; clazz = env.FindClass(className); } - Link(jsWrapper, javaObjectID, clazz); + Link(jsWrapper, javaObjectID, clazz, LinkKind::kPlain, Local(), record); } return jsWrapper; } @@ -552,6 +562,12 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, */ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jclass clazz, LinkKind kind, Local instanceTemplate) { + Link(object, javaObjectID, clazz, kind, instanceTemplate, std::nullopt); +} + +void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jclass clazz, + LinkKind kind, Local instanceTemplate, + std::optional record) { if (!IsJsRuntimeObject(object)) { string errMsg("Trying to link invalid 'this' to a Java object"); throw NativeScriptException(errMsg); @@ -584,17 +600,18 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, (void) inserted; if (state->canary) { - AdoptCanary(object, javaObjectID, kind, instanceTemplate); - state->record = FindCanaryRecord(javaObjectID); + state->record = AdoptCanary(object, javaObjectID, kind, instanceTemplate, + record.has_value() ? *record : FindCanaryRecord(javaObjectID)); } } -void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObjectID, - LinkKind kind, Local instanceTemplate) { - CanaryRecord* record = FindCanaryRecord(javaObjectID); +ObjectManager::CanaryRecord* ObjectManager::AdoptCanary(const Local& object, + uint32_t javaObjectID, LinkKind kind, + Local instanceTemplate, + CanaryRecord* record) { if (record == nullptr) { if (kind != LinkKind::kExtended) { - return; + return nullptr; } // Java calls into JS through this object for as long as it lives, so the // record is made now, not at the first write: a canary built later needs @@ -605,11 +622,12 @@ void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObject if (!shell.IsEmpty()) { created->shell.Reset(m_isolate, shell); } + record = created.get(); m_canaryRecords.emplace(javaObjectID, std::move(created)); - return; + return record; } if (!EnsureJavaStrong(javaObjectID, record)) { - return; + return nullptr; } if (!record->state.IsEmpty()) { auto context = m_isolate->GetCurrentContext(); @@ -619,6 +637,7 @@ void ObjectManager::AdoptCanary(const Local& object, uint32_t javaObject WrapperLifetimeCanary::CopyOwnProperties(this, context, record->state.Get(m_isolate), object, !record->stateNotPlain); } + return record; } Local ObjectManager::NewCanaryShell(const Local& object, @@ -693,7 +712,10 @@ bool ObjectManager::EnsureJavaStrong(int javaObjectID, CanaryRecord* record) { } Local ObjectManager::RebuildCanary(int javaObjectID) { - CanaryRecord* record = FindCanaryRecord(javaObjectID); + return RebuildCanary(javaObjectID, FindCanaryRecord(javaObjectID)); +} + +Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* record) { if (record == nullptr || record->shell.IsEmpty()) { return Local(); } @@ -705,7 +727,7 @@ Local ObjectManager::RebuildCanary(int javaObjectID) { // Never a clone of a canary: that would copy its #private brands and JsInfo. Local canary = record->shell.Get(isolate)->Clone(isolate); m_lifetimeStats.canaryRebuilds++; - Link(canary, javaObjectID, record->clazz, LinkKind::kExtended); + Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, Local(), record); return handleScope.Escape(canary); } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index c988a5cc9..56c80035b 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -2,6 +2,7 @@ #define OBJECTMANAGER_H_ #include +#include #include #include #include @@ -103,6 +104,10 @@ class ObjectManager { // The wrapper of object, registering it and creating the wrapper if needed. v8::Local GetOrCreateJSWrapper(jobject object); + // GetJsObjectByJavaObject, or CreateJSWrapper when that is empty. + v8::Local GetOrCreateJSWrapper(jint javaObjectID, int classIndex, + jobject instance); + // classIndex is Runtime.classIndexOf(instance's class), or 0 when unknown. v8::Local CreateJSWrapper(jint javaObjectID, int classIndex, jobject instance); @@ -352,10 +357,17 @@ class ObjectManager { static void CanaryGCEpilogue(v8::Isolate* isolate, v8::GCType type, v8::GCCallbackFlags flags, void* data); + // record is FindCanaryRecord(javaObjectID), or nullopt to look it up. + void Link(const v8::Local& object, uint32_t javaObjectID, jclass clazz, + LinkKind kind, v8::Local instanceTemplate, + std::optional record); + // Registers a new canary: creates an extended instance's record, and - // hydrates a canary for an object that already has state. - void AdoptCanary(const v8::Local& object, uint32_t javaObjectID, - LinkKind kind, v8::Local instanceTemplate); + // hydrates a canary for an object that already has state. record is + // FindCanaryRecord(javaObjectID); returns the canary's record, or null. + CanaryRecord* AdoptCanary(const v8::Local& object, uint32_t javaObjectID, + LinkKind kind, v8::Local instanceTemplate, + CanaryRecord* record); // An unlinked instance of instanceTemplate with what object, a canary // being registered, carries from its construction; empty on failure. @@ -370,6 +382,8 @@ class ObjectManager { // A new canary for a JS-extended instance whose canary died; empty when id // has no extended record or Java collected the object meanwhile. v8::Local RebuildCanary(int javaObjectID); + // record is FindCanaryRecord(javaObjectID). + v8::Local RebuildCanary(int javaObjectID, CanaryRecord* record); // Has the Java object table hold record's object strongly again; false (and // the record dropped) when Java collected it. From 53fb577a27b9e18000830f3661329bd8b8b08dc2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 02:54:12 -0300 Subject: [PATCH 16/20] perf(runtime): copy a canary's shell from its first rebuild instead of registration Building the shell when an extended object was registered made every construction pay for it, while few such objects are ever rebuilt. Measured on a phone (release build, medians): `new Ext0()` went from 5122 to 5839 ns (+10%) and a full GC per dead extended wrapper with state from 1883 to 2105 ns (+12%), while a realistic scroll creates about 241 extended instances per second and rebuilds about 12. Registration again keeps what the record kept before the eager shell (prototype, CallSuper and Metadata fields, implementation object, class) plus a pointer to the class's own instance template, which the runtime's metadata cache owns, so no object and no handle is added. The first rebuild makes the canary as before, from that template rather than a template shared by every class, hydrates it from the state, and keeps a clone of it as the shell, taken before JS can reach the canary and with its JsInfo cleared, so it holds nothing JS adds later (#private brands, weak-collection keys). A later rebuild clones the shell and links the clone without hydrating it. The write handlers drop the shell before they change the state, so a shell is only ever a copy of the current state and never keeps alive a value JS has since overwritten or deleted; the next rebuild hydrates and copies a new one. The record keeps its separate handles alongside the shell, so dropping it needs nothing else, and an object that is never rebuilt holds the same handles as before the eager shell. --- .../app/tests/testWrapperLifetimeModes.js | 140 ++++++++++++++++++ .../runtime/src/main/cpp/CallbackHandlers.cpp | 2 +- .../runtime/src/main/cpp/CallbackHandlers.h | 2 +- .../runtime/src/main/cpp/MetadataNode.cpp | 16 +- test-app/runtime/src/main/cpp/MetadataNode.h | 12 +- .../runtime/src/main/cpp/ObjectManager.cpp | 128 ++++++++-------- test-app/runtime/src/main/cpp/ObjectManager.h | 40 +++-- test-app/runtime/src/main/cpp/Runtime.cpp | 2 +- .../src/main/cpp/WrapperLifetimeCanary.cpp | 8 + .../src/main/cpp/WrapperLifetimeCanary.h | 6 +- 10 files changed, 262 insertions(+), 94 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js index 114b53dd5..526c85f02 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -256,6 +256,146 @@ describe("Wrapper lifetime modes", function () { expect(java.lang.String.valueOf(described)).toBe("described:second"); }); + // Each rebuild here comes from a Java call while no canary is alive. What the object's + // methods close over must not hold it, or it would never die. + function describeOwn(object, symbol) { + var names = Object.getOwnPropertyNames(object).sort(); + var described = {}; + names.forEach(function (name) { + var descriptor = Object.getOwnPropertyDescriptor(object, name); + described[name] = descriptor.get ? { get: true, enumerable: descriptor.enumerable, configurable: descriptor.configurable } : descriptor; + }); + described.symbol = object[symbol]; + return described; + } + + function plantDescribed(symbol) { + var runnable = new java.lang.Runnable({ + run: function () { + this.runs = (this.runs || 0) + 1; + } + }); + runnable.plain = 1; + Object.defineProperty(runnable, "fixed", { value: 2, writable: false, enumerable: true, configurable: false }); + Object.defineProperty(runnable, "hidden", { value: 3, writable: true, enumerable: false, configurable: true }); + Object.defineProperty(runnable, "doubled", { + get: function () { + return this.plain * 2; + }, + enumerable: true, + configurable: true + }); + runnable[symbol] = "symbol"; + Holder.held = runnable; + return new java.lang.Thread(runnable); + } + + it("rebuilds a canary twice with no write in between, keeping its properties as defined", function () { + var symbol = Symbol("rebuilt"); + var rebuilds = stats().canaryRebuilds; + var thread = plantDescribed(symbol); + // Reads only, each in a function of its own so no stale register keeps a canary + // alive across the next collection. + function read() { + var runnable = Holder.held; + return { + own: describeOwn(runnable, symbol), + doubled: runnable.doubled, + keys: Object.keys(runnable).sort(), + symbols: Object.getOwnPropertySymbols(runnable).length + }; + } + var seen = []; + for (var i = 0; i < 3; i++) { + collectBoth(); + collectJava(); + seen.push(read()); + } + expect(seen[0].own.plain).toEqual({ value: 1, writable: true, enumerable: true, configurable: true }); + expect(seen[0].own.fixed).toEqual({ value: 2, writable: false, enumerable: true, configurable: false }); + expect(seen[0].own.hidden).toEqual({ value: 3, writable: true, enumerable: false, configurable: true }); + expect(seen[0].own.doubled).toEqual({ get: true, enumerable: true, configurable: true }); + expect(seen[0].own.symbol).toBe("symbol"); + expect(seen[0].doubled).toBe(2); + expect(seen[0].keys).toEqual(["doubled", "fixed", "plain"]); + expect(seen[0].symbols).toBe(1); + expect(seen[1]).toEqual(seen[0]); + expect(seen[2]).toEqual(seen[0]); + if (canary) { + expect(stats().canaryRebuilds).toBe(rebuilds + 3); + } + collectBoth(); + collectJava(); + + thread.run(); + var runnable = Holder.held; + expect(runnable.runs).toBe(1); + expect(runnable.plain).toBe(1); + expect(function () { + "use strict"; + runnable.fixed = 5; + }).toThrow(); + expect(runnable.fixed).toBe(2); + }); + + it("rebuilds a canary written since its last rebuild with the written state", function () { + var symbol = Symbol("rewritten"); + var thread = plantDescribed(symbol); + collectBoth(); + collectJava(); + (function () { + var runnable = Holder.held; + runnable.plain = 10; + runnable.added = "added"; + delete runnable.hidden; + Object.defineProperty(runnable, "doubled", { + get: function () { + return this.plain * 3; + }, + enumerable: false, + configurable: true + }); + runnable[symbol] = "rewritten"; + })(); + collectBoth(); + collectJava(); + + thread.run(); + var runnable = Holder.held; + expect(runnable.runs).toBe(1); + expect(runnable.plain).toBe(10); + expect(runnable.added).toBe("added"); + expect("hidden" in runnable).toBe(false); + expect(runnable.doubled).toBe(30); + expect(Object.getOwnPropertyDescriptor(runnable, "doubled").enumerable).toBe(false); + expect(runnable[symbol]).toBe("rewritten"); + expect(Object.getOwnPropertyDescriptor(runnable, "fixed")).toEqual({ value: 2, writable: false, enumerable: true, configurable: false }); + }); + + it("keeps what a Java call writes into the canary rebuilt for it", function () { + var thread = (function () { + var runnable = new java.lang.Runnable({ + run: function () { + this.runs = (this.runs || 0) + 1; + this["run" + this.runs] = true; + } + }); + Holder.held = runnable; + return new java.lang.Thread(runnable); + })(); + for (var i = 0; i < 3; i++) { + collectBoth(); + collectJava(); + thread.run(); + } + collectBoth(); + collectJava(); + + var runnable = Holder.held; + expect(runnable.runs).toBe(3); + expect(Object.keys(runnable).sort()).toEqual(["run1", "run2", "run3", "runs"]); + }); + it("rebuilds an extended object Java constructed with its class", function () { var Made = java.lang.Object.extend({ toString: function () { diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 55edb2c0e..d196e3557 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -215,7 +215,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j const std::string &baseClassName, uint64_t defaultOverrides, const vector *contentMemberNames, - Local instanceTemplate) { + const Persistent *instanceTemplate) { bool success; DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str()); diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.h b/test-app/runtime/src/main/cpp/CallbackHandlers.h index fff974218..98004dfcb 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -43,7 +43,7 @@ namespace tns { const std::string &baseClassName = std::string(), uint64_t defaultOverrides = 0, const std::vector *contentMemberNames = nullptr, - v8::Local instanceTemplate = v8::Local()); + const v8::Persistent *instanceTemplate = nullptr); // Whether GetImplementedInterfaces would list any interface, without calling Java. static bool HasImplementedInterfaces(v8::Isolate *isolate, const v8::Local &implementationObject); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 74ce1fe75..255ac4a4e 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -199,7 +199,7 @@ MetadataNode::MetadataNode(MetadataTreeNode* treeNode) : } Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectManager* objectManager, const string& proxyClassName, - Local* instanceTemplate) { + const Persistent** instanceTemplate) { Local extInstance; auto cacheData = GetCachedExtendedClassData(isolate, proxyClassName); @@ -218,8 +218,8 @@ Local MetadataNode::CreateExtendedJSWrapper(Isolate* isolate, ObjectMana // Starts on the extended class's initial map, with its prototype, and without // running its constructor callback. auto context = Runtime::GetRuntime(isolate)->GetContext(); - *instanceTemplate = cacheData.instanceTemplate->Get(isolate); - if ((*instanceTemplate)->NewInstance(context).ToLocal(&extInstance)) { + *instanceTemplate = cacheData.instanceTemplate; + if (cacheData.instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&extInstance)) { // V8 may copy instances from a cached instantiation of the template, which keeps the // prototype the class had then. This only matters if code reassigns the extended // class's `prototype` property, which nothing in the runtime or core does; consider @@ -349,7 +349,7 @@ Local MetadataNode::CreateWrapper(Isolate* isolate) { return handle_scope.Escape(obj); } -Local MetadataNode::GetInstanceTemplate(Isolate* isolate, InstanceData& data) { +Persistent* MetadataNode::GetInstanceTemplate(Isolate* isolate, InstanceData& data) { if (data.instanceTemplate == nullptr) { // Throws for a class missing at runtime, which has no template. GetConstructorFunction(isolate); @@ -357,7 +357,7 @@ Local MetadataNode::GetInstanceTemplate(Isolate* isolate, Instan auto ft = Local::New(isolate, *cache->CtorFuncCache.at(m_treeNode).ft); data.instanceTemplate = new Persistent(isolate, ft->InstanceTemplate()); } - return data.instanceTemplate->Get(isolate); + return data.instanceTemplate; } Local MetadataNode::CreateJSWrapper(Isolate* isolate, ObjectManager* objectManager) { @@ -367,7 +367,7 @@ Local MetadataNode::CreateJSWrapper(Isolate* isolate, ObjectManager* obj obj = CreateArrayWrapper(isolate); } else { auto& data = GetInstanceData(isolate); - auto instanceTemplate = GetInstanceTemplate(isolate, data); + auto instanceTemplate = GetInstanceTemplate(isolate, data)->Get(isolate); // Starts on the class's initial map, with the constructor's prototype, and // without running the constructor callback. auto context = isolate->GetCurrentContext(); @@ -1607,7 +1607,7 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn bool success = CallbackHandlers::RegisterInstance(isolate, thiz, fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides, extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, - extData->instanceTemplate.Get(isolate)); + &extData->instanceTemplate); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -1679,7 +1679,7 @@ void MetadataNode::InterfaceConstructorCallback(const v8::FunctionCallbackInfoGetInstanceTemplate(isolate, node->GetInstanceData(isolate)) - : Local()); + : nullptr); if (frame.check()) { frame.log("Interface constructor: " + node->m_name); diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index 7acd8bbbc..d2650254b 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -67,9 +67,10 @@ class MetadataNode { static MetadataNode* GetNodeFromHandle(const v8::Local& value); - // instanceTemplate receives the template the wrapper was made from. + // instanceTemplate receives the template the wrapper was made from, which + // lives as long as this runtime's metadata cache. static v8::Local CreateExtendedJSWrapper(v8::Isolate* isolate, ObjectManager* objectManager, const std::string& proxyClassName, - v8::Local* instanceTemplate); + const v8::Persistent** instanceTemplate); static v8::Local GetImplementationObject(v8::Isolate* isolate, const v8::Local& object); @@ -202,9 +203,10 @@ class MetadataNode { // This runtime's per-instance data for this node, created on first use. InstanceData& GetInstanceData(v8::Isolate* isolate); - // The instance template of a class's or interface's constructor; throws - // for a class missing at runtime. data is GetInstanceData(isolate). - v8::Local GetInstanceTemplate(v8::Isolate* isolate, InstanceData& data); + // The instance template of a class's or interface's constructor, alive as + // long as this runtime's metadata cache; throws for a class missing at + // runtime. data is GetInstanceData(isolate). + v8::Persistent* GetInstanceTemplate(v8::Isolate* isolate, InstanceData& data); static void SetInstanceMetadata(v8::Isolate* isolate, v8::Local value, MetadataNode* node); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index b64c2f2c2..7a88f65f6 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -532,7 +532,7 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, // Nothing from here to the link runs JS or settles canaries, so the record // stays valid. CanaryRecord* record = FindCanaryRecord(javaObjectID); - if (record != nullptr && !record->shell.IsEmpty()) { + if (record != nullptr && record->extended) { // A JS-extended instance's canary starts from its record, not from its class. auto rebuilt = RebuildCanary(javaObjectID, record); if (!rebuilt.IsEmpty()) { @@ -552,7 +552,7 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, JEnv env; clazz = env.FindClass(className); } - Link(jsWrapper, javaObjectID, clazz, LinkKind::kPlain, Local(), record); + Link(jsWrapper, javaObjectID, clazz, LinkKind::kPlain, nullptr, record); } return jsWrapper; } @@ -561,13 +561,14 @@ Local ObjectManager::CreateJSWrapperHelper(jint javaObjectID, * Link the JavaScript object and it's java counterpart with an ID */ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, - jclass clazz, LinkKind kind, Local instanceTemplate) { + jclass clazz, LinkKind kind, + const Persistent* instanceTemplate) { Link(object, javaObjectID, clazz, kind, instanceTemplate, std::nullopt); } void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jclass clazz, - LinkKind kind, Local instanceTemplate, - std::optional record) { + LinkKind kind, const Persistent* instanceTemplate, + std::optional record, bool hydrate) { if (!IsJsRuntimeObject(object)) { string errMsg("Trying to link invalid 'this' to a Java object"); throw NativeScriptException(errMsg); @@ -601,26 +602,36 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jcl if (state->canary) { state->record = AdoptCanary(object, javaObjectID, kind, instanceTemplate, - record.has_value() ? *record : FindCanaryRecord(javaObjectID)); + record.has_value() ? *record : FindCanaryRecord(javaObjectID), + hydrate); } } -ObjectManager::CanaryRecord* ObjectManager::AdoptCanary(const Local& object, - uint32_t javaObjectID, LinkKind kind, - Local instanceTemplate, - CanaryRecord* record) { +ObjectManager::CanaryRecord* ObjectManager::AdoptCanary( + const Local& object, uint32_t javaObjectID, LinkKind kind, + const Persistent* instanceTemplate, CanaryRecord* record, bool hydrate) { if (record == nullptr) { if (kind != LinkKind::kExtended) { return nullptr; } // Java calls into JS through this object for as long as it lives, so the // record is made now, not at the first write: a canary built later needs - // the prototype and fields this one was registered with. Allocated before - // the record exists: a collection it starts runs the canary callbacks. - Local shell = NewCanaryShell(object, instanceTemplate); + // the prototype and fields this one was registered with. + NS_DCHECK(instanceTemplate != nullptr); + auto isolate = m_isolate; auto created = std::make_unique(); - if (!shell.IsEmpty()) { - created->shell.Reset(m_isolate, shell); + created->extended = true; + created->instanceTemplate = instanceTemplate; + created->prototype.Reset(isolate, object->GetPrototype()); + created->callSuper.Reset( + isolate, object->GetInternalField(static_cast(MetadataNodeKeys::CallSuper)).As()); + created->metadata.Reset( + isolate, object->GetInternalField(static_cast(MetadataNodeKeys::Metadata)).As()); + Local implementationObject; + if (V8GetPrivateValue(isolate, object, V8StringConstants::GetImplementationObject(isolate), + implementationObject) && + !implementationObject.IsEmpty()) { + created->implementationObject.Reset(isolate, implementationObject); } record = created.get(); m_canaryRecords.emplace(javaObjectID, std::move(created)); @@ -629,7 +640,7 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary(const Local& obj if (!EnsureJavaStrong(javaObjectID, record)) { return nullptr; } - if (!record->state.IsEmpty()) { + if (hydrate && !record->state.IsEmpty()) { auto context = m_isolate->GetCurrentContext(); if (context.IsEmpty()) { context = Runtime::GetRuntime(m_isolate)->GetContext(); @@ -640,45 +651,6 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary(const Local& obj return record; } -Local ObjectManager::NewCanaryShell(const Local& object, - Local instanceTemplate) { - auto isolate = m_isolate; - // Every extended link names its template; a record without a shell only - // loses the rebuild. - NS_DCHECK(!instanceTemplate.IsEmpty()); - if (instanceTemplate.IsEmpty()) { - return Local(); - } - EscapableHandleScope handleScope(isolate); - auto context = isolate->GetCurrentContext(); - if (context.IsEmpty()) { - context = Runtime::GetRuntime(isolate)->GetContext(); - } - Local shell; - if (!instanceTemplate->NewInstance(context).ToLocal(&shell)) { - return handleScope.Escape(Local()); - } - // An extend() instance already has its class's prototype; an interface - // implementation's is its own implementation object. - Local prototype = object->GetPrototype(); - if (!prototype->StrictEquals(shell->GetPrototype()) && - !shell->SetPrototype(context, prototype).FromMaybe(false)) { - return handleScope.Escape(Local()); - } - for (auto key : {MetadataNodeKeys::CallSuper, MetadataNodeKeys::Metadata}) { - shell->SetInternalField(static_cast(key), - object->GetInternalField(static_cast(key))); - } - Local implementationObject; - if (V8GetPrivateValue(isolate, object, V8StringConstants::GetImplementationObject(isolate), - implementationObject) && - !implementationObject.IsEmpty()) { - V8SetPrivateValue(isolate, shell, V8StringConstants::GetImplementationObject(isolate), - implementationObject); - } - return handleScope.Escape(shell); -} - ObjectManager::CanaryRecord* ObjectManager::FindCanaryRecord(int javaObjectID) { if (m_canaryRecords.empty()) { return nullptr; @@ -716,7 +688,7 @@ Local ObjectManager::RebuildCanary(int javaObjectID) { } Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* record) { - if (record == nullptr || record->shell.IsEmpty()) { + if (record == nullptr || !record->extended) { return Local(); } auto isolate = m_isolate; @@ -724,10 +696,42 @@ Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* recor if (!EnsureJavaStrong(javaObjectID, record)) { return handleScope.Escape(Local()); } - // Never a clone of a canary: that would copy its #private brands and JsInfo. - Local canary = record->shell.Get(isolate)->Clone(isolate); + if (!record->shell.IsEmpty()) { + Local canary = record->shell.Get(isolate)->Clone(isolate); + m_lifetimeStats.canaryRebuilds++; + Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, record, false); + return handleScope.Escape(canary); + } + + NS_DCHECK(record->instanceTemplate != nullptr); + if (record->instanceTemplate == nullptr) { + return handleScope.Escape(Local()); + } + auto context = isolate->GetCurrentContext(); + Local canary; + if (!record->instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&canary)) { + return handleScope.Escape(Local()); + } + Local prototype = record->prototype.Get(isolate); + if (!prototype.IsEmpty() && (prototype->IsObject() || prototype->IsNull()) && + !prototype->StrictEquals(canary->GetPrototype())) { + (void) canary->SetPrototype(context, prototype); + } + canary->SetInternalField(static_cast(MetadataNodeKeys::CallSuper), + record->callSuper.Get(isolate)); + canary->SetInternalField(static_cast(MetadataNodeKeys::Metadata), + record->metadata.Get(isolate)); + if (!record->implementationObject.IsEmpty()) { + V8SetPrivateValue(isolate, canary, V8StringConstants::GetImplementationObject(isolate), + record->implementationObject.Get(isolate)); + } m_lifetimeStats.canaryRebuilds++; - Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, Local(), record); + Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, record); + // Taken before JS can reach the canary, so it holds nothing JS adds later + // (#private brands, weak-collection keys); Link sets each clone's JsInfo. + Local shell = canary->Clone(isolate); + shell->SetInternalField(static_cast(MetadataNodeKeys::JsInfo), Undefined(isolate)); + record->shell.Reset(isolate, shell); return handleScope.Escape(canary); } @@ -812,6 +816,12 @@ bool ObjectManager::StateIsPlain(CanaryHandle* canary) { return canary->record == nullptr || !canary->record->stateNotPlain; } +void ObjectManager::StateChanging(CanaryHandle* canary) { + if (canary->record != nullptr && !canary->record->shell.IsEmpty()) { + canary->record->shell.Reset(); + } +} + void ObjectManager::SetStateNotPlain(CanaryHandle* canary) { if (canary->record != nullptr) { canary->record->stateNotPlain = true; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 56c80035b..0fd7d65eb 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -116,12 +116,12 @@ class ObjectManager { // JS-extended class's or an interface implementation's instance). enum class LinkKind { kPlain, kExtended }; - // instanceTemplate is the template object was made from. Canary mode needs - // it for an extended link: the canaries built after the first one are - // copies of a fresh instance of it. + // instanceTemplate is the template object was made from, alive as long as + // the runtime's metadata cache. Canary mode needs it for an extended link: + // a canary rebuilt later is an instance of it. void Link(const v8::Local& object, uint32_t javaObjectID, jclass clazz, LinkKind kind = LinkKind::kPlain, - v8::Local instanceTemplate = v8::Local()); + const v8::Persistent* instanceTemplate = nullptr); void ReleaseNativeCounterpart(v8::Local& object); @@ -213,6 +213,9 @@ class ObjectManager { // configurable data property: only a define can make one otherwise. bool StateIsPlain(CanaryHandle* canary); void SetStateNotPlain(CanaryHandle* canary); + // Before the handlers change the canary's state: a shell copied from an + // earlier state can no longer stand in for it. + void StateChanging(CanaryHandle* canary); // The canary's state object, created on its first write. v8::Local StateForWrite(CanaryHandle* canary); @@ -291,9 +294,17 @@ class ObjectManager { struct CanaryRecord { // The object's JS properties; empty until the first write. v8::Global state; - // JS-extended instances: a canary built later is a clone of this, with - // the first canary's prototype, internal fields and implementation object. - // Never linked, never handed to JS, and so never written. + // JS-extended instances: what a canary built later starts from, as the + // first canary had it once registered. + bool extended = false; + v8::Global prototype; + v8::Global callSuper; + v8::Global metadata; + v8::Global implementationObject; + const v8::Persistent* instanceTemplate = nullptr; + // A copy of the last rebuilt canary, taken once it was hydrated and before + // JS saw it, unlinked; a later rebuild clones it instead of hydrating. + // Present only while it matches the state. v8::Global shell; // The link's class, taken from the last canary (a global ref the class caches own). jclass clazz = nullptr; @@ -358,21 +369,18 @@ class ObjectManager { v8::GCCallbackFlags flags, void* data); // record is FindCanaryRecord(javaObjectID), or nullopt to look it up. + // hydrate false: object already carries the state's properties. void Link(const v8::Local& object, uint32_t javaObjectID, jclass clazz, - LinkKind kind, v8::Local instanceTemplate, - std::optional record); + LinkKind kind, const v8::Persistent* instanceTemplate, + std::optional record, bool hydrate = true); // Registers a new canary: creates an extended instance's record, and // hydrates a canary for an object that already has state. record is // FindCanaryRecord(javaObjectID); returns the canary's record, or null. CanaryRecord* AdoptCanary(const v8::Local& object, uint32_t javaObjectID, - LinkKind kind, v8::Local instanceTemplate, - CanaryRecord* record); - - // An unlinked instance of instanceTemplate with what object, a canary - // being registered, carries from its construction; empty on failure. - v8::Local NewCanaryShell(const v8::Local& object, - v8::Local instanceTemplate); + LinkKind kind, + const v8::Persistent* instanceTemplate, + CanaryRecord* record, bool hydrate); // The live canary state of holder, or null. ObjectWeakCallbackState* CanaryOf(const v8::Local& holder); diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 81b2f4c73..f97869679 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -727,7 +727,7 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, auto proxyClassName = m_objectManager->GetClassName(javaObject); DEBUG_WRITE("createJSInstanceNative class %s", proxyClassName.c_str()); - Local instanceTemplate; + const Persistent* instanceTemplate = nullptr; jsInstance = MetadataNode::CreateExtendedJSWrapper(isolate, m_objectManager, proxyClassName, &instanceTemplate); diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index ee73d56b4..e97f88304 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -58,6 +58,7 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can return false; } if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + objectManager->StateChanging(canary); (void)state->Set(context, property, value); } return true; @@ -69,6 +70,7 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can return false; } if ((attributes & ReadOnly) == 0) { + objectManager->StateChanging(canary); (void)state->Set(context, property, value); } return true; @@ -132,13 +134,17 @@ Intercepted Setter(Local property, Local value, if (state.IsEmpty()) { return Intercepted::kNo; } + objectManager->StateChanging(canary); (void)state->CreateDataProperty(context, property, value); } else if (objectManager->StateIsPlain(canary)) { // RewriteState found the name absent from the state. + objectManager->StateChanging(canary); (void)state->CreateDataProperty(context, property, value); } else if (!HasOwn(context, state, property)) { + objectManager->StateChanging(canary); (void)state->CreateDataProperty(context, property, value); } else if (!state->HasRealNamedCallbackProperty(context, property).FromMaybe(true)) { + objectManager->StateChanging(canary); (void)state->Set(context, property, value); } return Intercepted::kNo; @@ -152,6 +158,7 @@ Intercepted Deleter(Local property, const PropertyCallbackInfo& i } Local state = objectManager->StateOf(canary); if (!state.IsEmpty()) { + objectManager->StateChanging(canary); (void)state->Delete(info.GetIsolate()->GetCurrentContext(), property); } return Intercepted::kNo; @@ -178,6 +185,7 @@ Intercepted Definer(Local property, const PropertyDescriptor& descriptor, if (!plain) { objectManager->SetStateNotPlain(canary); } + objectManager->StateChanging(canary); (void)state->DefineProperty(info.GetIsolate()->GetCurrentContext(), property, const_cast(descriptor)); } diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h index 5ac732fda..8f1b7bc6f 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h @@ -23,9 +23,9 @@ class ObjectManager; // built later for the same object gets the state's properties copied back. // The state object is the source of truth. // -// ObjectManager owns the records (state, and for JS-extended instances a shell -// a new canary is cloned from: prototype, internal fields, implementation -// object). A record lives until Java collects its object, which +// ObjectManager owns the records (state, and for JS-extended instances what a +// new canary needs: prototype, internal fields, implementation object, and a +// copy of the last rebuilt canary while it matches the state). A record lives until Java collects its object, which // com.tns.WrapperLifetimeWatcher reports from its own thread. It cannot be // rooted only once the canary dies instead: a state reachable only through the // canary is garbage in the same collection. The cost is that state referencing From 4e6334eab79d0a8aebce3a76684e7b2cea422dfa Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:21:15 -0300 Subject: [PATCH 17/20] perf(runtime): mirror a canary write of a known state name with one store A canary write that rewrites a name its plain state already holds looked the name up on the state before storing it. A small per-runtime cache (64 sets x 4 ways, keyed by the record's address) now remembers names that are known own, writable data properties of a plain state, so such a write is a single Set on the state. A name enters the cache on its first rewrite, not when it is added: an entry holds a global handle, and caching on add made writes of new names about 8% slower on the phone. Entries are dropped before a delete or a define of the name, when the record is erased and at teardown; a state that stops being plain is never served from the cache. --- docs/ns-builtin-modules.md | 1 + .../assets/app/tests/testWrapperLifetime.js | 4 +- .../runtime/src/main/cpp/NsBuiltinModules.cpp | 1 + .../runtime/src/main/cpp/ObjectManager.cpp | 54 ++++++++++++++++++- test-app/runtime/src/main/cpp/ObjectManager.h | 43 +++++++++++++++ .../runtime/src/main/cpp/WrapperLifetime.h | 2 + .../src/main/cpp/WrapperLifetimeCanary.cpp | 11 +++- 7 files changed, 112 insertions(+), 4 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 06045800f..82ce4472b 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -192,6 +192,7 @@ every build on cold paths only: | `canaryStates` | `"canary"` only: state objects created to hold JS properties | | `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object | | `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Other wrappers have no handler | +| `canaryCachedWrites` | `"canary"` only: of those writes, rewrites of a name the handler knew to be a plain data property of the state, mirrored with one store | | `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object | In `"canary"` mode, `weakened` counts objects held weakly because their 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 350f9965f..e69a3c91d 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -37,8 +37,8 @@ describe("Wrapper lifetime", function () { it("exposes numeric counters", function () { var stats = runtime.getWrapperLifetimeStats(); expect(Object.keys(stats).sort()).toEqual( - ["canaryInterceptedWrites", "canaryNativeDeaths", "canaryRebuilds", "canaryStates", - "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); + ["canaryCachedWrites", "canaryInterceptedWrites", "canaryNativeDeaths", "canaryRebuilds", + "canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); Object.keys(stats).forEach(function (key) { expect(typeof stats[key]).toBe("number"); }); diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index a542afe1a..4842e73a3 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -178,6 +178,7 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { set("canaryStates", stats.canaryStates); set("canaryNativeDeaths", stats.canaryNativeDeaths); set("canaryInterceptedWrites", stats.canaryInterceptedWrites); + set("canaryCachedWrites", stats.canaryCachedWrites); set("canaryRebuilds", stats.canaryRebuilds); info.GetReturnValue().Set(result); } diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 7a88f65f6..6ff0c1eb2 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -663,7 +663,53 @@ void ObjectManager::EraseCanaryRecord(int javaObjectID) { if (auto live = m_idToObject.Find(javaObjectID)) { live->record = nullptr; } - m_canaryRecords.erase(javaObjectID); + auto it = m_canaryRecords.find(javaObjectID); + if (it != m_canaryRecords.end()) { + ForgetStateNames(it->second.get()); + m_canaryRecords.erase(it); + } +} + +void ObjectManager::CacheStateName(CanaryHandle* canary, const Local& property) { + CanaryRecord* record = canary->record; + if (record == nullptr || record->stateNotPlain || record->state.IsEmpty()) { + return; + } + size_t index = StateNameSet(record); + StateName* set = m_stateNames[index]; + for (size_t way = 0; way < kStateNameWays; way++) { + if (set[way].record == record && set[way].name == property) { + return; + } + } + StateName& entry = set[m_stateNameVictims[index]]; + m_stateNameVictims[index] = (m_stateNameVictims[index] + 1) % kStateNameWays; + entry.record = record; + entry.name.Reset(m_isolate, property); +} + +void ObjectManager::ForgetStateName(CanaryHandle* canary, const Local& property) { + CanaryRecord* record = canary->record; + if (record == nullptr) { + return; + } + StateName* set = m_stateNames[StateNameSet(record)]; + for (size_t way = 0; way < kStateNameWays; way++) { + if (set[way].record == record && set[way].name == property) { + set[way].record = nullptr; + set[way].name.Reset(); + } + } +} + +void ObjectManager::ForgetStateNames(CanaryRecord* record) { + StateName* set = m_stateNames[StateNameSet(record)]; + for (size_t way = 0; way < kStateNameWays; way++) { + if (set[way].record == record) { + set[way].record = nullptr; + set[way].name.Reset(); + } + } } bool ObjectManager::EnsureJavaStrong(int javaObjectID, CanaryRecord* record) { @@ -1299,6 +1345,12 @@ void ObjectManager::ReleaseAllRegistered() { } } m_idToObject.ForEach([](ObjectWeakCallbackState* state) { state->record = nullptr; }); + for (auto& set : m_stateNames) { + for (StateName& entry : set) { + entry.record = nullptr; + entry.name.Reset(); + } + } m_canaryRecords.clear(); m_instanceFieldTableKey.Reset(); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 0fd7d65eb..838a8d618 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -218,6 +218,16 @@ class ObjectManager { void StateChanging(CanaryHandle* canary); // The canary's state object, created on its first write. v8::Local StateForWrite(CanaryHandle* canary); + // The canary's state when its plain state is known to have `property` as an + // own data property; empty when that is not known. + inline v8::Local CachedPlainState(CanaryHandle* canary, + const v8::Local& property); + // After the handlers rewrote `property`, an own data property of the canary's + // plain state. An entry holds a global handle, so a name added to the state + // waits for its first rewrite. + void CacheStateName(CanaryHandle* canary, const v8::Local& property); + // Before the handlers delete or redefine `property` on the canary's state. + void ForgetStateName(CanaryHandle* canary, const v8::Local& property); // Set while the runtime copies properties between a canary and its state, so // the handlers let those defines through. The copy runs no JS, and only the @@ -399,6 +409,23 @@ class ObjectManager { void EraseCanaryRecord(int javaObjectID); + // Names that are own data properties of a plain state, the record's set + // chosen by its address: an entry is cleared before its name leaves the + // state and before its record is freed. + struct StateName { + CanaryRecord* record = nullptr; + v8::Global name; + }; + static constexpr size_t kStateNameSets = 64; + static constexpr size_t kStateNameWays = 4; + static size_t StateNameSet(const CanaryRecord* record) { + auto address = reinterpret_cast(record); + return ((address >> 4) ^ (address >> 10)) & (kStateNameSets - 1); + } + StateName m_stateNames[kStateNameSets][kStateNameWays]; + uint8_t m_stateNameVictims[kStateNameSets] = {}; + void ForgetStateNames(CanaryRecord* record); + // Settles canaries collected since the last flush: Java holds the objects // with records weakly and releases the others. False if the JNI call failed; // the ids are queued again. @@ -496,6 +523,22 @@ class ObjectManager { v8::Persistent* m_poJsWrapperFunc; v8::Persistent m_jsWrapperTemplate; }; + +inline v8::Local ObjectManager::CachedPlainState( + CanaryHandle* canary, const v8::Local& property) { + CanaryRecord* record = canary->record; + if (record == nullptr || record->stateNotPlain) { + return v8::Local(); + } + const StateName* set = m_stateNames[StateNameSet(record)]; + for (size_t way = 0; way < kStateNameWays; way++) { + if (set[way].record == record && set[way].name == property) { + m_lifetimeStats.canaryCachedWrites++; + return record->state.Get(m_isolate); + } + } + return v8::Local(); +} } // namespace tns #endif /* OBJECTMANAGER_H_ */ diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.h b/test-app/runtime/src/main/cpp/WrapperLifetime.h index c4c697efe..ce26d13bf 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -68,6 +68,8 @@ struct WrapperLifetimeStats { uint64_t canaryNativeDeaths = 0; // "canary" only: writes to canaries the write handler saw. uint64_t canaryInterceptedWrites = 0; + // "canary" only: of those, writes mirrored through the state name cache. + uint64_t canaryCachedWrites = 0; // "canary" only: canaries built anew for a JS-extended instance whose // previous canary died while Java kept the object. uint64_t canaryRebuilds = 0; diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index e97f88304..8129ed812 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -72,6 +72,7 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can if ((attributes & ReadOnly) == 0) { objectManager->StateChanging(canary); (void)state->Set(context, property, value); + objectManager->CacheStateName(canary, property); } return true; } @@ -98,7 +99,13 @@ Intercepted Setter(Local property, Local value, objectManager->CountCanaryWrite(); Isolate* isolate = info.GetIsolate(); Local context = isolate->GetCurrentContext(); - Local state = objectManager->StateOf(canary); + Local state = objectManager->CachedPlainState(canary, property); + if (!state.IsEmpty()) { + objectManager->StateChanging(canary); + (void)state->Set(context, property, value); + return Intercepted::kNo; + } + state = objectManager->StateOf(canary); // Own on the state means own on the canary: a rewrite of a JS property. if (!state.IsEmpty() && RewriteState(objectManager, canary, context, state, property, value)) { @@ -159,6 +166,7 @@ Intercepted Deleter(Local property, const PropertyCallbackInfo& i Local state = objectManager->StateOf(canary); if (!state.IsEmpty()) { objectManager->StateChanging(canary); + objectManager->ForgetStateName(canary, property); (void)state->Delete(info.GetIsolate()->GetCurrentContext(), property); } return Intercepted::kNo; @@ -186,6 +194,7 @@ Intercepted Definer(Local property, const PropertyDescriptor& descriptor, objectManager->SetStateNotPlain(canary); } objectManager->StateChanging(canary); + objectManager->ForgetStateName(canary, property); (void)state->DefineProperty(info.GetIsolate()->GetCurrentContext(), property, const_cast(descriptor)); } From 99c84059328e0de023c00f49e7d6d96af24d0f12 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:24:07 -0300 Subject: [PATCH 18/20] test(runtime): canary state writes: repeat names, defines, deletes, class fields What a rebuilt canary shows is its state, so these write, delete and define names on a canary in patterns that a cached mirror could get wrong, then rebuild it and check the state: repeat writes interleaved with Java fields and prototype accessors, writes after a define that changed attributes, deleted names added again, one name on two objects, more than one rebuild, and class fields and TypeScript-style defines. --- test-app/app/src/main/assets/app/mainpage.js | 1 + .../tests/testWrapperLifetimeStateWrites.js | 312 ++++++++++++++++++ 2 files changed, 313 insertions(+) create mode 100644 test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 32b35a6dd..62f5789e7 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -62,6 +62,7 @@ require("./tests/testsForTypescript"); require("./tests/testGC"); require("./tests/testWrapperLifetime"); require("./tests/testWrapperLifetimeModes"); +require("./tests/testWrapperLifetimeStateWrites"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js new file mode 100644 index 000000000..bdb89f197 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js @@ -0,0 +1,312 @@ +// Writes, deletes and defines on a canary must reach its state exactly as they reach the +// canary itself: what a rebuilt canary shows is the state. Each spec writes in a function +// of its own, so no register keeps the canary alive across the collection. +describe("Wrapper lifetime state writes", function () { + var runtime = require("ns:runtime"); + var canary = runtime.getConfig("wrapperLifetimeMode") === "canary"; + var Holder = com.tns.tests.WrapperHolder; + var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); + + var Dummy = com.tns.tests.DummyClass.extend({}); + Object.defineProperty(Dummy.prototype, "acc", { + get: function () { + return this.accSeen; + }, + set: function (value) { + this.accSeen = value; + }, + enumerable: false, + configurable: true + }); + + function rebuilds() { + return runtime.getWrapperLifetimeStats().canaryRebuilds; + } + + function collect() { + for (var i = 0; i < 2; i++) { + gc(); + java.lang.System.nanoTime(); + java.lang.Runtime.getRuntime().gc(); + java.lang.System.runFinalization(); + gc(); + java.lang.System.nanoTime(); + } + } + + function data(value, writable, enumerable, configurable) { + return { + value: value, + writable: writable !== false, + enumerable: enumerable !== false, + configurable: configurable !== false + }; + } + + // plant(object) runs on a new Dummy, then the Dummy is rebuilt from its state. + function rebuilt(plant) { + var before = rebuilds(); + (function () { + var object = new Dummy(); + plant(object); + Holder.held = object; + })(); + collect(); + var object = Holder.held; + if (canary) { + expect(rebuilds()).toBeGreaterThan(before); + } + return object; + } + + afterEach(function () { + Holder.held = null; + }); + + it("keeps repeat writes of a name across writes of other names, a Java field and a prototype accessor", function () { + var symbol = Symbol("repeat"); + var object = rebuilt(function (o) { + o.a = 1; + o.b = 1; + o.a = 2; + o.nameField = "java"; + o.a = 3; + o.acc = 5; + o.a = 4; + o[symbol] = 1; + o.b = 2; + o[symbol] = 2; + // More names written in turn than one object's cache entries hold. + for (var i = 0; i < 10; i++) { + o.a = i; + o.c = i; + o.d = i; + o.e = i; + o.f = i; + o.g = i; + } + o.nameField = "java again"; + o.acc = 6; + }); + expect(Object.keys(object).sort()).toEqual(["a", "accSeen", "b", "c", "d", "e", "f", "g"]); + expect(Object.getOwnPropertyDescriptor(object, "a")).toEqual(data(9)); + expect(object.b).toBe(2); + expect(object.g).toBe(9); + expect(object[symbol]).toBe(2); + expect(object.accSeen).toBe(6); + expect(hasOwn(object, "acc")).toBe(false); + expect(hasOwn(object, "nameField")).toBe(false); + expect(object.getName()).toBe("java again"); + }); + + it("keeps a write after a define that changed the property's attributes", function () { + var object = rebuilt(function (o) { + o.a = 1; + o.a = 2; + Object.defineProperty(o, "a", { writable: false }); + o.a = 3; + o.b = 1; + o.b = 2; + Object.defineProperty(o, "b", { enumerable: false }); + o.b = 3; + o.c = 1; + o.c = 2; + Object.defineProperty(o, "c", { value: 3, writable: true, enumerable: true, configurable: true }); + o.c = 4; + }); + expect(Object.getOwnPropertyDescriptor(object, "a")).toEqual(data(2, false)); + expect(Object.getOwnPropertyDescriptor(object, "b")).toEqual(data(3, true, false)); + expect(Object.getOwnPropertyDescriptor(object, "c")).toEqual(data(4)); + expect(function () { + "use strict"; + object.a = 5; + }).toThrow(); + object.b = 4; + expect(object.b).toBe(4); + }); + + it("sends a write past a deleted own property that shadowed a Java field or a prototype accessor", function () { + var object = rebuilt(function (o) { + Object.defineProperty(o, "nameField", data("own")); + o.nameField = "own 2"; + o.nameField = "own 3"; + expect(o.getName()).toBe("dummy"); + delete o.nameField; + o.nameField = "java"; + o.nameField = "java 2"; + Object.defineProperty(o, "acc", data(1)); + o.acc = 2; + o.acc = 3; + delete o.acc; + o.acc = 4; + o.acc = 5; + }); + expect(hasOwn(object, "nameField")).toBe(false); + expect(object.nameField).toBe("java 2"); + expect(object.getName()).toBe("java 2"); + expect(hasOwn(object, "acc")).toBe(false); + expect(object.accSeen).toBe(5); + expect(Object.keys(object)).toEqual(["accSeen"]); + }); + + it("keeps a name deleted and added again, and drops one deleted for good", function () { + var symbol = Symbol("deleted"); + var object = rebuilt(function (o) { + o.a = 1; + o.a = 2; + delete o.a; + o.a = 3; + o.a = 4; + o.b = 1; + o.b = 2; + delete o.b; + o[symbol] = 1; + o[symbol] = 2; + delete o[symbol]; + o[symbol] = 3; + }); + expect(Object.keys(object)).toEqual(["a"]); + expect(object.a).toBe(4); + expect("b" in object).toBe(false); + expect(object[symbol]).toBe(3); + }); + + it("keeps one name written on two objects in turn apart", function () { + var before = rebuilds(); + (function () { + var first = new Dummy(); + var second = new Dummy(); + first.x = 1; + second.x = 1; + first.x = 2; + second.x = 2; + delete first.x; + second.x = 3; + first.x = 4; + first.y = 1; + second.y = 1; + first.y = 2; + var list = new java.util.ArrayList(); + list.add(first); + list.add(second); + Holder.held = list; + })(); + collect(); + var first = Holder.held.get(0); + var second = Holder.held.get(1); + if (canary) { + expect(rebuilds()).toBeGreaterThan(before + 1); + } + expect(Object.keys(first)).toEqual(["x", "y"]); + expect(first.x).toBe(4); + expect(first.y).toBe(2); + expect(Object.keys(second)).toEqual(["x", "y"]); + expect(second.x).toBe(3); + expect(second.y).toBe(1); + }); + + it("keeps a canary's state across more than one rebuild", function () { + var object = rebuilt(function (o) { + o.a = 1; + o.b = 1; + }); + (function () { + var o = Holder.held; + o.a = 2; + o.a = 3; + o.c = 1; + delete o.b; + o.b = 2; + })(); + object = null; + collect(); + object = Holder.held; + expect(Object.keys(object)).toEqual(["a", "c", "b"]); + expect([object.a, object.b, object.c]).toEqual([3, 2, 1]); + }); + + // Class fields define their property, the way Object.defineProperty does: one shadowing a + // Java field is an own property, and the Java field keeps its value. + var fieldSymbol = Symbol("field"); + function Base() { + return new Dummy(); + } + class WithFields extends Base { + plain = 1; + ["computed"] = 2; + [fieldSymbol] = 3; + nameField = "field"; + acc = 4; + } + var TsFields = (function (_super) { + __extends(TsFields, _super); + function TsFields() { + var _this = _super.call(this) || this; + Object.defineProperty(_this, "plain", { enumerable: true, configurable: true, writable: true, value: 1 }); + Object.defineProperty(_this, "nameField", { enumerable: true, configurable: true, writable: true, value: "field" }); + return __native(_this); + } + return TsFields; + })(com.tns.tests.DummyClass); + + function expectFields(object) { + expect(Object.getOwnPropertyDescriptor(object, "plain")).toEqual(data(1)); + expect(Object.getOwnPropertyDescriptor(object, "computed")).toEqual(data(2)); + expect(Object.getOwnPropertyDescriptor(object, fieldSymbol)).toEqual(data(3)); + expect(Object.getOwnPropertyDescriptor(object, "nameField")).toEqual(data("field")); + expect(Object.getOwnPropertyDescriptor(object, "acc")).toEqual(data(4)); + expect(object.accSeen).toBeUndefined(); + expect(object.getName()).toBe("dummy"); + } + + function plantFields(warm) { + var before = rebuilds(); + (function () { + var made; + for (var i = 0; i < warm; i++) { + made = new WithFields(); + } + made = new WithFields(); + expectFields(made); + Holder.held = made; + })(); + collect(); + var object = Holder.held; + if (canary) { + expect(rebuilds()).toBeGreaterThan(before); + } + return object; + } + + it("keeps class fields defined on a JS-extended object, cold", function () { + expectFields(plantFields(0)); + }); + + it("keeps class fields defined on a JS-extended object, warm", function () { + var object = plantFields(3000); + expectFields(object); + object.plain = 5; + object = null; + collect(); + expect(Holder.held.plain).toBe(5); + }); + + it("keeps fields a TypeScript-style subclass defines in its constructor", function () { + var before = rebuilds(); + (function () { + var made; + for (var i = 0; i < 1000; i++) { + made = new TsFields(); + } + Holder.held = made; + })(); + collect(); + var object = Holder.held; + if (canary) { + expect(rebuilds()).toBeGreaterThan(before); + } + expect(Object.getOwnPropertyDescriptor(object, "plain")).toEqual(data(1)); + expect(Object.getOwnPropertyDescriptor(object, "nameField")).toEqual(data("field")); + expect(object.getName()).toBe("dummy"); + }); +}); From 7a1c9580374e1ed2693a560cf1839018aaa9f5b1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:26:21 -0300 Subject: [PATCH 19/20] perf(runtime): canary handlers find their manager and registration without V8 calls The handlers read the ObjectManager from an isolate data slot instead of unwrapping an External, and CanaryOfInstance reads the JsInfo internal field's Smi directly instead of going through GetInternalField, which creates a handle and looks the current isolate up through emulated TLS. Ids outside the Smi range still take LinkedIdOf. --- .../runtime/src/main/cpp/ObjectManager.cpp | 13 -------- test-app/runtime/src/main/cpp/ObjectManager.h | 33 ++++++++++++++++++- test-app/runtime/src/main/cpp/Runtime.cpp | 1 + test-app/runtime/src/main/cpp/Runtime.h | 4 ++- .../src/main/cpp/WrapperLifetimeCanary.cpp | 20 ++++++----- 5 files changed, 47 insertions(+), 24 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 6ff0c1eb2..078c4b1fb 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -839,19 +839,6 @@ bool ObjectManager::CanaryStateForWrite(const Local& holder, Local& holder) { - int id = LinkedIdOf(holder); - if (id == -1) { - return nullptr; - } - auto state = m_idToObject.Find(id); - // A `super` object shares its owner's id but is not the canary. - if (state == nullptr || !state->canary || !state->linked || *state->target != holder) { - return nullptr; - } - return state; -} - Local ObjectManager::StateOf(CanaryHandle* canary) { CanaryRecord* record = canary->record; return record != nullptr && !record->state.IsEmpty() ? record->state.Get(m_isolate) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 838a8d618..cce49a9e6 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -206,7 +206,7 @@ class ObjectManager { using CanaryHandle = ObjectWeakCallbackState; // holder's live canary registration, or null. holder must be an instance of // a template with the canary handlers (it has the Metadata field). - CanaryHandle* CanaryOfInstance(const v8::Local& holder); + inline CanaryHandle* CanaryOfInstance(const v8::Local& holder); // The canary's state object, empty if it has none yet. v8::Local StateOf(CanaryHandle* canary); // Whether every property of the canary's state is a writable, enumerable, @@ -524,6 +524,37 @@ class ObjectManager { v8::Persistent m_jsWrapperTemplate; }; +inline ObjectManager::CanaryHandle* ObjectManager::CanaryOfInstance( + const v8::Local& holder) { + // The JsInfo field read as Object::GetInternalField does, without the handle + // and the current-isolate lookup it costs; an id past the Smi range takes + // LinkedIdOf. + using A = v8::internal::Address; + using I = v8::internal::Internals; + A object = v8::internal::ValueHelper::ValueAsAddress(*holder); + int id = -1; + if (V8_LIKELY(I::CanHaveInternalField(I::GetInstanceType(object)))) { + A field = I::ReadRawField(object, I::kJSAPIObjectWithEmbedderSlotsHeaderSize + + I::kEmbedderDataSlotSize * + static_cast(MetadataNodeKeys::JsInfo)); +#ifdef V8_COMPRESS_POINTERS + field = static_cast(field); +#endif + if (V8_LIKELY(!I::HasHeapObjectTag(field))) { + id = I::SmiValue(field) - 1; + } + } + if (V8_UNLIKELY(id == -1)) { + id = LinkedIdOf(holder); + } + auto state = m_idToObject.Find(id); + // A `super` object shares its owner's id but is not the canary. + if (state == nullptr || !state->canary || !state->linked || *state->target != holder) { + return nullptr; + } + return state; +} + inline v8::Local ObjectManager::CachedPlainState( CanaryHandle* canary, const v8::Local& property) { CanaryRecord* record = canary->record; diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index f97869679..ba7260109 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -1002,6 +1002,7 @@ Isolate* Runtime::PrepareV8Runtime(const string& filesPath, auto consts = new V8StringConstants::PerIsolateV8Constants(isolate); isolate->SetData((uint32_t)Runtime::IsolateData::RUNTIME, this); isolate->SetData((uint32_t)Runtime::IsolateData::CONSTANTS, consts); + isolate->SetData((uint32_t)Runtime::IsolateData::OBJECT_MANAGER, m_objectManager); isolate->SetCaptureStackTraceForUncaughtExceptions(true, 100, StackTrace::kOverview); diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 178894eb6..c74572d6d 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -61,7 +61,9 @@ class Runtime { enum IsolateData { RUNTIME = 0, CONSTANTS = 1, - WORKER_WRAPPER = 2 + WORKER_WRAPPER = 2, + // The isolate's ObjectManager, for the canary write handlers. + OBJECT_MANAGER = 3 }; /* diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index 8129ed812..dc75128c4 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -44,9 +44,9 @@ Local OwnerOf(Local context, Local holder, Local return object; } -ObjectManager* ObjectManagerOf(Local data) { +ObjectManager* ObjectManagerOf(Isolate* isolate) { return static_cast( - data.As()->Value(v8::kExternalPointerTypeTagDefault)); + isolate->GetData(static_cast(Runtime::IsolateData::OBJECT_MANAGER))); } // Mirrors a write of a name the state already has; false if the state lacks it. @@ -86,9 +86,9 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can // becomes state. V8 calls the setter only when the canary is the receiver. Intercepted Setter(Local property, Local value, const PropertyCallbackInfo& info) { - ObjectManager* objectManager = ObjectManagerOf(info.Data()); + ObjectManager* objectManager = ObjectManagerOf(info.GetIsolate()); // v8::Object::DefineOwnProperty reaches the setter, not the definer. - if (objectManager->CopyingCanaryProperties()) { + if (V8_UNLIKELY(objectManager == nullptr || objectManager->CopyingCanaryProperties())) { return Intercepted::kNo; } Local holder = info.Holder(); @@ -158,7 +158,10 @@ Intercepted Setter(Local property, Local value, } Intercepted Deleter(Local property, const PropertyCallbackInfo& info) { - ObjectManager* objectManager = ObjectManagerOf(info.Data()); + ObjectManager* objectManager = ObjectManagerOf(info.GetIsolate()); + if (objectManager == nullptr) { + return Intercepted::kNo; + } ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(info.Holder()); if (canary == nullptr) { return Intercepted::kNo; @@ -176,8 +179,8 @@ Intercepted Deleter(Local property, const PropertyCallbackInfo& i // receiver that lacks `x` reach here. Intercepted Definer(Local property, const PropertyDescriptor& descriptor, const PropertyCallbackInfo& info) { - ObjectManager* objectManager = ObjectManagerOf(info.Data()); - if (objectManager->CopyingCanaryProperties()) { + ObjectManager* objectManager = ObjectManagerOf(info.GetIsolate()); + if (objectManager == nullptr || objectManager->CopyingCanaryProperties()) { return Intercepted::kNo; } ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(info.Holder()); @@ -232,10 +235,9 @@ void WrapperLifetimeCanary::ConfigureInstanceTemplate(Local inst return; } NS_CHECK(objectManager != nullptr); - Isolate* isolate = Isolate::GetCurrent(); instanceTemplate->SetHandler(NamedPropertyHandlerConfiguration( nullptr, Setter, nullptr, Deleter, nullptr, Definer, nullptr, - External::New(isolate, objectManager, v8::kExternalPointerTypeTagDefault), + Local(), PropertyHandlerFlags::kNone)); } From 76d08d2e33bea66a4db16c1c9c1b80a22723257b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:27:12 -0300 Subject: [PATCH 20/20] perf(runtime): keep the canary setter's uncached path out of line The setter's cache hit path stays small; the classification of a write the cache cannot place moves to a noinline function. Whole series, measured on an arm64 phone (release build, canary/all), ratio to the canary head, median of 3 interleaved launches: hot JS loop, per write 0.79 (2318 -> 1794 instructions) expando write of an existing name 0.76 (2303 -> 1767 instructions) write inside a Java->JS callback 0.80 (2361 -> 1833 instructions) write between two callbacks 0.84 write of a new name / first write 1.00 / 0.99 delete + re-add, defineProperty 0.97-1.02 V8's declined-store fallback (about 990 instructions) is unchanged; the trivial-handler floor is 0.42 of the canary head's hot-loop write. --- .../runtime/src/main/cpp/ObjectManager.cpp | 6 -- test-app/runtime/src/main/cpp/ObjectManager.h | 8 ++- .../src/main/cpp/WrapperLifetimeCanary.cpp | 65 +++++++++++-------- 3 files changed, 44 insertions(+), 35 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 078c4b1fb..a3a66a8d9 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -849,12 +849,6 @@ bool ObjectManager::StateIsPlain(CanaryHandle* canary) { return canary->record == nullptr || !canary->record->stateNotPlain; } -void ObjectManager::StateChanging(CanaryHandle* canary) { - if (canary->record != nullptr && !canary->record->shell.IsEmpty()) { - canary->record->shell.Reset(); - } -} - void ObjectManager::SetStateNotPlain(CanaryHandle* canary) { if (canary->record != nullptr) { canary->record->stateNotPlain = true; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index cce49a9e6..7021e1a16 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -215,7 +215,7 @@ class ObjectManager { void SetStateNotPlain(CanaryHandle* canary); // Before the handlers change the canary's state: a shell copied from an // earlier state can no longer stand in for it. - void StateChanging(CanaryHandle* canary); + inline void StateChanging(CanaryHandle* canary); // The canary's state object, created on its first write. v8::Local StateForWrite(CanaryHandle* canary); // The canary's state when its plain state is known to have `property` as an @@ -555,6 +555,12 @@ inline ObjectManager::CanaryHandle* ObjectManager::CanaryOfInstance( return state; } +inline void ObjectManager::StateChanging(CanaryHandle* canary) { + if (canary->record != nullptr && !canary->record->shell.IsEmpty()) { + canary->record->shell.Reset(); + } +} + inline v8::Local ObjectManager::CachedPlainState( CanaryHandle* canary, const v8::Local& property) { CanaryRecord* record = canary->record; diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index dc75128c4..37b59bcee 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -77,35 +77,14 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can return true; } -// The handlers mirror: each copies its write into the state and declines, so -// V8 also applies it to the canary, where reads find a real own property and -// never call into C++. There is no getter, query, enumerator or descriptor -// callback for the same reason. The handlers are masking, so they also see -// names the prototype chain has. After the setter declines, V8 adds a new name -// to the canary without calling the definer, so the setter itself decides what -// becomes state. V8 calls the setter only when the canary is the receiver. -Intercepted Setter(Local property, Local value, - const PropertyCallbackInfo& info) { - ObjectManager* objectManager = ObjectManagerOf(info.GetIsolate()); - // v8::Object::DefineOwnProperty reaches the setter, not the definer. - if (V8_UNLIKELY(objectManager == nullptr || objectManager->CopyingCanaryProperties())) { - return Intercepted::kNo; - } - Local holder = info.Holder(); - ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(holder); - if (canary == nullptr) { - return Intercepted::kNo; - } - objectManager->CountCanaryWrite(); - Isolate* isolate = info.GetIsolate(); +// A write the name cache could not place: classifies it from the state and +// the canary's prototype chain. +[[gnu::noinline]] Intercepted MirrorUncachedWrite(ObjectManager* objectManager, + ObjectManager::CanaryHandle* canary, + Local holder, Local property, + Local value, Isolate* isolate) { Local context = isolate->GetCurrentContext(); - Local state = objectManager->CachedPlainState(canary, property); - if (!state.IsEmpty()) { - objectManager->StateChanging(canary); - (void)state->Set(context, property, value); - return Intercepted::kNo; - } - state = objectManager->StateOf(canary); + Local state = objectManager->StateOf(canary); // Own on the state means own on the canary: a rewrite of a JS property. if (!state.IsEmpty() && RewriteState(objectManager, canary, context, state, property, value)) { @@ -157,6 +136,36 @@ Intercepted Setter(Local property, Local value, return Intercepted::kNo; } +// The handlers mirror: each copies its write into the state and declines, so +// V8 also applies it to the canary, where reads find a real own property and +// never call into C++. There is no getter, query, enumerator or descriptor +// callback for the same reason. The handlers are masking, so they also see +// names the prototype chain has. After the setter declines, V8 adds a new name +// to the canary without calling the definer, so the setter itself decides what +// becomes state. V8 calls the setter only when the canary is the receiver. +Intercepted Setter(Local property, Local value, + const PropertyCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + ObjectManager* objectManager = ObjectManagerOf(isolate); + // v8::Object::DefineOwnProperty reaches the setter, not the definer. + if (V8_UNLIKELY(objectManager == nullptr || objectManager->CopyingCanaryProperties())) { + return Intercepted::kNo; + } + Local holder = info.Holder(); + ObjectManager::CanaryHandle* canary = objectManager->CanaryOfInstance(holder); + if (V8_UNLIKELY(canary == nullptr)) { + return Intercepted::kNo; + } + objectManager->CountCanaryWrite(); + Local state = objectManager->CachedPlainState(canary, property); + if (V8_LIKELY(!state.IsEmpty())) { + objectManager->StateChanging(canary); + (void)state->Set(isolate->GetCurrentContext(), property, value); + return Intercepted::kNo; + } + return MirrorUncachedWrite(objectManager, canary, holder, property, value, isolate); +} + Intercepted Deleter(Local property, const PropertyCallbackInfo& info) { ObjectManager* objectManager = ObjectManagerOf(info.GetIsolate()); if (objectManager == nullptr) {