diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index b0f381b55..f787f5d19 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -195,11 +195,13 @@ every build on cold paths only: | `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 | +| `weakCollectionNativeCalls` | `"canary"` only: calls the weak collections make into the runtime: to make the key of a canary's Java object, to find the canary for a key, and to learn about canaries built for keyed objects since the last such call. A lookup of a value that was never a key makes none of its own, but the first lookup that misses after the runtime built such canaries, whatever value it looks up, makes that last call | In `"canary"` mode only array buffers backed by Java buffers resurrect; `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. +had a record (JS state, a weak-collection key, 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 @@ -237,7 +239,9 @@ their JS properties: 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. + JS object of your own, such as a `WeakMap` keyed by the native object (in + canary mode its entries live exactly as long as the Java object, see below), + or use `"all"`, which gives every wrapper state. Array buffers backed by Java buffers keep the `"resurrecting"` lifetime under either scope. @@ -265,9 +269,39 @@ 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. -`__releaseNativeCounterpart` drops the object's state with its link. +because nothing kept the old one. `__releaseNativeCounterpart` drops the +object's state with its link, and the released canary is a plain JS object +from then on: what the weak collections keyed on its Java object stays keyed +on it, and lives as long as it does. + +**Weak collections.** What could notice a new canary is whatever keys on the +old one without keeping it, so in canary mode a builtin +(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and +`FinalizationRegistry` with subclasses that key a Java object whose wrapper is +a canary by an opaque, frozen key the object's record holds. Entries and +targets therefore live exactly as long as the Java object; `WeakRef.prototype.deref` +(and the `get` alias) returns the live canary, a new one with the object's +state, or `undefined` once Java collected the object. `set`, `add`, +`getOrInsert`, `new WeakRef` and `register` create the key; lookups never do. +Neither gives the object a state. A Proxy around a Java object stays a +key of its own, and every other value passes through to the standard +collection. The cost is the other side of the same rooting: a `WeakMap` value +that references its Java key keeps the key, its record and so the Java object +alive for as long as the map lives. And `deref` builds a canary, which holds +the Java object strongly until it dies again, so a `WeakRef` to a Java object +that is dereferenced on every frame or event may keep the object from ever +being collected. In canary mode, an operation that can create the key costs a +native call for a Java object the collection does not hold yet; a plain JS +object costs only a V8 fast call that rules it out. Lookups (`get`, `has`, +`delete`, `unregister`, `deref`) make no native call, except a `deref` that +has to build a canary, and the first lookup that misses after the runtime +built canaries for keyed objects, which makes one call for all of them. An +operation that can create the +key also checks its receiver first so that a call that fails leaves no key +behind; that check names `has` (or +`unregister`) in its `TypeError`. The collections are subclasses of the +standard ones, which shows: `Object.getPrototypeOf(WeakMap.prototype)` is the +standard prototype, and `WeakMap.toString()` is not native code. 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 5c5c185b5..a8b1d2014 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -65,6 +65,7 @@ require("./tests/testWrapperLifetimeModes"); require("./tests/testWrapperLifetimeStateWrites"); require("./tests/testWrapperLifetimeFieldWrites"); require("./tests/testWrapperLifetimeRecordSharing"); +require("./tests/testWrapperLifetimeWeakCollections"); require("./tests/testsMemoryManagement"); require("./tests/testFieldGetSet"); require("./tests/extendedClassesTests"); 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 99fdb589e..f275310d0 100644 --- a/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetime.js @@ -38,7 +38,8 @@ describe("Wrapper lifetime", function () { var stats = runtime.getWrapperLifetimeStats(); expect(Object.keys(stats).sort()).toEqual( ["canaryCachedFieldWrites", "canaryCachedWrites", "canaryInterceptedWrites", "canaryNativeDeaths", - "canaryRebuilds", "canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]); + "canaryRebuilds", "canaryStates", "collected", "releasedAccesses", "releasedExplicitly", "resurrections", + "weakCollectionNativeCalls", "weakened"]); Object.keys(stats).forEach(function (key) { expect(typeof stats[key]).toBe("number"); }); diff --git a/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js new file mode 100644 index 000000000..d9f93d17c --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWrapperLifetimeWeakCollections.js @@ -0,0 +1,744 @@ +// Holds in every wrapper lifetime mode: in "canary" the collections key a Java object by +// its lifetime key, elsewhere the wrapper itself outlives the JS references. +describe("Weak collections of Java objects", 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 collectJava() { + for (var i = 0; i < 3; i++) { + java.lang.Runtime.getRuntime().gc(); + java.lang.System.runFinalization(); + } + } + + function crossIntoJava() { + java.lang.System.nanoTime(); + } + + // Lets JS drop every wrapper nothing references. + function collectBoth() { + gc(); + crossIntoJava(); + collectJava(); + gc(); + crossIntoJava(); + } + + 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); + })(); + } + + // A JS-extended object, a canary in every canary scope; Java keeps it in Holder. + function heldRunnable() { + var runnable = new java.lang.Runnable({ run: function () {} }); + Holder.held = runnable; + return runnable; + } + + afterEach(function () { + Holder.held = null; + }); + + it("keeps a WeakMap entry for a Java object across a wrapper change (" + mode + ")", function () { + var map = new WeakMap(); + (function () { + map.set(heldRunnable(), "value"); + })(); + collectBoth(); + + var again = Holder.held; + expect(map.has(again)).toBe(true); + expect(map.get(again)).toBe("value"); + expect(map.delete(again)).toBe(true); + expect(map.has(again)).toBe(false); + }); + + // A canary rebuilt more than once is a copy of an earlier rebuilt one: the key lives + // with the object's state, not on any canary, until the link is released. + it("keys canaries rebuilt from a copy of an earlier one by their Java object, through a release", function () { + var map = new WeakMap(); + var set = new WeakSet(); + (function () { + heldRunnable(); + })(); + collectBoth(); + (function () { + map.set(Holder.held, "first"); + })(); + collectBoth(); + (function () { + var second = Holder.held; + expect(map.get(second)).toBe("first"); + expect(map.delete(second)).toBe(true); + set.add(second); + })(); + collectBoth(); + + var third = Holder.held; + expect(map.has(third)).toBe(false); + expect(set.has(third)).toBe(true); + map.set(third, "third"); + __releaseNativeCounterpart(third); + expect(map.get(third)).toBe("third"); + expect(set.has(third)).toBe(true); + var after = Holder.held; + expect(after === third).toBe(false); + expect(map.has(after)).toBe(false); + expect(set.has(after)).toBe(false); + }); + + it("keeps a WeakSet member for a Java object across a wrapper change", function () { + var set = new WeakSet(); + (function () { + set.add(heldRunnable()); + })(); + collectBoth(); + + expect(set.has(Holder.held)).toBe(true); + }); + + it("keeps a getOrInsert entry for a Java object across a wrapper change", function () { + var map = new WeakMap(); + if (typeof map.getOrInsert !== "function") { + return; + } + (function () { + map.getOrInsert(heldRunnable(), "first"); + })(); + collectBoth(); + + expect(map.getOrInsert(Holder.held, "second")).toBe("first"); + var seen; + expect(map.getOrInsertComputed(Holder.held, function (key) { + seen = key; + return "computed"; + })).toBe("first"); + expect(seen).toBeUndefined(); + }); + + // A WeakRef keeps its target alive until the job that made it ends, so the wrapper can + // only change on a later task. + it("dereferences a WeakRef to a Java-held object while the object lives", function (done) { + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + var ref = (function () { + var runnable = heldRunnable(); + runnable.tag = "state"; + return new WeakRef(runnable); + })(); + setTimeout(function () { + collectBoth(); + if (canary) { + // Rebuilt by deref below, not by anything this spec kept. + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBe(rebuilds); + } + var target = ref.deref(); + expect(target).toBeDefined(); + expect(target.tag).toBe("state"); + expect(ref.get()).toBe(target); + expect(target.equals(Holder.held)).toBe(true); + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBe(rebuilds + 1); + } + done(); + }, 0); + }); + + // In canary mode a plain wrapper is a canary: its key hangs off its record, and deref + // makes a new wrapper the usual way, with the old one's JS properties under scope "all" + // only. + it("keeps a WeakMap entry and a WeakRef target for a Java-held plain object across a wrapper change", function (done) { + var map = new WeakMap(); + var ref = (function () { + var builder = new java.lang.StringBuilder("plain"); + builder.tag = "state"; + map.set(builder, "value"); + Holder.held = builder; + return new WeakRef(builder); + })(); + setTimeout(function () { + collectBoth(); + var again = Holder.held; + expect(map.get(again)).toBe("value"); + var target = ref.deref(); + expect(target).toBeDefined(); + expect(target.toString()).toBe("plain"); + if (canary && scope === "extended") { + expect(target.tag).toBeUndefined(); + } else { + expect(target.tag).toBe("state"); + } + done(); + }, 0); + }); + + // A keyed plain wrapper under scope "extended" is a canary with a record and no state: + // the next one is a new, empty object that stands for the same key. + it("finds a keyed Java-held plain object through its next canary, which has no state, under scope extended", function (done) { + if (!canary || scope !== "extended") { + done(); + return; + } + var NativeWeakRef = Object.getPrototypeOf(WeakRef); + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var target = {}; + var states = runtime.getWrapperLifetimeStats().canaryStates; + var first; + var refs = (function () { + var builder = new java.lang.StringBuilder("plain"); + builder.tag = "lost"; + map.set(builder, "value"); + set.add(builder); + registry.register(target, "held", builder); + Holder.held = builder; + first = new NativeWeakRef(builder); + return [new WeakRef(builder), new WeakRef(builder)]; + })(); + setTimeout(function () { + collectBoth(); + expect(first.deref()).toBeUndefined(); + // No canary is alive: deref builds one. + var built = refs[0].deref(); + expect(built).toBeDefined(); + expect(built.toString()).toBe("plain"); + expect(built.tag).toBeUndefined(); + expect(Holder.held === built).toBe(true); + built = null; + collectBoth(); + var again = Holder.held; + expect(again.tag).toBeUndefined(); + expect(map.get(again)).toBe("value"); + expect(map.has(again)).toBe(true); + expect(set.has(again)).toBe(true); + expect(refs[1].deref() === again).toBe(true); + expect(registry.unregister(again)).toBe(true); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + done(); + }, 0); + }); + + it("runs a FinalizationRegistry callback for a plain object only once Java collected it", function (done) { + if (!canary) { + done(); + return; + } + var heldCleaned = false; + var droppedCleaned = false; + var registry = new FinalizationRegistry(function (held) { + if (held === "held") { + heldCleaned = true; + } else if (held === "dropped") { + droppedCleaned = true; + } + }); + (function () { + var held = new java.lang.StringBuilder("held"); + Holder.held = held; + registry.register(held, "held"); + registry.register(new java.lang.StringBuilder("dropped"), "dropped"); + })(); + function finish() { + expect(heldCleaned).toBe(false); + expect(Holder.held.toString()).toBe("held"); + done(); + } + finish.fail = done.fail; + eventually(function () { + // A collected registry runs no callbacks. + return droppedCleaned && registry !== null; + }, finish, "the cleanup callback did not run"); + }, 20000); + + it("keeps what was keyed on a plain Java object after its link is released", function () { + if (!canary) { + return; + } + var map = new WeakMap(); + var set = new WeakSet(); + var builder = new java.lang.StringBuilder("released"); + map.set(builder, "value"); + set.add(builder); + __releaseNativeCounterpart(builder); + collectBoth(); + expect(map.get(builder)).toBe("value"); + expect(set.has(builder)).toBe(true); + expect(new WeakRef(builder).deref() === builder).toBe(true); + }); + + it("clears a WeakRef once Java collected the object", function (done) { + var ref = (function () { + return new WeakRef(new java.lang.Runnable({ run: function () {} })); + })(); + eventually(function () { + return ref.deref() === undefined; + }, done, "the WeakRef still dereferences"); + }, 20000); + + it("runs a FinalizationRegistry callback once Java collected the object", function (done) { + var cleaned = false; + var registry = new FinalizationRegistry(function (held) { + cleaned = held === "held"; + }); + (function () { + registry.register(new java.lang.Runnable({ run: function () {} }), "held"); + })(); + eventually(function () { + // A collected registry runs no callbacks. + return cleaned && registry !== null; + }, done, "the cleanup callback did not run"); + }, 20000); + + it("unregisters a FinalizationRegistry target through a later wrapper of its token", function () { + var registry = new FinalizationRegistry(function () {}); + var target = {}; + (function () { + var runnable = heldRunnable(); + registry.register(target, "held", runnable); + })(); + collectBoth(); + + expect(registry.unregister(Holder.held)).toBe(true); + expect(target).toBeDefined(); + }); + + it("rejects a FinalizationRegistry registration whose target is its held value", function () { + var registry = new FinalizationRegistry(function () {}); + var runnable = new java.lang.Runnable({ run: function () {} }); + expect(function () { + registry.register(runnable, runnable); + }).toThrowError(TypeError); + }); + + it("keys a Proxy around a Java object by the Proxy", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + var proxy = new Proxy(runnable, {}); + var map = new WeakMap(); + map.set(proxy, "proxy"); + expect(map.get(proxy)).toBe("proxy"); + expect(map.has(runnable)).toBe(false); + }); + + it("does not give state to a Java object a lookup only probes", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var runnable = new java.lang.Runnable({ run: function () {} }); + var states = runtime.getWrapperLifetimeStats().canaryStates; + expect(map.get(runnable)).toBeUndefined(); + expect(map.has(runnable)).toBe(false); + expect(set.has(runnable)).toBe(false); + expect(map.delete(runnable)).toBe(false); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + }); + + it("keeps working as the standard collections for other keys", function () { + var map = new WeakMap([[Object, 1]]); + var key = {}; + map.set(key, 2); + expect(map.get(Object)).toBe(1); + expect(map.get(key)).toBe(2); + var ref = new WeakRef(key); + expect(ref.deref()).toBe(key); + expect(new WeakSet([key]).has(key)).toBe(true); + expect(map instanceof WeakMap).toBe(true); + }); + + it("keys the entries given to the WeakMap and WeakSet constructors by the Java object", function () { + var map; + var set; + (function () { + var runnable = heldRunnable(); + map = new WeakMap([[runnable, "constructed"]]); + set = new WeakSet([runnable]); + })(); + collectBoth(); + + expect(map.get(Holder.held)).toBe("constructed"); + expect(set.has(Holder.held)).toBe(true); + }); + + it("keys a Java object in a subclass of WeakMap", function () { + class TaggedMap extends WeakMap { + set(key, value) { + return super.set(key, "tagged:" + value); + } + } + var map = new TaggedMap(); + (function () { + map.set(heldRunnable(), "value"); + })(); + collectBoth(); + + expect(map.get(Holder.held)).toBe("tagged:value"); + expect(map instanceof WeakMap).toBe(true); + }); + + it("does not run a FinalizationRegistry callback while Java holds the object", function (done) { + var cleaned = false; + var registry = new FinalizationRegistry(function () { + cleaned = true; + }); + (function () { + registry.register(heldRunnable(), "held"); + })(); + var polls = 0; + (function poll() { + collectBoth(); + if (cleaned) { + done.fail("the cleanup callback ran while Java held the object"); + return; + } + if (++polls < 5) { + setTimeout(poll, 50); + return; + } + expect(Holder.held).not.toBe(null); + // A collected registry runs no callbacks, so this spec would pass without one. + expect(registry instanceof FinalizationRegistry).toBe(true); + done(); + })(); + }, 20000); + + // Released, the wrapper is a plain JS object: what was keyed on it lives exactly as long + // as it does. Only booleans reach expect(), which could otherwise keep the wrapper. + it("keeps what was keyed on a Java object after its link is released, while the wrapper lives", function (done) { + var map = new WeakMap(); + var set = new WeakSet(); + var cleaned = false; + var registry = new FinalizationRegistry(function (held) { + cleaned = held === "released"; + }); + var runnable = new java.lang.Runnable({ run: function () {} }); + map.set(runnable, "value"); + set.add(runnable); + var ref = new WeakRef(runnable); + registry.register(runnable, "released"); + __releaseNativeCounterpart(runnable); + + expect(map.get(runnable)).toBe("value"); + expect(set.has(runnable)).toBe(true); + expect(ref.deref() === runnable).toBe(true); + setTimeout(function () { + collectBoth(); + expect(map.get(runnable)).toBe("value"); + expect(set.has(runnable)).toBe(true); + expect(ref.deref() === runnable).toBe(true); + expect(new WeakRef(runnable).deref() === runnable).toBe(true); + map.set(runnable, "again"); + expect(map.get(runnable)).toBe("again"); + expect(cleaned).toBe(false); + runnable = null; + setTimeout(function () { + eventually(function () { + // A collected registry runs no callbacks. + return cleaned && registry !== null; + }, done, "the cleanup callback did not run once the wrapper was collected"); + }, 0); + }, 0); + }, 20000); + + it("gives no state to a Java object it only keys", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var builder = new java.lang.StringBuilder("keyed"); + var states = runtime.getWrapperLifetimeStats().canaryStates; + map.set(builder, 1); + set.add(builder); + expect(map.get(builder)).toBe(1); + expect(set.has(builder)).toBe(true); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + }); + + it("makes no key for a call the standard collection rejects", function () { + var runnable = new java.lang.Runnable({ run: function () {} }); + var registry = new FinalizationRegistry(function () {}); + var map = new WeakMap(); + var states = runtime.getWrapperLifetimeStats().canaryStates; + expect(function () { + WeakMap.prototype.set.call({}, runnable, 1); + }).toThrowError(TypeError); + expect(function () { + WeakSet.prototype.add.call({}, runnable); + }).toThrowError(TypeError); + expect(function () { + registry.register(runnable, "held", 1); + }).toThrowError(TypeError); + expect(function () { + FinalizationRegistry.prototype.register.call({}, runnable, "held"); + }).toThrowError(TypeError); + if (typeof map.getOrInsertComputed === "function") { + expect(function () { + WeakMap.prototype.getOrInsert.call({}, runnable, 1); + }).toThrowError(TypeError); + expect(function () { + map.getOrInsertComputed(runnable, function () { + throw new Error("callback"); + }); + }).toThrowError("callback"); + } + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + }); + + it("hands getOrInsertComputed's callback the key it was given", function () { + var map = new WeakMap(); + if (typeof map.getOrInsertComputed !== "function") { + return; + } + var runnable = new java.lang.Runnable({ run: function () {} }); + var seen; + expect(map.getOrInsertComputed(runnable, function (key) { + seen = key; + return "computed"; + })).toBe("computed"); + expect(seen === runnable).toBe(true); + expect(map.get(runnable)).toBe("computed"); + }); + + it("matches the standard FinalizationRegistry.prototype.register signature and errors", function () { + var registry = new FinalizationRegistry(function () {}); + expect(FinalizationRegistry.prototype.register.length).toBe(2); + expect(function () { + registry.register(1, 1); + }).toThrowError(TypeError, /invalid target/); + }); + + // A canary built for an object that has a key, by any path (here a Java field read, not + // a deref), stands for the key at once; a canary that was never a key makes no state. + it("finds what was keyed on a Java object through a canary built by a Java read", function (done) { + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var token = new java.lang.StringBuilder("token"); + var NativeWeakRef = Object.getPrototypeOf(WeakRef) === Function.prototype ? WeakRef : Object.getPrototypeOf(WeakRef); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + var firstCanaries; + var refs = (function () { + var plain = new java.lang.StringBuilder("plain"); + map.set(plain, "plain value"); + set.add(plain); + var runnable = new java.lang.Runnable({ run: function () {} }); + registry.register(runnable, "held", plain); + map.set(runnable, "extended value"); + var list = new java.util.ArrayList(); + list.add(plain); + list.add(runnable); + Holder.held = list; + firstCanaries = [new NativeWeakRef(plain), new NativeWeakRef(runnable)]; + return [new WeakRef(plain), new WeakRef(runnable)]; + })(); + setTimeout(function () { + collectBoth(); + if (canary) { + expect(firstCanaries[0].deref()).toBeUndefined(); + expect(firstCanaries[1].deref()).toBeUndefined(); + } + var list = Holder.held; + var held = [list.get(0), list.get(1)]; + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + expect(map.get(held[0])).toBe("plain value"); + expect(set.has(held[0])).toBe(true); + expect(map.get(held[1])).toBe("extended value"); + expect(refs[0].deref() === held[0]).toBe(true); + expect(refs[1].deref() === held[1]).toBe(true); + expect(refs[1].deref() === refs[1].deref()).toBe(true); + expect(registry.unregister(held[0])).toBe(true); + expect(set.delete(held[0])).toBe(true); + expect(set.has(held[0])).toBe(false); + expect(map.delete(held[1])).toBe(true); + expect(map.has(held[1])).toBe(false); + var states = runtime.getWrapperLifetimeStats().canaryStates; + expect(map.has(token)).toBe(false); + expect(map.get(token)).toBeUndefined(); + expect(set.delete(token)).toBe(false); + expect(registry.unregister(token)).toBe(false); + expect(runtime.getWrapperLifetimeStats().canaryStates).toBe(states); + var plainTarget = {}; + expect(new WeakRef(plainTarget).deref()).toBe(plainTarget); + done(); + }, 0); + }); + + // Keying a canary must not keep it alive: only WeakRef construction and deref do, until + // the job ends, as the standard says. + it("lets a canary that was just keyed die in the same job", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + (function () { + var runnable = heldRunnable(); + map.set(runnable, "value"); + set.add(runnable); + })(); + collectBoth(); + expect(map.get(Holder.held)).toBe("value"); + expect(set.has(Holder.held)).toBe(true); + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds); + } + }); + + function nativeCalls() { + return runtime.getWrapperLifetimeStats().weakCollectionNativeCalls; + } + + it("never calls into the runtime for plain JS objects or lookups of values that were never keys", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var plain = {}; + var other = {}; + map.set(plain, 1); + set.add(plain); + registry.register(plain, "held", plain); + var ref = new WeakRef(plain); + var javaObject = new java.lang.Object(); + var runnable = new java.lang.Runnable({ run: function () {} }); + // A miss takes whatever canaries earlier specs left to be told about. + map.has({}); + var before = nativeCalls(); + expect(map.get(plain)).toBe(1); + expect(map.has(other)).toBe(false); + expect(map.get(other)).toBeUndefined(); + expect(map.delete(other)).toBe(false); + expect(set.has(plain)).toBe(true); + expect(set.has(other)).toBe(false); + expect(set.delete(other)).toBe(false); + expect(ref.deref()).toBe(plain); + expect(ref.get()).toBe(plain); + expect(registry.unregister(other)).toBe(false); + map.set(plain, 2); + set.add(plain); + expect(map.has(javaObject)).toBe(false); + expect(map.get(runnable)).toBeUndefined(); + expect(set.has(runnable)).toBe(false); + expect(registry.unregister(runnable)).toBe(false); + var fresh = {}; + map.set(fresh, 3); + set.add(fresh); + registry.register(fresh, "fresh", fresh); + expect(new WeakRef(fresh).deref()).toBe(fresh); + expect(map.getOrInsert ? map.getOrInsert({}, 4) : 4).toBe(4); + expect(nativeCalls()).toBe(before); + }); + + // The runtime only counts the canaries it builds for keyed objects; the first lookup + // that misses learns them all with one call. + it("finds a keyed Java object through canaries built while no lookup ran", function () { + var map = new WeakMap(); + var set = new WeakSet(); + var registry = new FinalizationRegistry(function () {}); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + (function () { + var runnable = heldRunnable(); + map.set(runnable, "value"); + set.add(runnable); + registry.register(runnable, "held", runnable); + })(); + collectBoth(); + (function () { + expect(set.has(Holder.held)).toBe(true); + })(); + collectBoth(); + // Built and dead again before any lookup saw it. + (function () { + Holder.held.hashCode(); + })(); + collectBoth(); + var again = Holder.held; + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds + 2); + } + var before = nativeCalls(); + expect(map.has({})).toBe(false); + if (canary) { + expect(nativeCalls()).toBe(before + 1); + } + expect(map.has({})).toBe(false); + expect(map.get(again)).toBe("value"); + expect(set.has(again)).toBe(true); + expect(registry.unregister(again)).toBe(true); + if (canary) { + expect(nativeCalls()).toBe(before + 1); + } + }); + + // Past 64 queued canaries the runtime prunes the queue as it builds more; the latest + // canary of an object built many times must survive the prunes the others' canaries make. + it("finds keyed Java objects through canaries built past the queue's prune while no lookup ran", function () { + var map = new WeakMap(); + var list = new java.util.ArrayList(); + Holder.held = list; + var count = 8; + (function () { + for (var i = 0; i < count; i++) { + var runnable = new java.lang.Runnable({ run: function () {} }); + list.add(runnable); + map.set(runnable, i); + } + })(); + gc(); + map.has({}); + var rebuilds = runtime.getWrapperLifetimeStats().canaryRebuilds; + for (var n = 0; n < 63; n++) { + (function () { + list.get(0).hashCode(); + })(); + gc(); + } + var first = list.get(0); + var others = []; + for (var i = 1; i < count; i++) { + others.push(list.get(i)); + } + if (canary) { + expect(runtime.getWrapperLifetimeStats().canaryRebuilds).toBeGreaterThan(rebuilds + 64); + } + var before = nativeCalls(); + expect(map.get(first)).toBe(0); + for (var j = 0; j < others.length; j++) { + expect(map.get(others[j])).toBe(j + 1); + } + if (canary) { + expect(nativeCalls()).toBe(before + 1); + } + }); + + it("finds a keyed Java object through a canary built and released while no lookup ran", function () { + var map = new WeakMap(); + var set = new WeakSet(); + (function () { + var runnable = heldRunnable(); + map.set(runnable, "value"); + set.add(runnable); + })(); + collectBoth(); + var released = Holder.held; + __releaseNativeCounterpart(released); + expect(set.has(released)).toBe(true); + expect(map.get(released)).toBe("value"); + expect(map.has({})).toBe(false); + }); + + it("installs the canary collections only in canary mode", function () { + var native = WeakMap.toString().indexOf("[native code]") !== -1; + expect(native).toBe(!canary); + }); +}); diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index e50fbb951..707ecec1c 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -100,6 +100,7 @@ set(RUNTIME_BUILTIN_JS ${RUNTIME_BUILTIN_JS_DIR}/require-factory.js ${RUNTIME_BUILTIN_JS_DIR}/structured-clone.js ${RUNTIME_BUILTIN_JS_DIR}/text-encoding.js + ${RUNTIME_BUILTIN_JS_DIR}/weak-collections.js ${RUNTIME_BUILTIN_JS_DIR}/weak-ref.js ${RUNTIME_BUILTIN_JS_DIR}/worker-events.js ) diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index 3c6e8bc72..829b6ed51 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -175,6 +175,7 @@ void GetWrapperLifetimeStatsCallback(const FunctionCallbackInfo& info) { set("collected", stats.collected); set("releasedExplicitly", stats.releasedExplicitly); set("releasedAccesses", stats.releasedAccesses); + set("weakCollectionNativeCalls", stats.weakCollectionNativeCalls); set("canaryStates", stats.canaryStates); set("canaryNativeDeaths", stats.canaryNativeDeaths); set("canaryInterceptedWrites", stats.canaryInterceptedWrites); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.cpp b/test-app/runtime/src/main/cpp/ObjectManager.cpp index d8e7b7b99..65ca90fc3 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.cpp +++ b/test-app/runtime/src/main/cpp/ObjectManager.cpp @@ -14,6 +14,7 @@ #include "V8GlobalHelpers.h" #include "V8StringConstants.h" #include "WrapperLifetimeCanary.h" +#include "include/v8-fast-api-calls.h" #include "include/v8.h" using namespace v8; @@ -117,6 +118,9 @@ void ObjectManager::Init(Isolate* isolate) { if (WrapperLifetimeCanary::Enabled()) { m_instanceFieldTableKey.Reset(isolate, Private::New(isolate)); + m_keyOfReleased.Reset(isolate, Private::New(isolate)); + m_objectOfKey.Reset(isolate, Private::New(isolate)); + m_releasedOfKey.Reset(isolate, Private::New(isolate)); isolate->AddGCEpilogueCallback(CanaryGCEpilogue, this); m_canaryEpilogueAdded = true; } @@ -618,6 +622,9 @@ void ObjectManager::Link(const Local& object, uint32_t javaObjectID, jcl state->record = AdoptCanary(object, javaObjectID, kind, instanceTemplate, record.has_value() ? *record : FindCanaryRecord(javaObjectID), hydrate); + if (state->record != nullptr && !state->record->key.IsEmpty()) { + MarkRekeyPending(state); + } } } @@ -980,14 +987,7 @@ bool ObjectManager::CanaryStateForWrite(const Local& holder, Local ObjectManager::AttachState(CanaryHandle* canary, const Local& fresh) { - CanaryRecord* record = canary->record; - if (record == nullptr) { - record = FindCanaryRecord(canary->javaObjectID); - } - if (record == nullptr) { - record = NewCanaryRecord(canary->javaObjectID); - } - canary->record = record; + CanaryRecord* record = RecordForWrite(canary); record->state.Reset(m_isolate, fresh); m_lifetimeStats.canaryStates++; return fresh; @@ -1019,6 +1019,18 @@ Local ObjectManager::NewEmptyState() { return m_emptyState.Get(m_isolate)->Clone(m_isolate); } +ObjectManager::CanaryRecord* ObjectManager::RecordForWrite(ObjectWeakCallbackState* canary) { + CanaryRecord* record = canary->record; + if (record == nullptr) { + record = FindCanaryRecord(canary->javaObjectID); + } + if (record == nullptr) { + record = NewCanaryRecord(canary->javaObjectID); + } + canary->record = record; + return record; +} + Local ObjectManager::StateOf(CanaryHandle* canary) { CanaryRecord* record = canary->record; return record != nullptr && !record->state.IsEmpty() ? record->state.Get(m_isolate) @@ -1060,6 +1072,7 @@ void ObjectManager::CanaryDiedStatic( } thisPtr->m_pendingCanaryDeaths.push_back(static_cast(id)); } + thisPtr->DropRekeyPending(state); delete state; } @@ -1206,6 +1219,328 @@ std::map ObjectManager::GetWrapperClass return counts; } +namespace { +// Only an object with a Metadata field can be a canary, released ones included; +// a Proxy is a key of its own. +bool MaybeCanary(Local value) { + return value->IsObject() && !value->IsProxy() && + ObjectManager::HasMetadataField(value.As()); +} + +void MaybeCanaryCallback(const FunctionCallbackInfo& info) { + info.GetReturnValue().Set(MaybeCanary(info[0])); +} + +#if NATIVESCRIPT_ENABLE_FAST_API +bool FastMaybeCanary(Local receiver, Local value) { + return MaybeCanary(value); +} + +const CFunction kFastMaybeCanary = CFunction::Make(FastMaybeCanary); +#endif +} // namespace + +bool ObjectManager::AddWeakCollectionFunctions(Local context, Local binding) { +#if NATIVESCRIPT_ENABLE_FAST_API + tns::SetFastMethodNoSideEffect(context, binding, "maybeCanary", MaybeCanaryCallback, + &kFastMaybeCanary); +#else + tns::SetMethodNoSideEffect(context, binding, "maybeCanary", MaybeCanaryCallback); +#endif + auto isolate = m_isolate; + Local unwrap; + Local wrap; + Local takeRekeys; + std::shared_ptr store = + ArrayBuffer::NewBackingStore(isolate, sizeof(int32_t)); + m_rekeyPendingCount = static_cast(store->Data()); + *m_rekeyPendingCount = 0; + Local pendingRekeys = Int32Array::New(ArrayBuffer::New(isolate, store), 0, 1); + m_rekeyPendingArray.Reset(isolate, pendingRekeys); + return Function::New(context, UnwrapForWeakCollection).ToLocal(&unwrap) && + Function::New(context, WrapForWeakCollection).ToLocal(&wrap) && + Function::New(context, TakeRekeysForWeakCollection).ToLocal(&takeRekeys) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "unwrap"), unwrap) + .FromMaybe(false) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "wrap"), wrap) + .FromMaybe(false) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "takeRekeys"), takeRekeys) + .FromMaybe(false) && + binding->Set(context, ArgConverter::ConvertToV8String(isolate, "pendingRekeys"), + pendingRekeys) + .FromMaybe(false); +} + +// unwrap(value, create): the weak collections' key for a canary's Java object, +// a frozen, null-prototype object that lives as long as the object's record, +// that is, until Java collects the object. Lookups pass `create` false and never +// make one: with no key yet, no entry can be keyed by it. The value itself for +// anything that is not a canary, a Proxy included (it is a key of its own). +namespace { +// Null rather than a throw while the isolate has no runtime. +ObjectManager* WeakCollectionManagerOf(Isolate* isolate) { + Runtime* runtime = Runtime::TryGetRuntime(isolate); + return runtime != nullptr ? runtime->GetObjectManager() : nullptr; +} + +void RethrowToV8(const char* what) { + NativeScriptException nsEx(std::string("Error: c++ exception: ") + what); + nsEx.ReThrowToV8(); +} +} // namespace + +void ObjectManager::UnwrapForWeakCollection(const FunctionCallbackInfo& info) { + try { + Isolate* isolate = info.GetIsolate(); + Local value = info[0]; + bool create = info[1]->IsTrue(); + info.GetReturnValue().Set(value); + // Canaries, released ones included, are runtime objects with a Metadata field. + if (!value->IsObject() || value->IsProxy() || !HasMetadataField(value.As())) { + return; + } + ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); + if (thisPtr == nullptr) { + return; + } + thisPtr->m_lifetimeStats.weakCollectionNativeCalls++; + Local holder = value.As(); + Local context = isolate->GetCurrentContext(); + ObjectWeakCallbackState* live = thisPtr->CanaryOf(holder); + CanaryRecord* record = live != nullptr ? thisPtr->FindCanaryRecord(live->javaObjectID) : nullptr; + if (record != nullptr && !record->key.IsEmpty()) { + info.GetReturnValue().Set(record->key.Get(isolate)); + return; + } + if (live == nullptr) { + // A canary whose link was released keeps its key itself. + Local key; + if (holder->GetPrivate(context, thisPtr->m_keyOfReleased.Get(isolate)).ToLocal(&key) && + key->IsObject()) { + info.GetReturnValue().Set(key); + } + return; + } + if (!create) { + return; + } + Local newKey = Object::New(isolate, Null(isolate), nullptr, nullptr, 0); + if (!newKey + ->SetPrivate(context, thisPtr->m_objectOfKey.Get(isolate), + Integer::NewFromUnsigned(isolate, live->javaObjectID)) + .FromMaybe(false) || + !newKey->SetIntegrityLevel(context, IntegrityLevel::kFrozen).FromMaybe(false)) { + return; + } + thisPtr->RecordForWrite(live)->key.Reset(isolate, newKey); + info.GetReturnValue().Set(newKey); + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + RethrowToV8(e.what()); + } catch (...) { + RethrowToV8("unknown"); + } +} + +// wrap(key): the Java object a key stands for, as its live canary or a new one +// (with its state, when it keeps one), or undefined once Java collected it. +// Anything that is not a key passes through. +void ObjectManager::WrapForWeakCollection(const FunctionCallbackInfo& info) { + try { + Isolate* isolate = info.GetIsolate(); + Local value = info[0]; + info.GetReturnValue().Set(value); + if (!value->IsObject()) { + return; + } + ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); + if (thisPtr == nullptr) { + return; + } + thisPtr->m_lifetimeStats.weakCollectionNativeCalls++; + Local context = isolate->GetCurrentContext(); + Local key = value.As(); + Local idValue; + if (!key->GetPrivate(context, thisPtr->m_objectOfKey.Get(isolate)).ToLocal(&idValue) || + !idValue->IsUint32()) { + return; + } + // The key of a released canary lives exactly as long as the canary. + Local released; + if (key->GetPrivate(context, thisPtr->m_releasedOfKey.Get(isolate)).ToLocal(&released) && + released->IsObject()) { + info.GetReturnValue().Set(released); + return; + } + info.GetReturnValue().SetUndefined(); + int id = static_cast(idValue.As()->Value()); + CanaryRecord* record = thisPtr->FindCanaryRecord(id); + if (record == nullptr || record->key.IsEmpty() || record->key.Get(isolate) != key) { + return; + } + if (auto live = thisPtr->m_idToObject.Find(id)) { + info.GetReturnValue().Set(thisPtr->JsObjectFor(live)); + return; + } + Local result = thisPtr->RebuildCanary(id); + if (result.IsEmpty() && thisPtr->FindCanaryRecord(id) != nullptr) { + // A plain object: a wrapper made from it the usual way links to its record, + // and gets its state back in scope. + JniLocalRef javaObject(thisPtr->JavaObjectOrNull(id)); + if (!javaObject.IsNull()) { + result = thisPtr->GetOrCreateJSWrapper(javaObject); + } + } + if (!result.IsEmpty()) { + info.GetReturnValue().Set(result); + } + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + RethrowToV8(e.what()); + } catch (...) { + RethrowToV8("unknown"); + } +} + +void ObjectManager::MarkRekeyPending(ObjectWeakCallbackState* state) { + if (m_rekeyPendingCount == nullptr || state->rekeyPending) { + return; + } + // Stale ids pile up only while JS makes no lookup that misses; prune them + // once they outnumber the live ones. An id is queued once per canary built + // for it, and every copy looks live while its latest canary is pending, so + // keep one copy of each; takeRekeys does not depend on their order. + if (m_rekeyPendingIds.size() >= 64 && + m_rekeyPendingIds.size() > 2 * static_cast(*m_rekeyPendingCount)) { + m_rekeyPendingIds.erase( + std::remove_if(m_rekeyPendingIds.begin(), m_rekeyPendingIds.end(), + [this](uint32_t id) { + auto live = m_idToObject.Find(id); + return live == nullptr || !live->rekeyPending; + }), + m_rekeyPendingIds.end()); + std::sort(m_rekeyPendingIds.begin(), m_rekeyPendingIds.end()); + m_rekeyPendingIds.erase(std::unique(m_rekeyPendingIds.begin(), m_rekeyPendingIds.end()), + m_rekeyPendingIds.end()); + } + state->rekeyPending = true; + m_rekeyPendingIds.push_back(state->javaObjectID); + ++*m_rekeyPendingCount; +} + +// takeRekeys(): [canary, key, canary, key, ...] for every live canary of a +// keyed object built since the last call. A canary whose link was released +// since holds its key itself. +void ObjectManager::TakeRekeysForWeakCollection(const FunctionCallbackInfo& info) { + try { + Isolate* isolate = info.GetIsolate(); + ObjectManager* thisPtr = WeakCollectionManagerOf(isolate); + if (thisPtr == nullptr) { + info.GetReturnValue().Set(Array::New(isolate, 0)); + return; + } + thisPtr->m_lifetimeStats.weakCollectionNativeCalls++; + std::vector& ids = thisPtr->m_rekeyTakenIds; + ids.swap(thisPtr->m_rekeyPendingIds); + if (thisPtr->m_rekeyPendingCount != nullptr) { + *thisPtr->m_rekeyPendingCount = 0; + } + // Handles only until every pair is taken: an allocation could start a + // collection, whose weak callbacks free registrations. + constexpr size_t kInlinePairs = 8; + Local inlinePairs[2 * kInlinePairs]; + LocalVector morePairs(isolate); + size_t count = 0; + bool released = false; + auto add = [&](Local canary, Local key) { + if (count < kInlinePairs) { + inlinePairs[2 * count] = canary; + inlinePairs[2 * count + 1] = key; + } else { + if (morePairs.empty()) { + morePairs.insert(morePairs.end(), inlinePairs, inlinePairs + 2 * kInlinePairs); + } + morePairs.push_back(canary); + morePairs.push_back(key); + } + count++; + }; + for (uint32_t id : ids) { + auto live = thisPtr->m_idToObject.Find(id); + if (live == nullptr || !live->rekeyPending) { + continue; + } + live->rekeyPending = false; + Local canary = Local::New(isolate, *live->target); + if (live->record != nullptr && !live->record->key.IsEmpty()) { + add(canary, live->record->key.Get(isolate)); + } else { + add(canary, Local()); + released = true; + } + } + ids.clear(); + Local* pairs = count <= kInlinePairs ? inlinePairs : morePairs.data(); + if (released) { + Local context = isolate->GetCurrentContext(); + Local keyOfReleased = thisPtr->m_keyOfReleased.Get(isolate); + size_t kept = 0; + for (size_t i = 0; i < count; i++) { + Local canary = pairs[2 * i]; + Local key = pairs[2 * i + 1]; + if (key.IsEmpty() && + (!canary.As()->GetPrivate(context, keyOfReleased).ToLocal(&key) || + !key->IsObject())) { + continue; + } + pairs[2 * kept] = canary; + pairs[2 * kept + 1] = key; + kept++; + } + count = kept; + } + info.GetReturnValue().Set(Array::New(isolate, pairs, 2 * count)); + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + RethrowToV8(e.what()); + } catch (...) { + RethrowToV8("unknown"); + } +} + +void ObjectManager::KeepWeakCollectionKey(int javaObjectID) { + CanaryRecord* record = FindCanaryRecord(javaObjectID); + auto live = m_idToObject.Find(javaObjectID); + if (record == nullptr || record->key.IsEmpty() || live == nullptr || !live->canary || + m_keyOfReleased.IsEmpty()) { + return; + } + Local context = m_isolate->GetCurrentContext(); + Local key = record->key.Get(m_isolate); + // Private symbols bypass the canary's write handler, and V8 lets them be + // added to the frozen key. + Local canary = Local::New(m_isolate, *live->target); + (void)canary->SetPrivate(context, m_keyOfReleased.Get(m_isolate), key); + (void)key->SetPrivate(context, m_releasedOfKey.Get(m_isolate), canary); +} + +jobject ObjectManager::JavaObjectOrNull(int javaObjectID) { + JEnv env; + JNIEnv* raw = env; + AssertIsolateLocked(); + // getJavaObjectByID throws for an id whose object was collected. + jobject object = raw->CallObjectMethod(m_javaRuntimeObject, GET_JAVAOBJECT_BY_ID_METHOD_ID, + javaObjectID); + if (raw->ExceptionCheck()) { + raw->ExceptionClear(); + return nullptr; + } + return object; +} + void ObjectManager::ReleaseCollectedCanaryStates() { if (!m_deathInboxOpen) { return; @@ -1526,7 +1861,14 @@ void ObjectManager::ReleaseAllRegistered() { m_canaryRecords.DrainAll([](CanaryRecord* record) { delete record; }); m_canaryRecordCount = 0; m_instanceFieldTableKey.Reset(); + m_keyOfReleased.Reset(); m_emptyState.Reset(); + m_rekeyPendingIds.clear(); + m_rekeyTakenIds.clear(); + m_rekeyPendingCount = nullptr; + m_rekeyPendingArray.Reset(); + m_objectOfKey.Reset(); + m_releasedOfKey.Reset(); auto jsInfoIdx = static_cast(MetadataNodeKeys::JsInfo); @@ -1649,6 +1991,9 @@ void ObjectManager::ReleaseNativeCounterpart(v8::Local& object) { javaObjectID); m_releaseCount++; m_lifetimeStats.releasedExplicitly++; + // What weak collections keyed on the object stays keyed on the released + // canary, now a plain JS object, for as long as it lives. + KeepWeakCollectionKey(javaObjectID); // Java no longer knows the id, so nothing could rebuild a canary from it. EraseCanaryRecord(javaObjectID); diff --git a/test-app/runtime/src/main/cpp/ObjectManager.h b/test-app/runtime/src/main/cpp/ObjectManager.h index e8da69dbe..57ff4f7c0 100644 --- a/test-app/runtime/src/main/cpp/ObjectManager.h +++ b/test-app/runtime/src/main/cpp/ObjectManager.h @@ -284,6 +284,16 @@ class ObjectManager { // Per Java class name (dotted), for ns:runtime's getWrapperClassCounts(). std::map GetWrapperClassCounts(); + // Canary mode: adds `maybeCanary` (a V8 fast call, false for any value but a + // runtime object), `unwrap` (a canary -> its Java object's weak-collection + // key), `wrap` (key -> live or new canary, or undefined once Java collected + // the object), `takeRekeys` (the canaries built for objects that have a key + // since the last call, with their keys) and `pendingRekeys` (an Int32Array + // whose element counts those still alive) to binding, for + // js/weak-collections.js. + bool AddWeakCollectionFunctions(v8::Local context, + v8::Local binding); + private: static void InitializeJNI(); @@ -327,6 +337,8 @@ class ObjectManager { bool keepsState = false; // A canary's record, cached; EraseCanaryRecord clears it. CanaryRecord* record = nullptr; + // A canary of a keyed object that takeRekeys has not returned yet. + bool rekeyPending = false; }; // Canary mode: what a canary built later for a JS-extended instance starts @@ -372,6 +384,8 @@ class ObjectManager { static constexpr uint8_t kStateTags = 6; uint8_t stateTagCount = 0; uint32_t stateTags[kStateTags]; + // The object's weak-collection key, made on first use. + v8::Global key; }; using JSInstanceInfo = ObjectWeakCallbackState; @@ -446,6 +460,8 @@ class ObjectManager { ObjectWeakCallbackState* CanaryOf(const v8::Local& holder); CanaryRecord* FindCanaryRecord(int javaObjectID); + // canary's record, made if it has none. + CanaryRecord* RecordForWrite(ObjectWeakCallbackState* canary); // A new canary for a JS-extended instance whose canary died; empty when id // has no extended record or Java collected the object meanwhile. @@ -547,6 +563,42 @@ class ObjectManager { // Cloned for each new state; never handed to JS. v8::Global m_emptyState; v8::Local NewEmptyState(); + // A weak-collection key names its object's id. Once the canary's link is + // released, the canary holds the key and the key leads back to the canary. + v8::Persistent m_keyOfReleased; + v8::Persistent m_objectOfKey; + v8::Persistent m_releasedOfKey; + + // Gives id's weak-collection key to its live canary, whose link is being + // released. + void KeepWeakCollectionKey(int javaObjectID); + + static void UnwrapForWeakCollection(const v8::FunctionCallbackInfo& info); + static void WrapForWeakCollection(const v8::FunctionCallbackInfo& info); + static void TakeRekeysForWeakCollection(const v8::FunctionCallbackInfo& info); + + // Canaries of keyed objects that JS has not been told about: ids whose + // registration has rekeyPending set, plus stale ids of ones that died. + std::vector m_rekeyPendingIds; + // takeRekeys swaps it with m_rekeyPendingIds, so neither reallocates. + std::vector m_rekeyTakenIds; + // The element of binding.pendingRekeys: the live ones among them. Written + // from the canary weak callback too, which may not call into V8. + int32_t* m_rekeyPendingCount = nullptr; + // Keeps the count's memory alive. + v8::Persistent m_rekeyPendingArray; + void MarkRekeyPending(ObjectWeakCallbackState* state); + void DropRekeyPending(ObjectWeakCallbackState* state) { + if (state->rekeyPending) { + state->rekeyPending = false; + if (m_rekeyPendingCount != nullptr && *m_rekeyPendingCount > 0) { + --*m_rekeyPendingCount; + } + } + } + + // id's Java object, or null once Java collected it. + jobject JavaObjectOrNull(int javaObjectID); void JSObjectFinalizer(v8::Isolate* isolate, ObjectWeakCallbackState* callbackState); diff --git a/test-app/runtime/src/main/cpp/WeakRef.cpp b/test-app/runtime/src/main/cpp/WeakRef.cpp index 68c85512f..c6be39871 100644 --- a/test-app/runtime/src/main/cpp/WeakRef.cpp +++ b/test-app/runtime/src/main/cpp/WeakRef.cpp @@ -1,4 +1,7 @@ #include "WeakRef.h" +#include "ObjectManager.h" +#include "Runtime.h" +#include "WrapperLifetimeCanary.h" #include "NativeScriptAssert.h" #include "ArgConverter.h" #include "BuiltinLoader.h" @@ -17,4 +20,13 @@ WeakRef::WeakRef() { void WeakRef::Init(v8::Isolate* isolate, Local context) { bool success = !BuiltinLoader::RunBuiltin(context, BuiltinId::kWeakRef).IsEmpty(); NS_DCHECK(success); + + if (!WrapperLifetimeCanary::Enabled()) { + return; + } + // Canary mode: the weak collections key Java objects, not their canaries. + auto binding = Object::New(isolate); + success = Runtime::GetObjectManager(isolate)->AddWeakCollectionFunctions(context, binding) && + !BuiltinLoader::RunBuiltin(context, BuiltinId::kWeakCollections, binding).IsEmpty(); + NS_CHECK(success); } diff --git a/test-app/runtime/src/main/cpp/WrapperLifetime.h b/test-app/runtime/src/main/cpp/WrapperLifetime.h index 6c1995d18..6d96c6fa6 100644 --- a/test-app/runtime/src/main/cpp/WrapperLifetime.h +++ b/test-app/runtime/src/main/cpp/WrapperLifetime.h @@ -77,6 +77,8 @@ struct WrapperLifetimeStats { // "canary" only: canaries built anew for a JS-extended instance whose // previous canary died while Java kept the object. uint64_t canaryRebuilds = 0; + // "canary" only: calls from js/weak-collections.js into the runtime. + uint64_t weakCollectionNativeCalls = 0; }; } // namespace tns diff --git a/test-app/runtime/src/main/cpp/js/primordials.js b/test-app/runtime/src/main/cpp/js/primordials.js index b8bb6f2dd..1521754c7 100644 --- a/test-app/runtime/src/main/cpp/js/primordials.js +++ b/test-app/runtime/src/main/cpp/js/primordials.js @@ -37,12 +37,14 @@ const intrinsics = { Uint32Array, URIError, URL, + WeakMap, WeakRef, WeakSet, // Well-known symbols. SymbolFor: Symbol.for, SymbolIterator: Symbol.iterator, + SymbolKeyFor: Symbol.keyFor, SymbolToStringTag: Symbol.toStringTag, // Namespaces / prototypes. @@ -108,6 +110,15 @@ const intrinsics = { StringPrototypeSlice: uncurryThis(String.prototype.slice), StringPrototypeStartsWith: uncurryThis(String.prototype.startsWith), SymbolPrototypeToString: uncurryThis(Symbol.prototype.toString), + WeakMapPrototypeDelete: uncurryThis(WeakMap.prototype.delete), + WeakMapPrototypeGet: uncurryThis(WeakMap.prototype.get), + // The upsert proposal: undefined where V8 does not ship it. + WeakMapPrototypeGetOrInsert: typeof WeakMap.prototype.getOrInsert === "function" + ? uncurryThis(WeakMap.prototype.getOrInsert) : undefined, + WeakMapPrototypeGetOrInsertComputed: typeof WeakMap.prototype.getOrInsertComputed === "function" + ? uncurryThis(WeakMap.prototype.getOrInsertComputed) : undefined, + WeakMapPrototypeHas: uncurryThis(WeakMap.prototype.has), + WeakMapPrototypeSet: uncurryThis(WeakMap.prototype.set), WeakRefPrototypeDeref: uncurryThis(WeakRef.prototype.deref), WeakSetPrototypeAdd: uncurryThis(WeakSet.prototype.add), WeakSetPrototypeDelete: uncurryThis(WeakSet.prototype.delete), diff --git a/test-app/runtime/src/main/cpp/js/weak-collections.js b/test-app/runtime/src/main/cpp/js/weak-collections.js new file mode 100644 index 000000000..a11204bab --- /dev/null +++ b/test-app/runtime/src/main/cpp/js/weak-collections.js @@ -0,0 +1,301 @@ +"use strict"; + +// Canary wrapper lifetime mode only (run by WeakRef.cpp): WeakMap, WeakSet, +// WeakRef and FinalizationRegistry key a Java object by its lifetime key +// instead of its wrapper. The wrapper is a canary that dies with its JS +// references while the Java object lives on, and a later wrapper for the same +// object is a new JS object; keyed by the wrapper, entries and targets would be +// lost with it. Every other value passes through unchanged. +// +// They are subclasses of the native collections, so what subclassing shows is +// left as it is: Object.getPrototypeOf(WeakMap.prototype) is the native +// prototype, and WeakMap.toString() is not native code. + +const { maybeCanary, unwrap, wrap, takeRekeys, pendingRekeys } = binding; +const { + FinalizationRegistry: NativeFinalizationRegistry, + FinalizationRegistryPrototypeRegister, + FinalizationRegistryPrototypeUnregister, + ObjectDefineProperty, + ObjectFreeze, + SymbolKeyFor, + WeakMap: NativeWeakMap, + WeakMapPrototypeDelete, + WeakMapPrototypeGet, + WeakMapPrototypeGetOrInsert, + WeakMapPrototypeGetOrInsertComputed, + WeakMapPrototypeHas, + WeakMapPrototypeSet, + WeakRef: NativeWeakRef, + WeakRefPrototypeDeref, + WeakSet: NativeWeakSet, + WeakSetPrototypeAdd, + WeakSetPrototypeDelete, + WeakSetPrototypeHas, +} = primordials; + +// Only an object can be a canary; anything else goes to the native method as is. +function isObject(value) { + return (typeof value === "object" && value !== null) || typeof value === "function"; +} + +// The values the native collections accept as keys and targets. +function canBeHeldWeakly(value) { + return isObject(value) || (typeof value === "symbol" && SymbolKeyFor(value) === undefined); +} + +// unwrap(value, true) makes the key on first use. A key is made only once the +// native method can no longer reject the call, so a failed call leaves no key +// behind: the receiver is checked first with a method that cannot insert +// anything. +// +// A canary is never stored as a key itself (its lifetime key is), so every +// method first tries the value as is. canaryToKey holds every canary that +// stands for a key and that this file has seen: the ones keyFor unwrapped, and +// the ones takeRekeys returned. pendingRekeys[0] counts the live canaries the +// runtime built for keyed objects since takeRekeys last ran; while it is 0, a +// value missing from canaryToKey was never a key, and no native code runs. +const canaryToKey = new NativeWeakMap(); + +function takePendingRekeys() { + const pairs = takeRekeys(); + for (let i = 0; i < pairs.length; i += 2) { + WeakMapPrototypeSet(canaryToKey, pairs[i], pairs[i + 1]); + } +} + +// The lifetime key value stands for, or undefined when that is value itself. +function otherKey(value) { + if (!isObject(value)) { + return undefined; + } + const key = WeakMapPrototypeGet(canaryToKey, value); + if (key !== undefined || pendingRekeys[0] === 0) { + return key; + } + takePendingRekeys(); + return WeakMapPrototypeGet(canaryToKey, value); +} + +// The key to store for value, an object, made on first use. +function keyFor(value) { + // A V8 fast call: a plain JS object reaches neither canaryToKey nor unwrap. + if (!maybeCanary(value)) { + return value; + } + const known = otherKey(value); + if (known !== undefined) { + return known; + } + const key = unwrap(value, true); + if (key !== value) { + WeakMapPrototypeSet(canaryToKey, value, key); + } + return key; +} + +// Unregistering it finds nothing: it is never a token. +const receiverProbe = ObjectFreeze({ __proto__: null }); + +class WeakMap extends NativeWeakMap { + get(key) { + const direct = WeakMapPrototypeGet(this, key); + if (direct !== undefined) { + return direct; + } + const other = otherKey(key); + return other === undefined ? undefined : WeakMapPrototypeGet(this, other); + } + + set(key, value) { + // Also checks the receiver before a key is made. + if (isObject(key) && !WeakMapPrototypeHas(this, key)) { + key = keyFor(key); + } + WeakMapPrototypeSet(this, key, value); + return this; + } + + has(key) { + if (WeakMapPrototypeHas(this, key)) { + return true; + } + const other = otherKey(key); + return other !== undefined && WeakMapPrototypeHas(this, other); + } + + delete(key) { + if (WeakMapPrototypeDelete(this, key)) { + return true; + } + const other = otherKey(key); + return other !== undefined && WeakMapPrototypeDelete(this, other); + } +} + +// V8 ships the upsert proposal; inherited, these would key on the wrapper. +if (WeakMapPrototypeGetOrInsert !== undefined) { + ObjectDefineProperty(WeakMap.prototype, "getOrInsert", { + value: function getOrInsert(key, value) { + if (isObject(key) && !WeakMapPrototypeHas(this, key)) { + key = keyFor(key); + } + return WeakMapPrototypeGetOrInsert(this, key, value); + }, + writable: true, + configurable: true, + }); +} +if (WeakMapPrototypeGetOrInsertComputed !== undefined) { + ObjectDefineProperty(WeakMap.prototype, "getOrInsertComputed", { + value: function getOrInsertComputed(key, callbackfn) { + if (!isObject(key) || typeof callbackfn !== "function") { + return WeakMapPrototypeGetOrInsertComputed(this, key, callbackfn); + } + if (WeakMapPrototypeHas(this, key)) { + return WeakMapPrototypeGet(this, key); + } + const existing = otherKey(key); + if (existing !== undefined && WeakMapPrototypeHas(this, existing)) { + return WeakMapPrototypeGet(this, existing); + } + // Before the key exists, so a callback that throws leaves none; it sees + // the key it was given, not the lifetime key. + const value = callbackfn(key); + WeakMapPrototypeSet(this, keyFor(key), value); + return value; + }, + writable: true, + configurable: true, + }); +} + +class WeakSet extends NativeWeakSet { + add(value) { + // Also checks the receiver before a key is made. + if (isObject(value) && !WeakSetPrototypeHas(this, value)) { + value = keyFor(value); + } + WeakSetPrototypeAdd(this, value); + return this; + } + + has(value) { + if (WeakSetPrototypeHas(this, value)) { + return true; + } + const other = otherKey(value); + return other !== undefined && WeakSetPrototypeHas(this, other); + } + + delete(value) { + if (WeakSetPrototypeDelete(this, value)) { + return true; + } + const other = otherKey(value); + return other !== undefined && WeakSetPrototypeDelete(this, other); + } +} + +class WeakRef extends NativeWeakRef { + // A NativeWeakRef to the canary this was made with or last dereferenced to, + // or undefined when the target is not a key. A live canary is always what + // wrap returns for its key: Java cannot collect the object while it lives, + // and a released canary stays its key's object. Only the constructor and + // deref make one: a NativeWeakRef keeps its target until the job ends, which + // they do by spec anyway. + #canary; + + constructor(target) { + const key = isObject(target) ? keyFor(target) : target; + super(key); + if (key !== target) { + this.#canary = new NativeWeakRef(target); + } + } + + // The live wrapper, a new one if the old one died while the Java object + // lived, or undefined once the Java object is gone. Like a native WeakRef + // target, the wrapper it returns stays alive until the job ends, so a second + // deref in the same job sees the same object. + deref() { + const target = WeakRefPrototypeDeref(this); + if (!isObject(target)) { + return target; + } + // False for a native WeakRef given this method through call(). + const cached = #canary in this; + if (cached) { + const last = this.#canary; + if (last === undefined) { + return target; + } + const live = WeakRefPrototypeDeref(last); + if (live !== undefined) { + return live; + } + } + const result = wrap(target); + // The native deref already keeps a target it returns as is. + if (result !== target && result !== undefined) { + const ref = new NativeWeakRef(result); + if (cached) { + this.#canary = ref; + } + } + return result; + } +} + +// weak-ref.js gave the native prototype `get` (an alias of `deref`) and a +// deprecated `clear`; inherited as is, `get` would hand out the lifetime key. +ObjectDefineProperty(WeakRef.prototype, "get", { + value: WeakRef.prototype.deref, + writable: true, + configurable: true, +}); + +class FinalizationRegistry extends NativeFinalizationRegistry { + constructor(cleanupCallback) { + super(cleanupCallback); + } + + // The default keeps `length` at 2, as on the native method. + register(target, heldValue, unregisterToken = undefined) { + // Checked on the original values: unwrapping would make target and + // heldValue differ. A call the native method rejects gets its error. + if (!canBeHeldWeakly(target) || target === heldValue || + (unregisterToken !== undefined && !canBeHeldWeakly(unregisterToken))) { + return FinalizationRegistryPrototypeRegister(this, target, heldValue, unregisterToken); + } + FinalizationRegistryPrototypeUnregister(this, receiverProbe); + FinalizationRegistryPrototypeRegister( + this, + isObject(target) ? keyFor(target) : target, + heldValue, + isObject(unregisterToken) ? keyFor(unregisterToken) : unregisterToken, + ); + } + + unregister(unregisterToken) { + if (FinalizationRegistryPrototypeUnregister(this, unregisterToken)) { + return true; + } + const other = otherKey(unregisterToken); + return other !== undefined && FinalizationRegistryPrototypeUnregister(this, other); + } +} + +for (const [name, value] of [ + ["WeakMap", WeakMap], + ["WeakSet", WeakSet], + ["WeakRef", WeakRef], + ["FinalizationRegistry", FinalizationRegistry], +]) { + ObjectDefineProperty(globalThis, name, { + value, + writable: true, + configurable: true, + enumerable: false, + }); +}