Skip to content

Commit 7e4f548

Browse files
committed
fix(runtime): weak collections validate before they make a key
- A canary's key and state are made only once the call can no longer fail: set, add, getOrInsert and register check their receiver first (WeakMap.prototype.set.call({}, canary, v) left a state and key behind), register leaves an invalid target or token to the native method, and getOrInsertComputed runs its callback before making the key, so a callback that throws leaves none. It no longer allocates a closure either. - register keeps the native length (2) and errors: register(1, 1) reports the invalid target rather than target and holdings being the same. - WeakRef.prototype.deref keeps the result alive for the job only when wrap() replaced what the native deref returned; it did so for every target. - The native methods are captured at startup through primordials, which gains WeakMap and its methods and Symbol.keyFor, instead of being resolved through super and the native prototype at call time. - Values that cannot be canaries skip the native unwrap call.
1 parent 3800de9 commit 7e4f548

2 files changed

Lines changed: 106 additions & 30 deletions

File tree

‎test-app/runtime/src/main/cpp/js/primordials.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,14 @@ const intrinsics = {
3737
Uint32Array,
3838
URIError,
3939
URL,
40+
WeakMap,
4041
WeakRef,
4142
WeakSet,
4243

4344
// Well-known symbols.
4445
SymbolFor: Symbol.for,
4546
SymbolIterator: Symbol.iterator,
47+
SymbolKeyFor: Symbol.keyFor,
4648
SymbolToStringTag: Symbol.toStringTag,
4749

4850
// Namespaces / prototypes.
@@ -108,6 +110,15 @@ const intrinsics = {
108110
StringPrototypeSlice: uncurryThis(String.prototype.slice),
109111
StringPrototypeStartsWith: uncurryThis(String.prototype.startsWith),
110112
SymbolPrototypeToString: uncurryThis(Symbol.prototype.toString),
113+
WeakMapPrototypeDelete: uncurryThis(WeakMap.prototype.delete),
114+
WeakMapPrototypeGet: uncurryThis(WeakMap.prototype.get),
115+
// The upsert proposal: undefined where V8 does not ship it.
116+
WeakMapPrototypeGetOrInsert: typeof WeakMap.prototype.getOrInsert === "function"
117+
? uncurryThis(WeakMap.prototype.getOrInsert) : undefined,
118+
WeakMapPrototypeGetOrInsertComputed: typeof WeakMap.prototype.getOrInsertComputed === "function"
119+
? uncurryThis(WeakMap.prototype.getOrInsertComputed) : undefined,
120+
WeakMapPrototypeHas: uncurryThis(WeakMap.prototype.has),
121+
WeakMapPrototypeSet: uncurryThis(WeakMap.prototype.set),
111122
WeakRefPrototypeDeref: uncurryThis(WeakRef.prototype.deref),
112123
WeakSetPrototypeAdd: uncurryThis(WeakSet.prototype.add),
113124
WeakSetPrototypeDelete: uncurryThis(WeakSet.prototype.delete),

‎test-app/runtime/src/main/cpp/js/weak-collections.js‎

Lines changed: 95 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,57 +6,108 @@
66
// references while the Java object lives on, and a later wrapper for the same
77
// object is a new JS object; keyed by the wrapper, entries and targets would be
88
// lost with it. Every other value passes through unchanged.
9+
//
10+
// They are subclasses of the native collections, so what subclassing shows is
11+
// left as it is: Object.getPrototypeOf(WeakMap.prototype) is the native
12+
// prototype, and WeakMap.toString() is not native code.
913

1014
const { unwrap, wrap } = binding;
11-
const { ObjectDefineProperty, TypeError } = primordials;
1215
const {
1316
FinalizationRegistry: NativeFinalizationRegistry,
17+
FinalizationRegistryPrototypeRegister,
18+
FinalizationRegistryPrototypeUnregister,
19+
ObjectDefineProperty,
20+
ObjectFreeze,
21+
SymbolKeyFor,
1422
WeakMap: NativeWeakMap,
23+
WeakMapPrototypeDelete,
24+
WeakMapPrototypeGet,
25+
WeakMapPrototypeGetOrInsert,
26+
WeakMapPrototypeGetOrInsertComputed,
27+
WeakMapPrototypeHas,
28+
WeakMapPrototypeSet,
1529
WeakRef: NativeWeakRef,
30+
WeakRefPrototypeDeref,
1631
WeakSet: NativeWeakSet,
17-
} = globalThis;
32+
WeakSetPrototypeAdd,
33+
WeakSetPrototypeDelete,
34+
WeakSetPrototypeHas,
35+
} = primordials;
36+
37+
// Only an object can be a canary; anything else goes to the native method as is.
38+
function isObject(value) {
39+
return (typeof value === "object" && value !== null) || typeof value === "function";
40+
}
41+
42+
// The values the native collections accept as keys and targets.
43+
function canBeHeldWeakly(value) {
44+
return isObject(value) || (typeof value === "symbol" && SymbolKeyFor(value) === undefined);
45+
}
1846

1947
// unwrap(value, true) makes the key on first use; lookups pass false so they
20-
// never create state for an object that was never a key.
48+
// never create state for an object that was never a key. A key is made only
49+
// once the native method can no longer reject the call, so a failed call leaves
50+
// no state behind: the receiver is checked first with a method that cannot
51+
// insert anything.
52+
function lookupKey(value) {
53+
return isObject(value) ? unwrap(value, false) : value;
54+
}
55+
56+
// Unregistering it finds nothing: it is never a token.
57+
const receiverProbe = ObjectFreeze({ __proto__: null });
58+
2159
class WeakMap extends NativeWeakMap {
2260
get(key) {
23-
return super.get(unwrap(key, false));
61+
return WeakMapPrototypeGet(this, lookupKey(key));
2462
}
2563

2664
set(key, value) {
27-
super.set(unwrap(key, true), value);
65+
if (isObject(key)) {
66+
WeakMapPrototypeHas(this, undefined);
67+
key = unwrap(key, true);
68+
}
69+
WeakMapPrototypeSet(this, key, value);
2870
return this;
2971
}
3072

3173
has(key) {
32-
return super.has(unwrap(key, false));
74+
return WeakMapPrototypeHas(this, lookupKey(key));
3375
}
3476

3577
delete(key) {
36-
return super.delete(unwrap(key, false));
78+
return WeakMapPrototypeDelete(this, lookupKey(key));
3779
}
3880
}
3981

4082
// V8 ships the upsert proposal; inherited, these would key on the wrapper.
41-
if (typeof NativeWeakMap.prototype.getOrInsert === "function") {
83+
if (WeakMapPrototypeGetOrInsert !== undefined) {
4284
ObjectDefineProperty(WeakMap.prototype, "getOrInsert", {
4385
value: function getOrInsert(key, value) {
44-
return NativeWeakMap.prototype.getOrInsert.call(this, unwrap(key, true), value);
86+
if (isObject(key)) {
87+
WeakMapPrototypeHas(this, undefined);
88+
key = unwrap(key, true);
89+
}
90+
return WeakMapPrototypeGetOrInsert(this, key, value);
4591
},
4692
writable: true,
4793
configurable: true,
4894
});
4995
}
50-
if (typeof NativeWeakMap.prototype.getOrInsertComputed === "function") {
96+
if (WeakMapPrototypeGetOrInsertComputed !== undefined) {
5197
ObjectDefineProperty(WeakMap.prototype, "getOrInsertComputed", {
5298
value: function getOrInsertComputed(key, callbackfn) {
53-
if (typeof callbackfn !== "function") {
54-
throw new TypeError("WeakMap.prototype.getOrInsertComputed: callback is not a function");
99+
if (!isObject(key) || typeof callbackfn !== "function") {
100+
return WeakMapPrototypeGetOrInsertComputed(this, key, callbackfn);
101+
}
102+
const existing = unwrap(key, false);
103+
if (WeakMapPrototypeHas(this, existing)) {
104+
return WeakMapPrototypeGet(this, existing);
55105
}
56-
// The callback sees the key it was given, not the lifetime key.
57-
return NativeWeakMap.prototype.getOrInsertComputed.call(this, unwrap(key, true), () =>
58-
callbackfn(key),
59-
);
106+
// Before the key exists, so a callback that throws leaves none; it sees
107+
// the key it was given, not the lifetime key.
108+
const value = callbackfn(key);
109+
WeakMapPrototypeSet(this, unwrap(key, true), value);
110+
return value;
60111
},
61112
writable: true,
62113
configurable: true,
@@ -65,22 +116,26 @@ if (typeof NativeWeakMap.prototype.getOrInsertComputed === "function") {
65116

66117
class WeakSet extends NativeWeakSet {
67118
add(value) {
68-
super.add(unwrap(value, true));
119+
if (isObject(value)) {
120+
WeakSetPrototypeHas(this, undefined);
121+
value = unwrap(value, true);
122+
}
123+
WeakSetPrototypeAdd(this, value);
69124
return this;
70125
}
71126

72127
has(value) {
73-
return super.has(unwrap(value, false));
128+
return WeakSetPrototypeHas(this, lookupKey(value));
74129
}
75130

76131
delete(value) {
77-
return super.delete(unwrap(value, false));
132+
return WeakSetPrototypeDelete(this, lookupKey(value));
78133
}
79134
}
80135

81136
class WeakRef extends NativeWeakRef {
82137
constructor(target) {
83-
const key = unwrap(target, true);
138+
const key = isObject(target) ? unwrap(target, true) : target;
84139
super(key);
85140
// The target itself, not only its key, stays alive until the job ends.
86141
if (key !== target) {
@@ -93,8 +148,13 @@ class WeakRef extends NativeWeakRef {
93148
// target, the wrapper it returns stays alive until the job ends, so a second
94149
// deref in the same job sees the same object.
95150
deref() {
96-
const result = wrap(super.deref());
97-
if (typeof result === "object" && result !== null) {
151+
const target = WeakRefPrototypeDeref(this);
152+
if (!isObject(target)) {
153+
return target;
154+
}
155+
const result = wrap(target);
156+
// The native deref already keeps a target it returns as is.
157+
if (result !== target && result !== undefined) {
98158
new NativeWeakRef(result);
99159
}
100160
return result;
@@ -114,20 +174,25 @@ class FinalizationRegistry extends NativeFinalizationRegistry {
114174
super(cleanupCallback);
115175
}
116176

117-
register(target, heldValue, unregisterToken) {
118-
// Checked on the original values: unwrapping would make them differ.
119-
if (target === heldValue) {
120-
throw new TypeError("FinalizationRegistry.prototype.register: target and holdings must not be same");
177+
// The default keeps `length` at 2, as on the native method.
178+
register(target, heldValue, unregisterToken = undefined) {
179+
// Checked on the original values: unwrapping would make target and
180+
// heldValue differ. A call the native method rejects gets its error.
181+
if (!canBeHeldWeakly(target) || target === heldValue ||
182+
(unregisterToken !== undefined && !canBeHeldWeakly(unregisterToken))) {
183+
return FinalizationRegistryPrototypeRegister(this, target, heldValue, unregisterToken);
121184
}
122-
super.register(
123-
unwrap(target, true),
185+
FinalizationRegistryPrototypeUnregister(this, receiverProbe);
186+
FinalizationRegistryPrototypeRegister(
187+
this,
188+
isObject(target) ? unwrap(target, true) : target,
124189
heldValue,
125-
unregisterToken === undefined ? undefined : unwrap(unregisterToken, true),
190+
isObject(unregisterToken) ? unwrap(unregisterToken, true) : unregisterToken,
126191
);
127192
}
128193

129194
unregister(unregisterToken) {
130-
return super.unregister(unwrap(unregisterToken, false));
195+
return FinalizationRegistryPrototypeUnregister(this, lookupKey(unregisterToken));
131196
}
132197
}
133198

0 commit comments

Comments
 (0)