From ef1a543bfc27c045a549e9937fdd0514cf92d3d6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 13:51:34 -0300 Subject: [PATCH 01/31] 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. Every wrapper of a Java object is a phantom-weak canary that dies with its JS references. On one in scope, 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) keeps the state of JS-extended instances only: other wrappers are canaries without a write handler or state, and a wrapper built after one died starts without the old one's JS properties. "all" keeps the state of every wrapper of a Java object. ns:runtime gains getWrapperClassCounts() and canary counters. --- docs/ns-builtin-modules.md | 66 ++- 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 | 447 ++++++++++++++++++ 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 | 399 +++++++++++++++- test-app/runtime/src/main/cpp/ObjectManager.h | 98 +++- test-app/runtime/src/main/cpp/Runtime.cpp | 3 +- .../runtime/src/main/cpp/WrapperLifetime.cpp | 8 +- .../runtime/src/main/cpp/WrapperLifetime.h | 19 + .../src/main/cpp/WrapperLifetimeCanary.cpp | 266 +++++++++++ .../src/main/cpp/WrapperLifetimeCanary.h | 75 +++ .../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, 1649 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 3262440a4..639887e9a 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,67 @@ 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. Canaries without state 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 only array buffers backed by Java buffers resurrect; +`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. Every wrapper of a Java object is a canary: a phantom-weak JS +object that dies with its JS references. `scope` chooses which canaries keep +their JS properties: + +| mode / scope | JS-extended instances | other wrappers | +|---|---|---| +| `"resurrecting"` (either scope) | resurrected | resurrected | +| `"canary"` / `"extended"` (default) | canaries with state | canaries without state | +| `"canary"` / `"all"` | canaries with state | canaries with state | + +- **State.** On a canary with state, a masking named interceptor (a setter, a + deleter and a definer, nothing that runs on reads) mirrors every JS property + written to the 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. +- **Canaries without state.** Under `"extended"`, the wrapper of a Java + object that is not a JS-extended instance (Java arrays included) has no write + handler and no state. Once JS drops it, it dies and Java no longer holds the + object for JS; when Java hands the object back later, its wrapper is a new + object without the old one's JS properties. JS properties on plain native + objects are therefore not preserved under `"extended"`: keep such state on a + JS object of your own, or use `"all"`, which gives every wrapper state. + Array buffers backed by Java buffers keep the `"resurrecting"` lifetime under + either scope. + +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 59f5ad709..d7451c67f 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..26340afe3 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -0,0 +1,447 @@ +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); + }); + + // Under "extended" a plain wrapper is a canary without state: nothing resurrects it, + // and Java stops holding its object for JS once it dies. + it("lets plain wrappers die without resurrecting them, under scope extended", function () { + if (!canary || scope !== "extended") { + return; + } + var list = new java.util.ArrayList(); + collectBoth(); + var before = stats(); + (function () { + for (var i = 0; i < 20; i++) { + list.add(new java.lang.StringBuilder("plain" + i)); + } + })(); + gc(); + crossIntoJava(); + var after = stats(); + expect(after.resurrections).toBe(before.resurrections); + expect(after.collected - before.collected).not.toBeLessThan(20); + expect(after.canaryStates).toBe(before.canaryStates); + expect(list.get(0).toString()).toBe("plain0"); + }); + + it("builds a new wrapper without the old one's JS properties for a plain object Java hands back, under scope extended", function () { + (function () { + var holder = new java.lang.StringBuilder("holder"); + holder.tag = "plain"; + Holder.held = holder; + })(); + collectBoth(); + + var holder = Holder.held; + expect(holder.toString()).toBe("holder"); + if (canary && scope === "extended") { + expect(holder.tag).toBeUndefined(); + expect(Object.keys(holder)).toEqual([]); + } else { + expect(holder.tag).toBe("plain"); + } + }); + + it("counts a plain wrapper as a canary without state, under scope extended", function () { + if (!canary || scope !== "extended") { + return; + } + var states = stats().canaryStates; + var plain = new java.lang.StringBuilder("counted"); + plain.tag = 1; + var entry = runtime.getWrapperClassCounts()["java.lang.StringBuilder"]; + expect(entry.canaries).toBeGreaterThan(0); + expect(entry.states).toBe(0); + expect(stats().canaryStates).toBe(states); + expect(Object.isFrozen(Object.freeze(plain))).toBe(true); + }); + + // An interface implementation Java hands back after its link was released gets a plain + // wrapper built from the interface's template, which carries the write handlers. + it("keeps no state for a plain wrapper whose template carries the write handlers, under scope extended", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + Holder.held = runnable; + __releaseNativeCounterpart(runnable); + var again = Holder.held; + expect(again).not.toBe(runnable); + var states = stats().canaryStates; + again.tag = "plain"; + expect(again.tag).toBe("plain"); + if (canary && scope === "all") { + expect(stats().canaryStates).toBe(states + 1); + } else { + expect(stats().canaryStates).toBe(states); + } + }); + + it("releases a plain wrapper's link and lets Java hand its object back in a new wrapper", function () { + var plain = new java.lang.StringBuilder("released"); + plain.tag = "released"; + Holder.held = plain; + var before = stats(); + __releaseNativeCounterpart(plain); + expect(stats().releasedExplicitly).toBe(before.releasedExplicitly + 1); + expect(function () { + plain.toString(); + }).toThrowError(/no longer has available Java instance counterpart/); + expect(plain.tag).toBe("released"); + + var again = Holder.held; + expect(again).not.toBe(plain); + expect(again.toString()).toBe("released"); + expect(again.tag).toBeUndefined(); + }); + + 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 307db3370..e50fbb951 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -242,6 +242,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 8800c1561..989ba76a4 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -243,7 +243,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 15eb80cac..4492aceeb 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); @@ -1354,6 +1357,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; @@ -2304,6 +2312,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 b6d2f900f..bb868b960 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( @@ -374,7 +392,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)); @@ -504,6 +522,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); } @@ -524,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) { + jclass clazz, LinkKind kind) { if (!IsJsRuntimeObject(object)) { string errMsg("Trying to link invalid 'this' to a Java object"); throw NativeScriptException(errMsg); @@ -537,9 +561,17 @@ 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::Enabled() && HasMetadataField(object); + state->keepsState = + state->canary && WrapperLifetimeCanary::InScope(kind == LinkKind::kExtended); + 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); @@ -548,6 +580,337 @@ 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) { + auto state = CanaryOf(holder); + return state != nullptr && state->keepsState; +} + +bool ObjectManager::ExistingCanaryState(const Local& holder, Local* out) { + auto state = CanaryOf(holder); + if (state == nullptr || !state->keepsState) { + 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 || !state->keepsState) { + 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, @@ -670,7 +1033,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 @@ -681,6 +1045,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(); @@ -813,6 +1186,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); @@ -935,6 +1318,8 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { javaObjectID); m_releaseCount++; 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. @@ -972,3 +1357,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 46f55c2bf..299c68c00 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 @@ -71,7 +72,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(); } } @@ -103,8 +105,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); @@ -172,6 +178,30 @@ class ObjectManager { const WrapperLifetimeStats& GetLifetimeStats() const { return m_lifetimeStats; } + // Canary mode (WrapperLifetimeCanary), for its write handlers. holder is a + // live canary in scope: 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(); @@ -206,6 +236,29 @@ 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; + // A canary in scope: the write handlers mirror its JS properties. Its + // template can carry them while it is not, e.g. an interface proxy's. + bool keepsState = 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; @@ -255,6 +308,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); @@ -332,6 +424,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 a2eec376d..80ea2220d 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -711,7 +711,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..be65fe848 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -14,9 +14,19 @@ 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: every wrapper is a canary that dies + // with its JS references. The JS properties of one in scope 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 { + // The JS properties kept are those of instances Java can call into JS + // through: JS-extended classes and interface implementations. Under + // kCanary, other wrappers are canaries without state, and a wrapper built + // after one died starts empty. kExtended, kAll, }; @@ -54,6 +64,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..ab4b5e6ca --- /dev/null +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.h @@ -0,0 +1,75 @@ +#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 is a canary: a phantom-weak JS object that dies with +// its JS references. On a canary in scope, a masking named interceptor with +// only a setter, deleter and definer mirrors every JS property written to it +// 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: their JS properties are state only under + // scope "all". + kPlain, + }; + + static bool Enabled() { + return GetWrapperLifetimeMode() == WrapperLifetimeMode::kCanary; + } + + // Whether the JS properties of a canary linked as `extended` are state. + 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 4fb065fc8..887cce586 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 "RuntimeGates.h" #include "NativeScriptException.h" #include "CallbackHandlers.h" @@ -542,3 +543,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 460fadcbe..7ec5a5452 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; /** @@ -226,6 +227,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; @@ -251,10 +322,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 573d1e64e..6f97764af 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 deb0f9708f7bdb78e3987643cb41fa71c6e38e94 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 18:02:35 -0300 Subject: [PATCH 02/31] 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. - Docs: where states are let go of, what weakened counts, which wrappers refuse freeze, and class names. --- docs/ns-builtin-modules.md | 15 +++-- .../runtime/src/main/cpp/ArgConverter.cpp | 6 +- .../runtime/src/main/cpp/ObjectManager.cpp | 23 ++++++-- test-app/runtime/src/main/cpp/ObjectManager.h | 5 +- .../java/com/tns/WrapperLifetimeWatcher.java | 55 +++++++++++-------- 5 files changed, 69 insertions(+), 35 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 639887e9a..a3b4aea09 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,9 +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 only array buffers backed by Java buffers resurrect; -`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. +`weakened` counts objects held weakly because their 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. Every wrapper of a Java object is a canary: a phantom-weak JS @@ -221,7 +221,9 @@ their JS properties: - **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 @@ -244,7 +246,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 any wrapper built from a template that carries the write handler +(JS-extended instances, and 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 e5d31e1d6..8fb783b53 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" @@ -151,9 +152,12 @@ void ArgConverter::ConvertJavaArgsToJsArgs(Isolate* isolate, JNIEnv* env, const auto hintedObjectID = static_cast(bits); auto classIndex = static_cast((bits >> 32) & 0x7fffffff); // JS run since the call started (the method lookup) may have reached the - // argument another way and released its id; it is then resolved again. + // argument another way and released its id; it is then resolved again. In + // canary mode a settle may also have released a fresh id whose canary another + // thread made and dropped before this call took the lock. if ((bits & JavaCallArgs::FreshArg) != 0 && objectManager->ReleaseCount() == args.releasesAtStart && + !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 bb868b960..a300868c2 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()) { @@ -797,10 +800,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); } } @@ -837,6 +840,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; } @@ -1187,8 +1197,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 299c68c00..50006d42f 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -187,7 +187,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 { @@ -345,6 +347,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/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 518111ffe78282f25952158ce3d9b0f5df6e0419 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 15:28:30 -0300 Subject: [PATCH 03/31] 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 26340afe3..94206efec 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 87a50406c6ae6e6c15569c300832d8f06659ca53 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 15:36:29 -0300 Subject: [PATCH 04/31] 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 a3b4aea09..710eb5ef4 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -245,7 +245,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 any wrapper built from a template that carries the write handler (JS-extended instances, and 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 2665c3c99031521721dfa02bc0c800aa292d29af Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 18:59:06 -0300 Subject: [PATCH 05/31] 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 4510e950d0ac5e8985c59b99cac87e5bcbf1fd03 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 19:07:24 -0300 Subject: [PATCH 06/31] 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 94206efec..2c418e320 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -398,7 +398,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 e0af9f17d6deab02b79da9d1c9db87e10ebd4a9d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 07/31] 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 2c418e320..16bf48e7e 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -400,6 +400,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 80ea2220d..2d780d9eb 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -625,8 +625,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 6f97764af..23452353f 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1726,6 +1726,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 @@ -1736,7 +1737,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 3c4d852881be1bb250f695cc7e595422ff56905a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 18:01:34 -0300 Subject: [PATCH 08/31] 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 release count the call already records covers it: a canary settle that releases ids now bumps it, as an explicit release does. The runtime passes its multithreaded-JS flag to native at init for this. --- test-app/runtime/src/main/cpp/ArgConverter.cpp | 8 ++++---- test-app/runtime/src/main/cpp/ObjectManager.cpp | 3 +++ test-app/runtime/src/main/cpp/ObjectManager.h | 12 ++++++++++-- test-app/runtime/src/main/cpp/Runtime.cpp | 1 + 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 ++-- 7 files changed, 24 insertions(+), 10 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ArgConverter.cpp b/test-app/runtime/src/main/cpp/ArgConverter.cpp index 8fb783b53..f4550221d 100644 --- a/test-app/runtime/src/main/cpp/ArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/ArgConverter.cpp @@ -152,12 +152,12 @@ void ArgConverter::ConvertJavaArgsToJsArgs(Isolate* isolate, JNIEnv* env, const auto hintedObjectID = static_cast(bits); auto classIndex = static_cast((bits >> 32) & 0x7fffffff); // JS run since the call started (the method lookup) may have reached the - // argument another way and released its id; it is then resolved again. In - // canary mode a settle may also have released a fresh id whose canary another - // thread made and dropped before this call took the lock. + // argument another way and released its id; it is then resolved again. Under + // multithreaded JS a canary settle may also release a fresh id before this call + // takes the lock, which the count cannot see. if ((bits & JavaCallArgs::FreshArg) != 0 && objectManager->ReleaseCount() == args.releasesAtStart && - !WrapperLifetimeCanary::Enabled() && + (!WrapperLifetimeCanary::Enabled() || !objectManager->MultithreadedJavascript()) && !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 a300868c2..9ae453560 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -828,6 +828,9 @@ bool ObjectManager::FlushCanaryDeaths() { JniLocalRef releaseArray(toJava(release)); bool failed = (!weaken.empty() && weakenArray.IsNull()) || (!release.empty() && releaseArray.IsNull()); + if (!release.empty()) { + m_releaseCount++; + } 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 50006d42f..7b57088fe 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -78,10 +78,16 @@ class ObjectManager { } } - // Ids JS released explicitly (ReleaseNativeCounterpart). While this does not move, an - // id Java registered for a call is still registered. + // Ids JS released explicitly (ReleaseNativeCounterpart), and canary settles that + // released ids. While this does not move, an id Java registered for a call is still + // registered. uint64_t ReleaseCount() const { return m_releaseCount; } + // 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; } + // Whether a wrapper was ever created for this id and not yet collected. bool HasJsObject(int javaObjectID) const { return m_idToObject.Find(javaObjectID) != nullptr; @@ -409,6 +415,8 @@ class ObjectManager { bool m_useGlobalRefs; + bool m_multithreadedJavascript = false; + 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 2d780d9eb..d76862852 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -240,6 +240,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"); diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 28b29f26b..7d74a180a 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -160,6 +160,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 887cce586..7a430ea9e 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -98,7 +98,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{ @@ -108,7 +108,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 23452353f..79fe731d8 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 e867f45e03aebb08eedd8007f99528826da00163 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 09/31] 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 9ae453560..b578a8c6a 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -426,7 +426,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 d2173d6f4592da399c9a8a3fc08e23210c02ece8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:17:41 -0300 Subject: [PATCH 10/31] docs(runtime): canary limits: finalize() calls, prototypes, #private - 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. --- docs/ns-builtin-modules.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 710eb5ef4..b3c9ad871 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -245,13 +245,19 @@ 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 +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 any wrapper built from a template that carries the write handler (JS-extended instances, and 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 45e432ba378cfe1a7978b37607baf4b9c8ab610d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 20:21:51 -0300 Subject: [PATCH 11/31] 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 0f4e6e84322977d712a96d70de02c8f718c7ddfe Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 20 Nov 2026 23:39:19 -0300 Subject: [PATCH 12/31] 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 4492aceeb..08f6a4758 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); @@ -615,6 +616,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 { @@ -631,17 +643,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) { @@ -653,6 +686,7 @@ void MetadataNode::FieldAccessorSetterCallback(const FunctionCallbackInfo NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } + return true; } void MetadataNode::PropertyAccessorGetterCallback(const FunctionCallbackInfo& info) { @@ -804,6 +838,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, @@ -826,6 +866,7 @@ class MetadataNode::PrototypeTemplateFiller { private: Local m_protoTemplate; std::unordered_set m_addedNames; + std::vector> m_fields; }; void MetadataNode::SetInstanceMembers( @@ -1361,7 +1402,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; @@ -1398,6 +1440,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 */); @@ -2313,7 +2372,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 2cad92ba9..3c3b91090 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 b578a8c6a..32769ae51 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); } @@ -742,12 +747,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->keepsState || !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(); @@ -1212,8 +1257,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 7b57088fe..0ce64a76f 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -193,6 +193,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. @@ -213,6 +244,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 { @@ -249,6 +282,8 @@ class ObjectManager { // A canary in scope: the write handlers mirror its JS properties. Its // template can carry them while it is not, e.g. an interface proxy's. bool keepsState = 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 @@ -267,6 +302,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; @@ -352,9 +389,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 ab4b5e6ca..c39fdc46e 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). // @@ -53,12 +54,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 26b762b85da7a14861867af65f7dc54954b88823 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 01:20:22 -0300 Subject: [PATCH 13/31] 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 16bf48e7e..c02e97f0c 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 989ba76a4..dec5daa33 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -215,7 +215,8 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j const std::string &baseClassName, uint64_t defaultOverrides, const vector *contentMemberNames, - jclass *resolvedClass) { + jclass *resolvedClass, + Local instanceTemplate) { bool success; DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str()); @@ -248,7 +249,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 d9f9d71b6..d0fa3f8f5 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -43,7 +43,8 @@ namespace tns { const std::string &baseClassName = std::string(), uint64_t defaultOverrides = 0, const std::vector *contentMemberNames = nullptr, - jclass *resolvedClass = nullptr); + jclass *resolvedClass = 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 08f6a4758..9ba71d488 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)); } @@ -1595,7 +1602,8 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn bool success = CallbackHandlers::RegisterInstance(isolate, thiz, extData->fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides, extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, - &extData->resolvedClass); + &extData->resolvedClass, + extData->instanceTemplate.Get(isolate)); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -1664,7 +1672,11 @@ void MetadataNode::InterfaceConstructorCallback(const v8::FunctionCallbackInfoGetInstanceTemplate(isolate, node->GetInstanceData(isolate)) + : Local()); if (frame.check()) { frame.log("Interface constructor: " + node->m_name); @@ -2371,6 +2383,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 3c3b91090..cefdd727e 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(v8::Isolate* isolate, 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); @@ -325,11 +331,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 32769ae51..31c721a93 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; @@ -552,7 +547,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); @@ -1259,7 +1270,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 0ce64a76f..f7e0c9fa6 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -115,8 +115,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); @@ -291,13 +295,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. @@ -363,7 +364,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); @@ -387,8 +393,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 d76862852..ea3393475 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -707,8 +707,9 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, Local implementationObject; DEBUG_WRITE("createJSInstanceNative class %s", jniName.c_str()); + Local instanceTemplate; jsInstance = MetadataNode::CreateExtendedJSWrapper(isolate, m_objectManager, - jniName); + jniName, &instanceTemplate); if (jsInstance.IsEmpty()) { throw NativeScriptException( @@ -727,7 +728,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 c39fdc46e..17917df82 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 6ed93d53a7c215279d8efaf8eb7c525f5d5ff70d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 01:21:02 -0300 Subject: [PATCH 14/31] 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 c02e97f0c..eb6d5098e 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 31c721a93..b57621d51 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -442,7 +442,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 f7e0c9fa6..57e89dfbd 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -98,7 +98,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 ea3393475..2d2a09466 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -620,7 +620,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, args.releasesAtStart = m_objectManager->ReleaseCount(); // 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 35819a5dc4f4401a32f10624ac203a375f37f6f6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 01:22:24 -0300 Subject: [PATCH 15/31] 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 f4550221d..c8cc96ed3 100644 --- a/test-app/runtime/src/main/cpp/ArgConverter.cpp +++ b/test-app/runtime/src/main/cpp/ArgConverter.cpp @@ -167,10 +167,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 b57621d51..0d9936a4e 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -462,12 +462,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, @@ -524,10 +528,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) { @@ -541,7 +551,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; } @@ -551,6 +561,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 57e89dfbd..56c4c24c2 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 @@ -108,6 +109,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); @@ -362,10 +367,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. @@ -380,6 +392,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 45e1055ba1233964566312ddb86e8a5042444d59 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 02:54:12 -0300 Subject: [PATCH 16/31] 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 | 130 ++++++++-------- 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, 264 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 eb6d5098e..07331df7e 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 dec5daa33..1e9e69fb1 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -216,7 +216,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j uint64_t defaultOverrides, const vector *contentMemberNames, jclass *resolvedClass, - 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 d0fa3f8f5..cc05eaa47 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -44,7 +44,7 @@ namespace tns { uint64_t defaultOverrides = 0, const std::vector *contentMemberNames = nullptr, jclass *resolvedClass = 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 9ba71d488..6e6791c66 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(); @@ -1603,7 +1603,7 @@ void MetadataNode::ExtendedClassConstructorCallback(const v8::FunctionCallbackIn bool success = CallbackHandlers::RegisterInstance(isolate, thiz, extData->fullClassName, argWrapper, implementationObject, false, extData->node->m_name, extData->defaultOverrides, extData->contentMemberNames ? &*extData->contentMemberNames : nullptr, &extData->resolvedClass, - extData->instanceTemplate.Get(isolate)); + &extData->instanceTemplate); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -1676,7 +1676,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 cefdd727e..7fbeeddeb 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(v8::Isolate* isolate, 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 0d9936a4e..40fa19244 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -531,7 +531,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()) { @@ -551,7 +551,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; } @@ -560,13 +560,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,9 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary(const Local& obj if (!EnsureJavaStrong(javaObjectID, record)) { return nullptr; } - if (!record->state.IsEmpty()) { + // Out of scope, a record never holds JS properties for the canary. + if (hydrate && !record->state.IsEmpty() && + WrapperLifetimeCanary::InScope(kind == LinkKind::kExtended)) { auto context = m_isolate->GetCurrentContext(); if (context.IsEmpty()) { context = Runtime::GetRuntime(m_isolate)->GetContext(); @@ -640,45 +653,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 +690,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 +698,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); } @@ -813,6 +819,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 56c4c24c2..8a32ec14c 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -121,12 +121,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); @@ -219,6 +219,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); @@ -301,9 +304,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; @@ -368,21 +379,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 2d2a09466..07b2025b0 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -707,7 +707,7 @@ void Runtime::CreateJSInstanceNative(JNIEnv* _env, jobject obj, Local implementationObject; DEBUG_WRITE("createJSInstanceNative class %s", jniName.c_str()); - Local instanceTemplate; + const Persistent* instanceTemplate = nullptr; jsInstance = MetadataNode::CreateExtendedJSWrapper(isolate, m_objectManager, jniName, &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 17917df82..03f4e696f 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 fdf6e3e656aa14b3e19a2ec93d35ba63b78986f1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:21:15 -0300 Subject: [PATCH 17/31] 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 b3c9ad871..0165f2128 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. Canaries without state 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 only array buffers backed by Java buffers resurrect; 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 40fa19244..a63c28533 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -665,7 +665,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) { @@ -1306,6 +1352,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 8a32ec14c..3ad811297 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -224,6 +224,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 @@ -409,6 +419,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. @@ -507,6 +534,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 be65fe848..1879e4d29 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -70,6 +70,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 b31d24430f44e5bcd56b5bc7bdc02d4495376b0e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:24:07 -0300 Subject: [PATCH 18/31] 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 d7451c67f..03a758089 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 05d43d0d108dedf15676032bc0bf92627c508276 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:26:21 -0300 Subject: [PATCH 19/31] 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 a63c28533..c26d61d88 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -842,19 +842,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->keepsState || !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 3ad811297..343434939 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -212,7 +212,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, @@ -535,6 +535,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->keepsState || !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 07b2025b0..2737174a6 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -984,6 +984,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 7d74a180a..32aa95b2e 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 ccf4ad7a742dea1b2ca21b0780a1565e96ce2d17 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 04:27:12 -0300 Subject: [PATCH 20/31] 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 c26d61d88..ab15b58a2 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -852,12 +852,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 343434939..99ecac208 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -221,7 +221,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 @@ -566,6 +566,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) { From 30cc978fde0aecca05d6f04e0e0fe35e3f1643a1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 15:26:01 -0300 Subject: [PATCH 21/31] perf(runtime): wrap an object whose id Java already knew by its class index getOrCreateJavaObjectIDAndClass returns the class index only for an object it registered in that call, since a known id almost always has a live wrapper. In canary mode the object of a dead canary keeps its id until the next settle (and for good when it has a record), so a Java field read or method return that handed it back to JS was wrapped through the slow class lookup: GetObjectClass, the class name and a FindClass by name. WrapperClassFor now asks Java for the missing index (getClassIndex), one call, and takes the cached path. Returning the index with every id instead cost about 10% on returns of already-wrapped objects. --- test-app/runtime/src/main/cpp/ObjectManager.cpp | 13 +++++++++++++ test-app/runtime/src/main/cpp/ObjectManager.h | 2 ++ test-app/runtime/src/main/java/com/tns/Runtime.java | 8 +++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index ab15b58a2..827850709 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -60,6 +60,10 @@ void ObjectManager::InitializeJNI() { runtimeClass, "getOrCreateJavaObjectIDAndClass", "(Ljava/lang/Object;)J"); NS_CHECK(GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID != nullptr); + GET_CLASS_INDEX_METHOD_ID = env.GetMethodID( + runtimeClass, "getClassIndex", "(Ljava/lang/Object;)I"); + NS_CHECK(GET_CLASS_INDEX_METHOD_ID != nullptr); + FIND_JAVA_OBJECT_ID_METHOD_ID = env.GetMethodID( runtimeClass, "findJavaObjectID", "(Ljava/lang/Object;)I"); NS_CHECK(FIND_JAVA_OBJECT_ID_METHOD_ID != nullptr); @@ -488,6 +492,13 @@ const std::string& ObjectManager::WrapperClassFor(int classIndex, jclass& clazz, std::string& scratch, MetadataNode*& node) { + if (classIndex <= 0 && instance != nullptr) { + // getOrCreateJavaObjectIDAndClass leaves the index out for an id Java + // already knew, such as a dead canary's object's. One call for it is + // cheaper than looking the class up by name. + JEnv env; + classIndex = env.CallIntMethod(m_javaRuntimeObject, GET_CLASS_INDEX_METHOD_ID, instance); + } if (classIndex > 0 && static_cast(classIndex) < m_wrapperClasses.size() && m_wrapperClasses[classIndex] != nullptr) { @@ -1495,6 +1506,8 @@ jclass ObjectManager::JAVA_LANG_CLASS = nullptr; jmethodID ObjectManager::GET_NAME_METHOD_ID = nullptr; jmethodID ObjectManager::GET_JAVAOBJECT_BY_ID_METHOD_ID = nullptr; jmethodID ObjectManager::GET_OR_CREATE_JAVA_OBJECT_ID_METHOD_ID = nullptr; +jmethodID ObjectManager::GET_CLASS_INDEX_METHOD_ID = nullptr; + jmethodID ObjectManager::GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID = nullptr; jmethodID ObjectManager::FIND_JAVA_OBJECT_ID_METHOD_ID = nullptr; diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 99ecac208..7d0b635ad 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -520,6 +520,8 @@ class ObjectManager { static jmethodID GET_OR_CREATE_JAVA_OBJECT_ID_AND_CLASS_METHOD_ID; + static jmethodID GET_CLASS_INDEX_METHOD_ID; + static jmethodID FIND_JAVA_OBJECT_ID_METHOD_ID; static jmethodID MAKE_INSTANCE_STRONG_METHOD_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 79fe731d8..dc51b898b 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1347,7 +1347,8 @@ private int findJavaObjectID(Object obj) { } // The class index is only needed to create a wrapper, and an object that already has - // an id almost always has one; native asks for the class itself when it does not. + // an id almost always has one; native asks for the index (getClassIndex) when it does + // not, e.g. for the object of a canary that died. @RuntimeCallable private long getOrCreateJavaObjectIDAndClass(Object obj) { long found = getOrCreateObjectId(obj); @@ -1357,6 +1358,11 @@ private long getOrCreateJavaObjectIDAndClass(Object obj) { return packIdAndClass((int) found, obj); } + @RuntimeCallable + private int getClassIndex(Object obj) { + return classIndexOf(obj.getClass()); + } + @RuntimeCallable private int getOrCreateJavaObjectID(Object obj) { long found = getOrCreateObjectId(obj); From 42e70dec88491cff2e7e5bd9ff034223000247b8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 14:58:28 -0300 Subject: [PATCH 22/31] docs(runtime): canary limits: a JS class extending a Java class without extend() --- docs/ns-builtin-modules.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 0165f2128..a53e63e27 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -258,7 +258,11 @@ 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. +the canary and do not carry over. A class that extends a Java class with +`class X extends java.lang.Object` and no `extend()` (Java cannot call its +overrides either) is linked as a plain wrapper: under `"extended"`, a canary +built later for one of its objects has the Java class's prototype, not +`X.prototype`, and none of the old canary's JS properties. 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 0d98b9f452eb703ad15f41d0cfb0886f197afc52 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 07:25:32 -0300 Subject: [PATCH 23/31] perf(runtime): cache where a canary's Java field writes land A Java field write through a canary's masking setter looked the name up along the prototype chain on every write before running the field's setter. The handler now caches the field by the name written and the canary's prototype. A hit rechecks the prototype, the canary's state and any prototypes between it and the field accessor's owner, then runs the setter; field accessors are non-configurable, so the owner itself needs no recheck. A write of a name with no entry reads one line of name tags and makes no V8 call. getWrapperLifetimeStats() counts the hits as canaryCachedFieldWrites. --- docs/ns-builtin-modules.md | 1 + test-app/app/src/main/assets/app/mainpage.js | 1 + .../assets/app/tests/fieldWritesWorker.js | 21 ++ .../assets/app/tests/testWrapperLifetime.js | 4 +- .../tests/testWrapperLifetimeFieldWrites.js | 304 ++++++++++++++++++ .../com/tns/tests/CanaryFieldFixtures.java | 34 ++ .../runtime/src/main/cpp/MetadataNode.cpp | 20 +- test-app/runtime/src/main/cpp/MetadataNode.h | 21 +- .../runtime/src/main/cpp/NsBuiltinModules.cpp | 1 + .../runtime/src/main/cpp/ObjectManager.cpp | 100 ++++++ test-app/runtime/src/main/cpp/ObjectManager.h | 67 +++- .../runtime/src/main/cpp/WrapperLifetime.h | 2 + .../src/main/cpp/WrapperLifetimeCanary.cpp | 27 +- 13 files changed, 575 insertions(+), 28 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/fieldWritesWorker.js create mode 100644 test-app/app/src/main/assets/app/tests/testWrapperLifetimeFieldWrites.js create mode 100644 test-app/app/src/main/java/com/tns/tests/CanaryFieldFixtures.java diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index a53e63e27..b0f381b55 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -193,6 +193,7 @@ every build on cold paths only: | `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object | | `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Canaries without state 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 | +| `canaryCachedFieldWrites` | `"canary"` only: of those writes, Java field writes the handler placed from an earlier write of the same name through an object with the same prototype, without looking the name up along the prototype chain | | `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object | In `"canary"` mode only array buffers backed by Java buffers resurrect; diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 03a758089..4205be807 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -63,6 +63,7 @@ require("./tests/testGC"); require("./tests/testWrapperLifetime"); require("./tests/testWrapperLifetimeModes"); require("./tests/testWrapperLifetimeStateWrites"); +require("./tests/testWrapperLifetimeFieldWrites"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); diff --git a/test-app/app/src/main/assets/app/tests/fieldWritesWorker.js b/test-app/app/src/main/assets/app/tests/fieldWritesWorker.js new file mode 100644 index 000000000..9bebead95 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/fieldWritesWorker.js @@ -0,0 +1,21 @@ +// Entry for testWrapperLifetimeFieldWrites: the same fields written from another runtime. +var Fixtures = com.tns.tests.CanaryFieldFixtures; +var result = { values: [] }; +try { + var leaf = new Fixtures.Leaf(); + leaf.f = 1; + leaf.f = 2; + result.values.push(leaf.getF()); + var Ext = Fixtures.Base.extend({}); + var ext = new Ext(); + ext.f = 2; + ext.f = 3; + result.values.push(ext.getF()); + leaf.f = 4; + result.values.push(leaf.getF()); + ext.f = 5; + result.values.push(ext.getF()); +} catch (e) { + result.error = String(e && e.message || e); +} +postMessage(result); 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 e69a3c91d..99fdb589e 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( - ["canaryCachedWrites", "canaryInterceptedWrites", "canaryNativeDeaths", "canaryRebuilds", - "canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); + ["canaryCachedFieldWrites", "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/app/src/main/assets/app/tests/testWrapperLifetimeFieldWrites.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeFieldWrites.js new file mode 100644 index 000000000..16c04591e --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeFieldWrites.js @@ -0,0 +1,304 @@ +// A canary's write handler runs a Java field's setter itself and caches where the field +// is, by name and the canary's prototype. Each spec writes once to fill that cache, then +// changes what the write should reach, then checks the next write reached it. +describe("Wrapper lifetime Java field writes", function () { + var runtime = require("ns:runtime"); + var mode = runtime.getConfig("wrapperLifetimeMode"); + var scope = runtime.getConfig("wrapperLifetimeScope"); + var canary = mode === "canary"; + var Fixtures = com.tns.tests.CanaryFieldFixtures; + var Base = Fixtures.Base; + var Leaf = Fixtures.Leaf; + var Holder = com.tns.tests.WrapperHolder; + var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty); + var ShadowBase = Fixtures.ShadowBase; + // Calls the Java getter even on an object whose prototype chain no longer has it. + function javaF(object) { + return (object instanceof ShadowBase ? ShadowBase : Base).prototype.getF.call(object); + } + + function cachedFieldWrites() { + return runtime.getWrapperLifetimeStats().canaryCachedFieldWrites; + } + + // Whether writes to `object` go through the canary write handler. + function handled(extended) { + return canary && (scope === "all" || extended); + } + + // Runs write() twice, expecting the cache to place at least one of them: a + // collection that moves the prototype in between turns a hit into a refill. + function expectCached(write, extended) { + var before = cachedFieldWrites(); + write(); + write(); + var hits = cachedFieldWrites() - before; + if (handled(extended)) { + expect(hits).toBeGreaterThan(0); + } else { + expect(hits).toBe(0); + } + } + + // Fills the cache with a write of object.f, then writes it from the cache. + function warm(object, extended) { + object.f = 10; + expectCached(function () { + object.f = 11; + }, extended); + expect(javaF(object)).toBe(11); + } + + function accessor(log) { + return { + get: function () { + return "js"; + }, + set: function (value) { + log.push(value); + }, + configurable: true + }; + } + + 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(); + } + } + + afterEach(function () { + Holder.held = null; + }); + + it("writes a field declared on the own, an extended or a farther class prototype from the cache", function () { + warm(new Base(), false); + warm(new Leaf(), false); + var Ext = Base.extend({}); + warm(new Ext(), true); + var LeafExt = Leaf.extend({}); + var deep = new LeafExt(); + warm(deep, true); + expect(Object.keys(deep)).toEqual([]); + }); + + it("writes one field name through more prototypes than a cache set has ways from the cache", function () { + var BaseExt = Base.extend({}); + var MidExt = Fixtures.Mid.extend({}); + var LeafExt = Leaf.extend({}); + var objects = [[new Base(), false], [new Fixtures.Mid(), false], [new Leaf(), false], + [new BaseExt(), true], [new MidExt(), true], [new LeafExt(), true]]; + objects.forEach(function (pair) { + pair[0].f = 1; + }); + var before = cachedFieldWrites(); + for (var pass = 0; pass < 2; pass++) { + objects.forEach(function (pair, i) { + pair[0].f = 100 + i; + }); + } + objects.forEach(function (pair, i) { + expect(javaF(pair[0])).toBe(100 + i); + }); + var expected = objects.filter(function (pair) { + return handled(pair[1]); + }).length; + var hits = cachedFieldWrites() - before; + if (expected > 0) { + expect(hits).not.toBeLessThan(expected); + } else { + expect(hits).toBe(0); + } + }); + + it("sends a write to an accessor defined later on a Java class prototype between the canary and the field", function () { + var ShadowMid = Fixtures.ShadowMid; + var leaf = new Fixtures.ShadowLeaf(); + var ext = new (Fixtures.ShadowLeaf.extend({}))(); + warm(leaf, false); + warm(ext, true); + var log = []; + Object.defineProperty(ShadowMid.prototype, "f", accessor(log)); + try { + leaf.f = 20; + ext.f = 21; + expect(log).toEqual([20, 21]); + expect(leaf.getF()).toBe(11); + expect(ext.getF()).toBe(11); + } finally { + delete ShadowMid.prototype.f; + } + leaf.f = 22; + ext.f = 23; + expect(leaf.getF()).toBe(22); + expect(ext.getF()).toBe(23); + expect(hasOwn(leaf, "f")).toBe(false); + }); + + it("sends a write to an accessor or a data property defined later on the extended class prototype", function () { + var WithAccessor = Base.extend({}); + var withAccessor = new WithAccessor(); + warm(withAccessor, true); + var log = []; + Object.defineProperty(WithAccessor.prototype, "f", accessor(log)); + withAccessor.f = 30; + expect(log).toEqual([30]); + expect(withAccessor.getF()).toBe(11); + + var WithData = Base.extend({}); + var withData = new WithData(); + warm(withData, true); + Object.defineProperty(WithData.prototype, "f", { value: 0, writable: true, configurable: true }); + withData.f = 31; + expect(hasOwn(withData, "f")).toBe(true); + expect(withData.getF()).toBe(11); + // The own property the write made now shadows the field. + delete WithData.prototype.f; + withData.f = 32; + expect(withData.f).toBe(32); + expect(withData.getF()).toBe(11); + delete withData.f; + withData.f = 33; + expect(withData.getF()).toBe(33); + expect(hasOwn(withData, "f")).toBe(false); + }); + + it("writes an own property defined on the instance, and the field again once it is deleted", function () { + [[new Base(), false], [new (Base.extend({}))(), true]].forEach(function (pair) { + var object = pair[0]; + warm(object, pair[1]); + Object.defineProperty(object, "f", { value: 40, writable: true, enumerable: true, configurable: true }); + object.f = 41; + expect(Object.getOwnPropertyDescriptor(object, "f").value).toBe(41); + expect(javaF(object)).toBe(11); + delete object.f; + expectCached(function () { + object.f = 42; + }, pair[1]); + expect(javaF(object)).toBe(42); + expect(hasOwn(object, "f")).toBe(false); + }); + }); + + it("writes an own property an object with JS state has, whichever object filled the cache", function () { + var Ext = Base.extend({}); + var other = new Ext(); + var own = new Ext(); + own.tag = "state"; + Object.defineProperty(own, "f", { value: 50, writable: true, enumerable: true, configurable: true }); + warm(other, true); + own.f = 51; + expect(own.f).toBe(51); + expect(own.getF()).toBe(1); + own.tag = "more"; + warm(other, true); + own.f = 52; + expect(own.f).toBe(52); + expect(own.getF()).toBe(1); + }); + + it("keeps apart a plain object of a class and an extended one whose prototype has its own accessor", function () { + var log = []; + var Own = Base.extend({}); + Object.defineProperty(Own.prototype, "f", accessor(log)); + + var plainFirst = new Base(); + var extendedSecond = new Own(); + warm(plainFirst, false); + extendedSecond.f = 60; + extendedSecond.f = 61; + + var extendedFirst = new Own(); + extendedFirst.f = 62; + extendedFirst.f = 63; + var plainSecond = new Base(); + warm(plainSecond, false); + + expect(log).toEqual([60, 61, 62, 63]); + expect(extendedSecond.getF()).toBe(1); + expect(extendedFirst.getF()).toBe(1); + expect(plainFirst.getF()).toBe(11); + }); + + it("writes the own property a rebuilt canary got from its state", function () { + var Rebuilt = Base.extend({}); + (function () { + var object = new Rebuilt(); + Object.defineProperty(object, "f", { value: 70, writable: true, enumerable: true, configurable: true }); + Holder.held = object; + })(); + collect(); + var object = Holder.held; + expect(hasOwn(object, "f")).toBe(true); + warm(new Rebuilt(), true); + object.f = 71; + expect(object.f).toBe(71); + expect(object.getF()).toBe(1); + }); + + it("throws for a final field on a cached write as on the first", function () { + [[new Base(), false], [new (Base.extend({}))(), true]].forEach(function (pair) { + var object = pair[0]; + var message = /final field/; + expect(function () { + object.fixed = 4; + }).toThrowError(message); + expectCached(function () { + expect(function () { + object.fixed = 5; + }).toThrowError(message); + }, pair[1]); + expect(object.fixed).toBe(3); + }); + }); + + it("follows a prototype chain that changed under a cached write", function () { + var plain = new Base(); + warm(plain, false); + Object.setPrototypeOf(plain, Object.prototype); + plain.f = 80; + expect(hasOwn(plain, "f")).toBe(true); + expect(javaF(plain)).toBe(11); + + var Detached = Base.extend({}); + var detached = new Detached(); + warm(detached, true); + Object.setPrototypeOf(Detached.prototype, Object.prototype); + detached.f = 81; + expect(hasOwn(detached, "f")).toBe(true); + expect(javaF(detached)).toBe(11); + + var Longer = Base.extend({}); + var longer = new Longer(); + warm(longer, true); + var log = []; + var inserted = Object.create(Base.prototype, { f: accessor(log) }); + Object.setPrototypeOf(Longer.prototype, inserted); + longer.f = 82; + expect(log).toEqual([82]); + expect(javaF(longer)).toBe(11); + }); + + it("writes fields from a worker, each runtime with its own cache", function (done) { + var worker = new Worker("./fieldWritesWorker.js"); + var main = new Leaf(); + warm(main, false); + worker.onmessage = function (msg) { + worker.terminate(); + expect(msg.data.error).toBeUndefined(); + expect(msg.data.values).toEqual([2, 3, 4, 5]); + main.f = 12; + expect(main.getF()).toBe(12); + done(); + }; + worker.onerror = function (e) { + worker.terminate(); + done.fail(String(e && e.message || e)); + }; + }); +}); diff --git a/test-app/app/src/main/java/com/tns/tests/CanaryFieldFixtures.java b/test-app/app/src/main/java/com/tns/tests/CanaryFieldFixtures.java new file mode 100644 index 000000000..1af792695 --- /dev/null +++ b/test-app/app/src/main/java/com/tns/tests/CanaryFieldFixtures.java @@ -0,0 +1,34 @@ +package com.tns.tests; + +// Targets for testWrapperLifetimeFieldWrites.js. The Shadow classes are only for +// specs that change their prototypes. +public class CanaryFieldFixtures { + public static class Base { + public int f = 1; + public final int fixed = 3; + + public int getF() { + return f; + } + } + + public static class Mid extends Base { + } + + public static class Leaf extends Mid { + } + + public static class ShadowBase { + public int f = 1; + + public int getF() { + return f; + } + } + + public static class ShadowMid extends ShadowBase { + } + + public static class ShadowLeaf extends ShadowMid { + } +} diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index 6e6791c66..241bd8281 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -665,23 +665,26 @@ void MetadataNode::FieldAccessorSetterCallback(const FunctionCallbackInfo } } -bool MetadataNode::TrySetInstanceField(Isolate* isolate, Local context, - Local fieldTableKey, Local owner, - Local receiver, Local property, - Local value) { +FieldCallbackData* MetadataNode::InstanceFieldOf(Local context, + Local fieldTableKey, + Local owner, Local property) { Local table; if (!owner->GetPrivate(context, fieldTableKey).ToLocal(&table) || !table->IsObject()) { - return false; + return nullptr; } Local entry; if (!table.As()->GetRealNamedProperty(context, property).ToLocal(&entry) || !entry->IsExternal()) { - return false; + return nullptr; } - auto fieldData = static_cast( + return static_cast( entry.As()->Value(v8::kExternalPointerTypeTagDefault)); +} + +void MetadataNode::SetInstanceFieldFromJs(Isolate* isolate, Local receiver, + Local value, FieldCallbackData* field) { try { - SetInstanceField(isolate, receiver, value, fieldData); + SetInstanceField(isolate, receiver, value, field); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { @@ -693,7 +696,6 @@ bool MetadataNode::TrySetInstanceField(Isolate* isolate, Local context, NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } - return true; } void MetadataNode::PropertyAccessorGetterCallback(const FunctionCallbackInfo& info) { diff --git a/test-app/runtime/src/main/cpp/MetadataNode.h b/test-app/runtime/src/main/cpp/MetadataNode.h index 7fbeeddeb..b856ba61f 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.h +++ b/test-app/runtime/src/main/cpp/MetadataNode.h @@ -38,16 +38,19 @@ 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. + * Canary mode: the Java instance field whose accessor the class + * prototype `owner` carries for `property`, or null 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 FieldCallbackData* InstanceFieldOf(v8::Local context, + v8::Local fieldTableKey, + v8::Local owner, + v8::Local property); + // Canary mode: runs field's setter as a write through receiver would, + // a failure thrown to JS. + static void SetInstanceFieldFromJs(v8::Isolate* isolate, v8::Local receiver, + v8::Local value, FieldCallbackData* field); static void Init(v8::Isolate* isolate); diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 4842e73a3..3c6e8bc72 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -179,6 +179,7 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { set("canaryNativeDeaths", stats.canaryNativeDeaths); set("canaryInterceptedWrites", stats.canaryInterceptedWrites); set("canaryCachedWrites", stats.canaryCachedWrites); + set("canaryCachedFieldWrites", stats.canaryCachedFieldWrites); 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 827850709..ffc23ba32 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -725,6 +725,97 @@ void ObjectManager::ForgetStateNames(CanaryRecord* record) { } } +FieldCallbackData* ObjectManager::CheckedInstanceField(CanaryHandle* canary, + const Local& holder, + const Local& property, + uint32_t tag) { + Local prototype = holder->GetPrototype(); + if (!prototype->IsObject()) { + return nullptr; + } + const FieldWrite* set = m_fieldWrites[FieldWriteSet(tag, prototype)]; + for (size_t way = 0; way < kFieldWriteWays; way++) { + const FieldWrite& entry = set[way]; + if (entry.name != property || entry.prototype != prototype) { + continue; + } + Local context = m_isolate->GetCurrentContext(); + // The state has every own property of the canary. + CanaryRecord* record = canary->record; + if (record != nullptr && !record->state.IsEmpty() && + record->state.Get(m_isolate)->HasRealNamedProperty(context, property).FromMaybe(true)) { + return nullptr; + } + Local object = prototype; + for (int i = 0; i < entry.depth; i++) { + Local below = object.As(); + if (below->HasRealNamedProperty(context, property).FromMaybe(true)) { + return nullptr; + } + object = below->GetPrototype(); + if (!object->IsObject()) { + return nullptr; + } + } + if (entry.depth > 0 && entry.owner != object) { + return nullptr; + } + // Every own property of a canary is in its state, so none can shadow the field. + NS_DCHECK(!holder->HasRealNamedProperty(context, property).FromMaybe(false)); + m_lifetimeStats.canaryCachedFieldWrites++; + return entry.field; + } + return nullptr; +} + +void ObjectManager::CacheInstanceField(const Local& holder, const Local& owner, + int depth, const Local& property, + FieldCallbackData* field) { + Local prototype = holder->GetPrototype(); + if (!prototype->IsObject() || depth < 0) { + return; + } + uint32_t tag = FieldNameTag(property); + size_t nameIndex = FieldNameSet(tag); + uint32_t* tags = m_fieldNameTags[nameIndex]; + if (std::find(tags, tags + kFieldNameWays, tag) == tags + kFieldNameWays) { + uint32_t* empty = std::find(tags, tags + kFieldNameWays, 0u); + if (empty == tags + kFieldNameWays) { + empty = &tags[m_fieldNameVictims[nameIndex]]; + m_fieldNameVictims[nameIndex] = (m_fieldNameVictims[nameIndex] + 1) % kFieldNameWays; + } + *empty = tag; + } + size_t index = FieldWriteSet(tag, prototype); + FieldWrite* set = m_fieldWrites[index]; + FieldWrite* entry = nullptr; + for (size_t way = 0; way < kFieldWriteWays && entry == nullptr; way++) { + if (set[way].name == property && set[way].prototype == prototype) { + entry = &set[way]; + } + } + for (size_t way = 0; way < kFieldWriteWays && entry == nullptr; way++) { + if (set[way].prototype.IsEmpty()) { + entry = &set[way]; + } + } + if (entry == nullptr) { + entry = &set[m_fieldWriteVictims[index]]; + m_fieldWriteVictims[index] = (m_fieldWriteVictims[index] + 1) % kFieldWriteWays; + } + entry->name.Reset(m_isolate, property); + entry->prototype.Reset(m_isolate, prototype.As()); + entry->prototype.SetWeak(); + if (depth > 0) { + entry->owner.Reset(m_isolate, owner); + entry->owner.SetWeak(); + } else { + entry->owner.Reset(); + } + entry->field = field; + entry->depth = depth; +} + bool ObjectManager::EnsureJavaStrong(int javaObjectID, CanaryRecord* record) { if (!record->javaWeak) { return true; @@ -1350,6 +1441,15 @@ void ObjectManager::ReleaseAllRegistered() { entry.name.Reset(); } } + for (auto& set : m_fieldWrites) { + for (FieldWrite& entry : set) { + entry.name.Reset(); + entry.prototype.Reset(); + entry.owner.Reset(); + entry.field = nullptr; + } + } + std::fill(&m_fieldNameTags[0][0], &m_fieldNameTags[0][0] + kFieldNameSets * kFieldNameWays, 0u); 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 7d0b635ad..4a13c686f 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -21,6 +21,7 @@ namespace tns { struct JavaCallArgs; +struct FieldCallbackData; class MetadataNode; class ObjectManager { @@ -234,12 +235,22 @@ class ObjectManager { 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); + // The Java instance field a write of `property` on the canary `holder` runs + // the setter of, when a cached earlier write through an object with holder's + // prototype still applies; null otherwise. + inline FieldCallbackData* CachedInstanceField(CanaryHandle* canary, + const v8::Local& holder, + const v8::Local& property); + // After a write of `property` on the canary `holder` found `field`'s + // accessor on `owner`, `depth` prototypes above holder's prototype. + void CacheInstanceField(const v8::Local& holder, const v8::Local& owner, + int depth, const v8::Local& property, FieldCallbackData* field); // 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 + // instance field accessors' data (MetadataNode::InstanceFieldOf); empty // in other modes. v8::Local InstanceFieldTableKey() { return m_instanceFieldTableKey.Get(m_isolate); @@ -436,6 +447,47 @@ class ObjectManager { uint8_t m_stateNameVictims[kStateNameSets] = {}; void ForgetStateNames(CanaryRecord* record); + // Java instance fields the write handler ran the setter of, by the name + // written and the canary's prototype. Field accessors are non-configurable, + // so a hit rechecks only what lies below the accessor's owner: the canary's + // state and the prototypes in between. Sets are picked by addresses, which a + // moving collection may change; the entry then just misses. + struct FieldWrite { + v8::Global name; + // Weak, as is owner: the cache keeps no prototype alive. + v8::Global prototype; + // Empty when the owner is the prototype itself. + v8::Global owner; + FieldCallbackData* field = nullptr; + int depth = 0; + }; + // The low half of a name's tagged address: never 0, and only a filter, as a + // name can move or its address be reused. + static uint32_t FieldNameTag(const v8::Local& name) { + return static_cast(v8::internal::ValueHelper::ValueAsAddress(*name)); + } + static constexpr size_t kFieldNameSets = 32; + static constexpr size_t kFieldNameWays = 4; + static size_t FieldNameSet(uint32_t tag) { + return ((tag >> 3) ^ (tag >> 9)) & (kFieldNameSets - 1); + } + // Tags of the names entries were made for, so a write of any other name + // reads one line and makes no V8 call. One name has entries for many + // prototypes (a field every LayoutParams subclass inherits). + uint32_t m_fieldNameTags[kFieldNameSets][kFieldNameWays] = {}; + uint8_t m_fieldNameVictims[kFieldNameSets] = {}; + static constexpr size_t kFieldWriteSets = 64; + static constexpr size_t kFieldWriteWays = 4; + static size_t FieldWriteSet(uint32_t tag, const v8::Local& prototype) { + auto address = static_cast(v8::internal::ValueHelper::ValueAsAddress(*prototype)); + uint32_t mixed = (address ^ tag) * 0x9E3779B1u; + return (mixed >> 26) & (kFieldWriteSets - 1); + } + FieldWrite m_fieldWrites[kFieldWriteSets][kFieldWriteWays]; + uint8_t m_fieldWriteVictims[kFieldWriteSets] = {}; + FieldCallbackData* CheckedInstanceField(CanaryHandle* canary, const v8::Local& holder, + const v8::Local& property, uint32_t tag); + // 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. @@ -589,6 +641,19 @@ inline v8::Local ObjectManager::CachedPlainState( } return v8::Local(); } + +inline FieldCallbackData* ObjectManager::CachedInstanceField(CanaryHandle* canary, + const v8::Local& holder, + const v8::Local& property) { + uint32_t tag = FieldNameTag(property); + const uint32_t* tags = m_fieldNameTags[FieldNameSet(tag)]; + for (size_t way = 0; way < kFieldNameWays; way++) { + if (tags[way] == tag) { + return CheckedInstanceField(canary, holder, property, tag); + } + } + return nullptr; +} } // 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 1879e4d29..6c1995d18 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -72,6 +72,8 @@ struct WrapperLifetimeStats { uint64_t canaryInterceptedWrites = 0; // "canary" only: of those, writes mirrored through the state name cache. uint64_t canaryCachedWrites = 0; + // "canary" only: of those, Java field writes placed by the field cache. + uint64_t canaryCachedFieldWrites = 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 37b59bcee..39c24b368 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -31,15 +31,19 @@ bool HasOwn(Local context, Local state, Local property) { } // 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) { +// `property`, interceptors skipped, and how many prototypes up from holder it +// is; empty if there is none. +Local OwnerOf(Local context, Local holder, Local property, + int* steps) { Local object = holder; + *steps = 0; while (!object->HasRealNamedProperty(context, property).FromMaybe(false)) { Local prototype = object->GetPrototype(); if (!prototype->IsObject()) { return Local(); } object = prototype.As(); + ++*steps; } return object; } @@ -100,15 +104,20 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can if ((attributes & ReadOnly) != 0) { return Intercepted::kNo; } - Local owner = OwnerOf(context, holder, property); + int steps; + Local owner = OwnerOf(context, holder, property, &steps); 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; + if (owner != holder) { + FieldCallbackData* field = MetadataNode::InstanceFieldOf( + context, objectManager->InstanceFieldTableKey(), owner, property); + if (field != nullptr) { + objectManager->CacheInstanceField(holder, owner, steps - 1, property, field); + MetadataNode::SetInstanceFieldFromJs(isolate, holder, value, field); + return Intercepted::kYes; + } } Maybe accessor = owner->HasRealNamedCallbackProperty(context, property); if (accessor.IsNothing() || accessor.FromJust()) { @@ -163,6 +172,10 @@ Intercepted Setter(Local property, Local value, (void)state->Set(isolate->GetCurrentContext(), property, value); return Intercepted::kNo; } + if (FieldCallbackData* field = objectManager->CachedInstanceField(canary, holder, property)) { + MetadataNode::SetInstanceFieldFromJs(isolate, holder, value, field); + return Intercepted::kYes; + } return MirrorUncachedWrite(objectManager, canary, holder, property, value, isolate); } From 0a015e29ce91d282f4788589d34db965f4e5be29 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:16:47 -0300 Subject: [PATCH 24/31] perf(runtime): create a canary's state with its first property A canary's first write looked the canary and its record up twice more and then added the property to an empty state in a second call. The state is now made holding the property, from the handle the write handler already has. --- .../runtime/src/main/cpp/ObjectManager.cpp | 37 +++++++++++++------ test-app/runtime/src/main/cpp/ObjectManager.h | 7 ++++ .../src/main/cpp/WrapperLifetimeCanary.cpp | 6 +-- 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index ffc23ba32..712746af5 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -927,21 +927,36 @@ bool ObjectManager::CanaryStateForWrite(const Local& holder, LocalkeepsState) { 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); + *out = AttachState(state, Object::New(m_isolate, Null(m_isolate), nullptr, nullptr, 0)); + return true; +} + +Local ObjectManager::AttachState(CanaryHandle* canary, const Local& fresh) { + CanaryRecord* record = canary->record; + if (record == nullptr) { + record = FindCanaryRecord(canary->javaObjectID); + } if (record == nullptr) { auto created = std::make_unique(); record = created.get(); - m_canaryRecords.emplace(id, std::move(created)); + m_canaryRecords.emplace(canary->javaObjectID, std::move(created)); } - state->record = record; + canary->record = record; record->state.Reset(m_isolate, fresh); m_lifetimeStats.canaryStates++; - *out = fresh; - return true; + return fresh; +} + +Local ObjectManager::NewStateWith(CanaryHandle* canary, Local property, + Local value) { + // JS the write handler ran after it found no state (a Proxy trap on the + // prototype chain) may have made one for the canary since. + Local existing = StateOf(canary); + if (!existing.IsEmpty()) { + (void)existing->CreateDataProperty(m_isolate->GetCurrentContext(), property, value); + return existing; + } + return AttachState(canary, Object::New(m_isolate, Null(m_isolate), &property, &value, 1)); } Local ObjectManager::StateOf(CanaryHandle* canary) { @@ -965,9 +980,7 @@ Local ObjectManager::StateForWrite(CanaryHandle* canary) { if (!existing.IsEmpty()) { return existing; } - Local state; - return CanaryStateForWrite(Local::New(m_isolate, *canary->target), &state) ? state - : Local(); + return AttachState(canary, Object::New(m_isolate, Null(m_isolate), nullptr, nullptr, 0)); } void ObjectManager::CanaryDiedStatic( diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 4a13c686f..cd7609a9a 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -225,6 +225,10 @@ class ObjectManager { inline void StateChanging(CanaryHandle* canary); // The canary's state object, created on its first write. v8::Local StateForWrite(CanaryHandle* canary); + // A new state for a canary that has none, holding `property` as a plain data + // property. + v8::Local NewStateWith(CanaryHandle* canary, v8::Local property, + v8::Local value); // 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, @@ -430,6 +434,9 @@ class ObjectManager { void EraseCanaryRecord(int javaObjectID); + // Makes fresh the state of canary's record, creating the record if needed. + v8::Local AttachState(CanaryHandle* canary, const v8::Local& fresh); + // 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. diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index 39c24b368..00fad0bfb 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -125,12 +125,8 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can } } if (state.IsEmpty()) { - state = objectManager->StateForWrite(canary); - if (state.IsEmpty()) { - return Intercepted::kNo; - } objectManager->StateChanging(canary); - (void)state->CreateDataProperty(context, property, value); + objectManager->NewStateWith(canary, property, value); } else if (objectManager->StateIsPlain(canary)) { // RewriteState found the name absent from the state. objectManager->StateChanging(canary); From 753dcaaa1e1c0cee76f166312a243c3095f87802 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:18:05 -0300 Subject: [PATCH 25/31] perf(runtime): skip the state lookup for a name a canary's state lacks A canary write the name cache misses looked the name up on the state before looking it up along the prototype chain, so a new name paid for two lookups. A record now keeps the tags of the first six names the handlers added to its plain state, and a write of a name without a tag goes straight to the prototype chain lookup. A stale tag only sends the write down that path, which also handles a name the canary already has. --- test-app/runtime/src/main/cpp/ObjectManager.h | 47 +++++++++++++++++++ .../src/main/cpp/WrapperLifetimeCanary.cpp | 7 ++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index cd7609a9a..8951b77dd 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -233,6 +233,11 @@ class ObjectManager { // own data property; empty when that is not known. inline v8::Local CachedPlainState(CanaryHandle* canary, const v8::Local& property); + // Whether the canary's state may have `property`; false only for a plain + // state that the handlers never added the name to as it is now. + inline bool StateMayHave(CanaryHandle* canary, const v8::Local& property); + // After the handlers added `property` to the canary's state. + inline void NoteStateName(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. @@ -347,6 +352,13 @@ class ObjectManager { bool javaWeak = false; // A define reached the state with an accessor or non-default attributes. bool stateNotPlain = false; + // Tags (FieldNameTag) of the names the handlers added to a plain state, so a + // write of a name without one skips looking the state up. A name that moved + // since has another tag; its write takes the path for a name the state lacks, + // which also handles one the canary has. Past kStateTags, every write looks. + static constexpr uint8_t kStateTags = 6; + uint8_t stateTagCount = 0; + uint32_t stateTags[kStateTags]; }; using JSInstanceInfo = ObjectWeakCallbackState; @@ -649,6 +661,41 @@ inline v8::Local ObjectManager::CachedPlainState( return v8::Local(); } +inline bool ObjectManager::StateMayHave(CanaryHandle* canary, + const v8::Local& property) { + CanaryRecord* record = canary->record; + if (record == nullptr || record->stateNotPlain || + record->stateTagCount > CanaryRecord::kStateTags) { + return true; + } + uint32_t tag = FieldNameTag(property); + for (uint8_t i = 0; i < record->stateTagCount; i++) { + if (record->stateTags[i] == tag) { + return true; + } + } + return false; +} + +inline void ObjectManager::NoteStateName(CanaryHandle* canary, + const v8::Local& property) { + CanaryRecord* record = canary->record; + if (record == nullptr || record->stateTagCount > CanaryRecord::kStateTags) { + return; + } + uint32_t tag = FieldNameTag(property); + for (uint8_t i = 0; i < record->stateTagCount; i++) { + if (record->stateTags[i] == tag) { + return; + } + } + if (record->stateTagCount == CanaryRecord::kStateTags) { + record->stateTagCount++; + return; + } + record->stateTags[record->stateTagCount++] = tag; +} + inline FieldCallbackData* ObjectManager::CachedInstanceField(CanaryHandle* canary, const v8::Local& holder, const v8::Local& property) { diff --git a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp index 00fad0bfb..855d243b4 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp +++ b/test-app/runtime/src/main/cpp/WrapperLifetimeCanary.cpp @@ -90,7 +90,7 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can Local context = isolate->GetCurrentContext(); Local state = objectManager->StateOf(canary); // Own on the state means own on the canary: a rewrite of a JS property. - if (!state.IsEmpty() && + if (!state.IsEmpty() && objectManager->StateMayHave(canary, property) && RewriteState(objectManager, canary, context, state, property, value)) { return Intercepted::kNo; } @@ -127,10 +127,12 @@ bool RewriteState(ObjectManager* objectManager, ObjectManager::CanaryHandle* can if (state.IsEmpty()) { objectManager->StateChanging(canary); objectManager->NewStateWith(canary, property, value); + objectManager->NoteStateName(canary, property); } else if (objectManager->StateIsPlain(canary)) { - // RewriteState found the name absent from the state. + // The state lacks the name, or has it as a plain data property. objectManager->StateChanging(canary); (void)state->CreateDataProperty(context, property, value); + objectManager->NoteStateName(canary, property); } else if (!HasOwn(context, state, property)) { objectManager->StateChanging(canary); (void)state->CreateDataProperty(context, property, value); @@ -218,6 +220,7 @@ Intercepted Definer(Local property, const PropertyDescriptor& descriptor, objectManager->ForgetStateName(canary, property); (void)state->DefineProperty(info.GetIsolate()->GetCurrentContext(), property, const_cast(descriptor)); + objectManager->NoteStateName(canary, property); } return Intercepted::kNo; } From 59cdf19a438a9cc9508cc389e2170a750340d533 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:19:11 -0300 Subject: [PATCH 26/31] perf(runtime): share an extended class's rebuild data between canary records Every JS-extended instance's canary record held its own four global handles to the prototype, CallSuper and Metadata fields and implementation object it registered with, though the instances of one class register with the same values. Records now point to a shared, reference-counted copy, found by the instance template and reused while the values match, so a record adds one global handle (its state) instead of five. An interface implementation, whose implementation object differs per instance, still gets its own copy. --- .../runtime/src/main/cpp/ObjectManager.cpp | 82 ++++++++++++++----- test-app/runtime/src/main/cpp/ObjectManager.h | 37 +++++++-- 2 files changed, 89 insertions(+), 30 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 712746af5..384f36814 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -542,7 +542,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->extended) { + if (record != nullptr && record->cls != nullptr) { // A JS-extended instance's canary starts from its record, not from its class. auto rebuilt = RebuildCanary(javaObjectID, record); if (!rebuilt.IsEmpty()) { @@ -630,20 +630,19 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary( // the prototype and fields this one was registered with. NS_DCHECK(instanceTemplate != nullptr); auto isolate = m_isolate; - auto created = std::make_unique(); - 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); + if (!V8GetPrivateValue(isolate, object, V8StringConstants::GetImplementationObject(isolate), + implementationObject)) { + implementationObject = Local(); } + CanaryClass* cls = CanaryClassFor( + instanceTemplate, object->GetPrototype(), + object->GetInternalField(static_cast(MetadataNodeKeys::CallSuper)).As(), + object->GetInternalField(static_cast(MetadataNodeKeys::Metadata)).As(), + implementationObject); + auto created = std::make_unique(); + created->cls = cls; + cls->records++; record = created.get(); m_canaryRecords.emplace(javaObjectID, std::move(created)); return record; @@ -664,6 +663,44 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary( return record; } +ObjectManager::CanaryRecord::~CanaryRecord() { + if (cls != nullptr && --cls->records == 0) { + if (cls->slot != nullptr && *cls->slot == cls) { + *cls->slot = nullptr; + } + delete cls; + } +} + +ObjectManager::CanaryClass* ObjectManager::CanaryClassFor( + const Persistent* instanceTemplate, const Local& prototype, + const Local& callSuper, const Local& metadata, + const Local& implementationObject) { + auto address = reinterpret_cast(instanceTemplate); + CanaryClass*& slot = m_canaryClasses[((address >> 4) ^ (address >> 9)) % kCanaryClassSlots]; + // Global == Local compares the objects, and an empty handle equals only an empty one. + if (slot != nullptr && slot->instanceTemplate == instanceTemplate && + slot->prototype == prototype && slot->callSuper == callSuper && + slot->metadata == metadata && slot->implementationObject == implementationObject) { + return slot; + } + auto isolate = m_isolate; + auto cls = new CanaryClass(); + cls->instanceTemplate = instanceTemplate; + cls->prototype.Reset(isolate, prototype); + cls->callSuper.Reset(isolate, callSuper); + cls->metadata.Reset(isolate, metadata); + if (!implementationObject.IsEmpty()) { + cls->implementationObject.Reset(isolate, implementationObject); + } + if (slot != nullptr) { + slot->slot = nullptr; + } + slot = cls; + cls->slot = &slot; + return cls; +} + ObjectManager::CanaryRecord* ObjectManager::FindCanaryRecord(int javaObjectID) { if (m_canaryRecords.empty()) { return nullptr; @@ -838,7 +875,7 @@ Local ObjectManager::RebuildCanary(int javaObjectID) { } Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* record) { - if (record == nullptr || !record->extended) { + if (record == nullptr || record->cls == nullptr) { return Local(); } auto isolate = m_isolate; @@ -853,27 +890,28 @@ Local ObjectManager::RebuildCanary(int javaObjectID, CanaryRecord* recor return handleScope.Escape(canary); } - NS_DCHECK(record->instanceTemplate != nullptr); - if (record->instanceTemplate == nullptr) { + const CanaryClass* cls = record->cls; + NS_DCHECK(cls->instanceTemplate != nullptr); + if (cls->instanceTemplate == nullptr) { return handleScope.Escape(Local()); } auto context = isolate->GetCurrentContext(); Local canary; - if (!record->instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&canary)) { + if (!cls->instanceTemplate->Get(isolate)->NewInstance(context).ToLocal(&canary)) { return handleScope.Escape(Local()); } - Local prototype = record->prototype.Get(isolate); + Local prototype = cls->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)); + cls->callSuper.Get(isolate)); canary->SetInternalField(static_cast(MetadataNodeKeys::Metadata), - record->metadata.Get(isolate)); - if (!record->implementationObject.IsEmpty()) { + cls->metadata.Get(isolate)); + if (!cls->implementationObject.IsEmpty()) { V8SetPrivateValue(isolate, canary, V8StringConstants::GetImplementationObject(isolate), - record->implementationObject.Get(isolate)); + cls->implementationObject.Get(isolate)); } m_lifetimeStats.canaryRebuilds++; Link(canary, javaObjectID, record->clazz, LinkKind::kExtended, nullptr, record); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index 8951b77dd..9c81087c4 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -329,19 +329,31 @@ class ObjectManager { CanaryRecord* record = nullptr; }; - // 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; + // Canary mode: what a canary built later for a JS-extended instance starts + // from, as the first canary had it once registered. The records of instances + // that registered with the same values share one; the last of them frees it. + struct CanaryClass { v8::Global prototype; v8::Global callSuper; v8::Global metadata; v8::Global implementationObject; const v8::Persistent* instanceTemplate = nullptr; + uint32_t records = 0; + // The m_canaryClasses slot offering it to new records, or null. + CanaryClass** slot = nullptr; + }; + + // 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 { + CanaryRecord() = default; + CanaryRecord(const CanaryRecord&) = delete; + CanaryRecord& operator=(const CanaryRecord&) = delete; + ~CanaryRecord(); + // The object's JS properties; empty until the first write. + v8::Global state; + // JS-extended instances only. + CanaryClass* cls = 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. @@ -512,6 +524,15 @@ class ObjectManager { // the ids are queued again. bool FlushCanaryDeaths(); + // The last class registered per instance template, by template address. + static constexpr size_t kCanaryClassSlots = 16; + CanaryClass* m_canaryClasses[kCanaryClassSlots] = {}; + // A class for a new extended record with these values, shared when they match. + CanaryClass* CanaryClassFor(const v8::Persistent* instanceTemplate, + const v8::Local& prototype, + const v8::Local& callSuper, + const v8::Local& metadata, + const v8::Local& implementationObject); std::unordered_map> m_canaryRecords; std::vector m_pendingCanaryDeaths; bool m_copyingCanaryProperties = false; From 302451da0c64865b706b03b4a554af41d344853b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:22:14 -0300 Subject: [PATCH 27/31] perf(runtime): keep canary records in the object id index Canary records lived in an unordered_map keyed by Java object id, so every canary registration paid a hashed lookup, and every record a node allocation and a hashed insert and erase. They now live in the same radix index the wrapper registrations use. --- .../runtime/src/main/cpp/ObjectManager.cpp | 46 +++++++++++-------- test-app/runtime/src/main/cpp/ObjectManager.h | 6 ++- 2 files changed, 31 insertions(+), 21 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 384f36814..2da4d8dc8 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -640,11 +640,9 @@ ObjectManager::CanaryRecord* ObjectManager::AdoptCanary( object->GetInternalField(static_cast(MetadataNodeKeys::CallSuper)).As(), object->GetInternalField(static_cast(MetadataNodeKeys::Metadata)).As(), implementationObject); - auto created = std::make_unique(); - created->cls = cls; + record = NewCanaryRecord(javaObjectID); + record->cls = cls; cls->records++; - record = created.get(); - m_canaryRecords.emplace(javaObjectID, std::move(created)); return record; } if (!EnsureJavaStrong(javaObjectID, record)) { @@ -702,21 +700,30 @@ ObjectManager::CanaryClass* ObjectManager::CanaryClassFor( } ObjectManager::CanaryRecord* ObjectManager::FindCanaryRecord(int javaObjectID) { - if (m_canaryRecords.empty()) { - return nullptr; + return m_canaryRecordCount == 0 ? nullptr : m_canaryRecords.Find(javaObjectID); +} + +ObjectManager::CanaryRecord* ObjectManager::NewCanaryRecord(int javaObjectID) { + auto record = new CanaryRecord(); + record->id = javaObjectID; + if (!m_canaryRecords.Insert(javaObjectID, record)) { + NS_DCHECK(false); + delete record; + return m_canaryRecords.Find(javaObjectID); } - auto it = m_canaryRecords.find(javaObjectID); - return it != m_canaryRecords.end() ? it->second.get() : nullptr; + m_canaryRecordCount++; + return record; } void ObjectManager::EraseCanaryRecord(int javaObjectID) { if (auto live = m_idToObject.Find(javaObjectID)) { live->record = nullptr; } - auto it = m_canaryRecords.find(javaObjectID); - if (it != m_canaryRecords.end()) { - ForgetStateNames(it->second.get()); - m_canaryRecords.erase(it); + if (CanaryRecord* record = FindCanaryRecord(javaObjectID)) { + ForgetStateNames(record); + m_canaryRecords.Erase(javaObjectID); + m_canaryRecordCount--; + delete record; } } @@ -975,9 +982,7 @@ Local ObjectManager::AttachState(CanaryHandle* canary, const LocaljavaObjectID); } if (record == nullptr) { - auto created = std::make_unique(); - record = created.get(); - m_canaryRecords.emplace(canary->javaObjectID, std::move(created)); + record = NewCanaryRecord(canary->javaObjectID); } canary->record = record; record->state.Reset(m_isolate, fresh); @@ -1171,16 +1176,16 @@ std::map ObjectManager::GetWrapperClass entry.canaries++; } }); - for (const auto& [id, record] : m_canaryRecords) { + m_canaryRecords.ForEach([&](CanaryRecord* record) { if (record->state.IsEmpty()) { - continue; + return; } jclass clazz = record->clazz; - if (auto live = m_idToObject.Find(id)) { + if (auto live = m_idToObject.Find(record->id)) { clazz = live->objectClazz; } counts[nameOf(clazz)].states++; - } + }); return counts; } @@ -1501,7 +1506,8 @@ void ObjectManager::ReleaseAllRegistered() { } } std::fill(&m_fieldNameTags[0][0], &m_fieldNameTags[0][0] + kFieldNameSets * kFieldNameWays, 0u); - m_canaryRecords.clear(); + m_canaryRecords.DrainAll([](CanaryRecord* record) { delete record; }); + m_canaryRecordCount = 0; 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 9c81087c4..6a06bf642 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -350,6 +350,7 @@ class ObjectManager { CanaryRecord(const CanaryRecord&) = delete; CanaryRecord& operator=(const CanaryRecord&) = delete; ~CanaryRecord(); + int id = -1; // The object's JS properties; empty until the first write. v8::Global state; // JS-extended instances only. @@ -533,7 +534,10 @@ class ObjectManager { const v8::Local& callSuper, const v8::Local& metadata, const v8::Local& implementationObject); - std::unordered_map> m_canaryRecords; + // Owns the records. + ObjectIdIndex m_canaryRecords; + size_t m_canaryRecordCount = 0; + CanaryRecord* NewCanaryRecord(int javaObjectID); std::vector m_pendingCanaryDeaths; bool m_copyingCanaryProperties = false; bool m_deathInboxOpen = false; From 116b4576013086dce809ad3c0586460a2340f92c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:49:41 -0300 Subject: [PATCH 28/31] test(runtime): cover canary records' name tags and shared class data Rewrites of names past the record's tags, of names added by a define, of a name made at run time across collections, and of a re-added name on a later canary; rebuilds of one class's instances, of interface implementations with their own implementation objects, of interleaved instances of more classes than the shared-data slots, and of a class whose earlier records were all freed. --- test-app/app/src/main/assets/app/mainpage.js | 1 + .../tests/testWrapperLifetimeRecordSharing.js | 232 ++++++++++++++++++ 2 files changed, 233 insertions(+) create mode 100644 test-app/app/src/main/assets/app/tests/testWrapperLifetimeRecordSharing.js diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 4205be807..5c5c185b5 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -64,6 +64,7 @@ require("./tests/testWrapperLifetime"); require("./tests/testWrapperLifetimeModes"); require("./tests/testWrapperLifetimeStateWrites"); require("./tests/testWrapperLifetimeFieldWrites"); +require("./tests/testWrapperLifetimeRecordSharing"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeRecordSharing.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeRecordSharing.js new file mode 100644 index 000000000..268c3ec53 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeRecordSharing.js @@ -0,0 +1,232 @@ +// What a canary record keeps between canaries: the names its state has, which decide +// whether a write must look the state up, and its class's rebuild data, which the +// records of one class share. A rebuilt canary shows both. +describe("Wrapper lifetime record sharing", 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({}); + + 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(); + } + } + + // 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; + } + + // Rebuilds every object a Java list holds; make(i) runs in a function of its own. + function rebuiltAll(count, make) { + var list = new java.util.ArrayList(); + (function () { + for (var i = 0; i < count; i++) { + list.add(make(i)); + } + })(); + var before = rebuilds(); + collect(); + var objects = []; + for (var i = 0; i < count; i++) { + objects.push(list.get(i)); + } + if (canary) { + expect(rebuilds()).toBeGreaterThan(before); + } + return objects; + } + + afterEach(function () { + Holder.held = null; + }); + + it("keeps rewrites of names written before and after more names than a record tags", function () { + var object = rebuilt(function (o) { + for (var i = 0; i < 10; i++) { + o["n" + i] = i; + } + o.n0 = "first"; + o.n9 = "last"; + o.n5 = "middle"; + }); + expect(Object.keys(object)).toEqual(["n0", "n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8", "n9"]); + expect([object.n0, object.n5, object.n9, object.n1]).toEqual(["first", "middle", "last", 1]); + }); + + it("keeps a rewrite of a name added by a define", function () { + var object = rebuilt(function (o) { + Object.defineProperty(o, "plain", { value: 1, writable: true, enumerable: true, configurable: true }); + o.plain = 2; + Object.defineProperty(o, "hidden", { value: 1, writable: true, enumerable: false, configurable: true }); + o.hidden = 2; + o.after = 1; + o.after = 2; + }); + expect(Object.getOwnPropertyDescriptor(object, "plain")).toEqual({ value: 2, writable: true, enumerable: true, configurable: true }); + expect(Object.getOwnPropertyDescriptor(object, "hidden")).toEqual({ value: 2, writable: true, enumerable: false, configurable: true }); + expect(object.after).toBe(2); + }); + + it("keeps a rewrite of a name made at run time, across collections", function () { + var object = rebuilt(function (o) { + var name = ["late", Date.now() % 7, "name"].join("_"); + o[name] = 1; + o.marker = name; + gc(); + gc(); + o[name] = 2; + o[String(name)] = 3; + }); + expect(object[object.marker]).toBe(3); + expect(Object.keys(object)).toEqual([object.marker, "marker"]); + }); + + it("keeps a name deleted and written again, then rewritten, on a later canary", function () { + var object = rebuilt(function (o) { + o.a = 1; + o.b = 1; + delete o.a; + o.a = 2; + }); + (function () { + var o = Holder.held; + o.a = 3; + o.b = 2; + o.c = 1; + o.c = 2; + })(); + object = null; + collect(); + object = Holder.held; + expect(Object.keys(object)).toEqual(["b", "a", "c"]); + expect([object.a, object.b, object.c]).toEqual([3, 2, 2]); + }); + + it("rebuilds instances of one class with the class's prototype and methods", function () { + var Cls = com.tns.tests.DummyClass.extend({ + tag: function () { + return "cls"; + } + }); + var objects = rebuiltAll(4, function (i) { + var o = new Cls(); + o.index = i; + return o; + }); + objects.forEach(function (o, i) { + expect(Object.getPrototypeOf(o)).toBe(Cls.prototype); + expect(o instanceof Cls).toBe(true); + expect(o.tag()).toBe("cls"); + expect(o.index).toBe(i); + expect(o.getName()).toBe("dummy"); + }); + }); + + it("rebuilds interface implementations with their own implementation object", function () { + var objects = rebuiltAll(3, function (i) { + return new java.lang.Runnable({ + run: function () { + this.ran = i; + }, + which: i + }); + }); + objects.forEach(function (o, i) { + expect(o.which).toBe(i); + o.run(); + expect(o.ran).toBe(i); + expect(hasOwn(o, "which")).toBe(false); + }); + expect(Object.getPrototypeOf(objects[0])).not.toBe(Object.getPrototypeOf(objects[1])); + }); + + it("rebuilds instances of more classes than a record can share data with at once", function () { + var D = com.tns.tests.DummyClass; + function k(n) { + return function () { + return n; + }; + } + // One per line: extend() names a class by where it is called. + var classes = [ + D.extend({ cls: k(0) }), + D.extend({ cls: k(1) }), + D.extend({ cls: k(2) }), + D.extend({ cls: k(3) }), + D.extend({ cls: k(4) }), + D.extend({ cls: k(5) }), + D.extend({ cls: k(6) }), + D.extend({ cls: k(7) }), + D.extend({ cls: k(8) }), + D.extend({ cls: k(9) }), + D.extend({ cls: k(10) }), + D.extend({ cls: k(11) }), + D.extend({ cls: k(12) }), + D.extend({ cls: k(13) }), + D.extend({ cls: k(14) }), + D.extend({ cls: k(15) }), + D.extend({ cls: k(16) }), + D.extend({ cls: k(17) }), + D.extend({ cls: k(18) }), + D.extend({ cls: k(19) }), + ]; + var count = classes.length; + // Classes interleaved, so instances of one class register between other classes'. + var objects = rebuiltAll(3 * count, function (i) { + var o = new classes[i % count](); + o.index = i; + return o; + }); + objects.forEach(function (o, i) { + expect(Object.getPrototypeOf(o)).toBe(classes[i % count].prototype); + expect(o.cls()).toBe(i % count); + expect(o.index).toBe(i); + }); + }); + + it("rebuilds an instance of a class whose earlier instances' records were all freed", function () { + var Cls = com.tns.tests.DummyClass.extend({ + tag: function () { + return "again"; + } + }); + (function () { + for (var i = 0; i < 50; i++) { + new Cls().index = i; + } + })(); + collect(); + collect(); + var objects = rebuiltAll(2, function (i) { + var o = new Cls(); + o.index = i; + return o; + }); + expect(objects[1].tag()).toBe("again"); + expect(Object.getPrototypeOf(objects[1])).toBe(Cls.prototype); + expect(objects[1].index).toBe(1); + }); +}); From 30ff36226d3b1a790f4e3f6b07801900959bef4d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 13:22:28 -0300 Subject: [PATCH 29/31] perf(runtime): make canary states fast-mode objects A state was made with Object::New and a null prototype, which V8 makes a dictionary-mode object. States are now clones of one empty fast-mode object with a null prototype, so states that get the same names in the same order share their maps' transitions. A 3-name state takes 104 bytes instead of 208. On a phone (release, canary/all, 6 rounds), against the commits before it: a canary's first write takes about 0.75 of its time, a new-name write 0.85, constructing a JS-extended instance with 1-5 fields 0.92-0.94, and a full collection with 10,000 live stateful canaries 0.80-0.88. Rewriting a name a state already has takes about 1.11, and 1.07 across 512 objects. --- .../runtime/src/main/cpp/ObjectManager.cpp | 21 ++++++++++++++++--- test-app/runtime/src/main/cpp/ObjectManager.h | 3 +++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 2da4d8dc8..9b3086c47 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -972,7 +972,7 @@ bool ObjectManager::CanaryStateForWrite(const Local& holder, LocalkeepsState) { return false; } - *out = AttachState(state, Object::New(m_isolate, Null(m_isolate), nullptr, nullptr, 0)); + *out = AttachState(state, NewEmptyState()); return true; } @@ -999,7 +999,21 @@ Local ObjectManager::NewStateWith(CanaryHandle* canary, Local prop (void)existing->CreateDataProperty(m_isolate->GetCurrentContext(), property, value); return existing; } - return AttachState(canary, Object::New(m_isolate, Null(m_isolate), &property, &value, 1)); + Local fresh = NewEmptyState(); + (void)fresh->CreateDataProperty(m_isolate->GetCurrentContext(), property, value); + return AttachState(canary, fresh); +} + +// A fast-mode object with a null prototype: states made from one copy share +// its map, so states that get the same names in the same order share their +// maps' transitions. Object::New with a null prototype makes a dictionary. +Local ObjectManager::NewEmptyState() { + if (m_emptyState.IsEmpty()) { + Local empty = Object::New(m_isolate); + (void)empty->SetPrototype(m_isolate->GetCurrentContext(), Null(m_isolate)); + m_emptyState.Reset(m_isolate, empty); + } + return m_emptyState.Get(m_isolate)->Clone(m_isolate); } Local ObjectManager::StateOf(CanaryHandle* canary) { @@ -1023,7 +1037,7 @@ Local ObjectManager::StateForWrite(CanaryHandle* canary) { if (!existing.IsEmpty()) { return existing; } - return AttachState(canary, Object::New(m_isolate, Null(m_isolate), nullptr, nullptr, 0)); + return AttachState(canary, NewEmptyState()); } void ObjectManager::CanaryDiedStatic( @@ -1509,6 +1523,7 @@ void ObjectManager::ReleaseAllRegistered() { m_canaryRecords.DrainAll([](CanaryRecord* record) { delete record; }); m_canaryRecordCount = 0; m_instanceFieldTableKey.Reset(); + m_emptyState.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 6a06bf642..e8da69dbe 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -544,6 +544,9 @@ class ObjectManager { bool m_canaryEpilogueAdded = false; int m_deathInboxRuntimeId = -1; v8::Persistent m_instanceFieldTableKey; + // Cloned for each new state; never handed to JS. + v8::Global m_emptyState; + v8::Local NewEmptyState(); void JSObjectFinalizer(v8::Isolate* isolate, ObjectWeakCallbackState* callbackState); From 9cc697a7eb7f74eacb97296cfad7ee72249154c2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 19:34:43 -0300 Subject: [PATCH 30/31] fix(runtime): count an object constructed from JS under its class RegisterInstance links the wrapper before the class is known to the link, then records the class with SetJavaClass. That set only the instance info, so getWrapperClassCounts(), which reads the weak-callback state, counted every JS-constructed object under , and a dead canary's record never got the class either. SetJavaClass now updates the state too. --- .../src/main/assets/app/tests/testWrapperLifetimeModes.js | 8 ++++++++ test-app/runtime/src/main/cpp/ObjectManager.cpp | 3 +++ 2 files changed, 11 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 07331df7e..d20b0300c 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeModes.js @@ -757,6 +757,14 @@ describe("Wrapper lifetime modes", function () { } }); + it("counts an object constructed from JS under its own class", function () { + var Counted = com.tns.tests.DummyClass.extend({}); + var made = new Counted(); + var entry = runtime.getWrapperClassCounts()[made.getClass().getName()]; + expect(entry).toBeDefined(); + expect(entry.wrappers).toBe(1); + }); + it("counts canary activity", function () { var before = stats(); var runnable = new java.lang.Runnable({ run: function () {} }); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index 9b3086c47..d8e7b7b99 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -362,6 +362,9 @@ jclass ObjectManager::GetJavaClass(const Local& instance) { void ObjectManager::SetJavaClass(const Local& instance, jclass clazz) { JSInstanceInfo* jsInfo = GetJSInstanceInfo(instance); jsInfo->objectClazz = clazz; + if (ObjectWeakCallbackState* state = m_idToObject.Find(jsInfo->javaObjectID)) { + state->objectClazz = clazz; + } } int ObjectManager::GetOrCreateObjectId(jobject object) { From 65d9d16e7e336fb848a1416c657fcc5fc6179913 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 19:34:43 -0300 Subject: [PATCH 31/31] test(runtime): assert the second rebuild in the multi-rebuild state specs --- .../app/tests/testWrapperLifetimeStateWrites.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js index bdb89f197..cb1e15182 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeStateWrites.js @@ -220,7 +220,11 @@ describe("Wrapper lifetime state writes", function () { })(); object = null; collect(); + var before = rebuilds(); object = Holder.held; + if (canary) { + expect(rebuilds()).toBeGreaterThan(before); + } expect(Object.keys(object)).toEqual(["a", "c", "b"]); expect([object.a, object.b, object.c]).toEqual([3, 2, 1]); }); @@ -288,7 +292,12 @@ describe("Wrapper lifetime state writes", function () { object.plain = 5; object = null; collect(); - expect(Holder.held.plain).toBe(5); + var before = rebuilds(); + object = Holder.held; + if (canary) { + expect(rebuilds()).toBeGreaterThan(before); + } + expect(object.plain).toBe(5); }); it("keeps fields a TypeScript-style subclass defines in its constructor", function () {