JavaScript: for-in keeps a detached proxy reachable, Promise checks its executor first, and late Proxy and Reflect respect a sealed global

This commit is contained in:
dotCooCoo committed 2026-11-28 23:11:43 -08:00
1 parent c7c77fea24
commit 0248f7eb74
5 files changed
+98 -7

No files matched your search

+3 -3
View File
@@ -5,7 +5,7 @@
use std::rc::Rc;
use super::object::{from_prop, names_array, to_desc};
use super::{arg, data, method, native};
use super::{arg, method, native};
use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key};
use crate::interp::{Desc, Interp, JsResult};
use crate::proxy::desc_values;
@@ -22,7 +22,7 @@ pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> {
// Naming a new method can collect, and the constructor is reachable from nowhere else
// until it is published.
interp.rooted(&[Value::Object(proxy)], |interp| method(interp, proxy, "revocable", revocable, 2))?;
data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?;
interp.define_own_property(global, key("Proxy"), &Desc::data(Value::Object(proxy), HIDDEN), true)?;
}
if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) {
install_reflect(interp)?;
@@ -37,7 +37,7 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> {
let object_proto = interp.intrinsics.object_proto;
let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
interp.rooted(&[Value::Object(reflect)], |interp| reflect_methods(interp, reflect))?;
data(interp, global, "Reflect", Value::Object(reflect), HIDDEN)
interp.define_own_property(global, key("Reflect"), &Desc::data(Value::Object(reflect), HIDDEN), true).map(|_| ())
}
/// Defines `Reflect`'s functions on `reflect`, which the caller keeps reachable.
+3
View File
@@ -331,6 +331,9 @@ impl Interp {
self.held_bytes = held;
r?
} else {
if subclass && name == "Promise" && !args.first().is_some_and(|v| self.is_callable(v)) {
return Err(self.type_error("the Promise executor is not a function"));
}
// `Number`, `String`, `Date` and `Function` convert their arguments before
// `prototype` is read (sections 20.1.1.1, 21.1.1.1, 20.4.2 and 19.2.1.1.1), so
// a conversion that throws reads nothing from `new.target`.
+6 -2
View File
@@ -3245,8 +3245,9 @@ impl Interp {
}
/// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its
/// `ownKeys` trap and the next object with its `getPrototypeOf` trap, which
/// `temp_roots[slot]` keeps reachable. Descriptors are checked when iteration reaches each name.
/// `ownKeys` trap and the next object with its `getPrototypeOf` trap.
/// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype.
/// Descriptors are checked when iteration reaches each name.
fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<Vec<Key>> {
let mut seen = std::collections::HashSet::new();
let mut held = HeldBytes::new(self);
@@ -3254,6 +3255,9 @@ impl Interp {
let mut cur = Some(id);
while let Some(o) = cur {
if self.is_proxy(o) {
if let Some(root) = self.temp_roots.get_mut(slot) {
*root = Value::Object(o);
}
let keys = self.own_keys(o)?;
for k in keys {
self.use_fuel()?;
+77
View File
@@ -112,6 +112,38 @@ fn late_proxy_and_reflect_installation_keeps_their_methods_reachable() {
assert!(realm.interp().heap.collections > 0);
}
#[test]
fn late_proxy_and_reflect_installation_respects_global_extensibility() {
for operation in ["preventExtensions", "seal", "freeze"] {
for (setup, has_proxy, has_reflect) in
[("", false, false), ("var Proxy = 7;", true, false), ("var Reflect = 8;", false, true), ("var Proxy = 7, Reflect = 8;", true, true)]
{
let mut realm = Realm::new();
assert_eq!(realm.run(&format!("{setup} var runs = 0; Object.{operation}(this); 0")), Ok(JsValue::Number(0.0)));
realm.set_es2015(true);
if has_proxy && has_reflect {
assert_eq!(realm.run("Proxy + Reflect"), Ok(JsValue::Number(15.0)));
} else {
for _ in 0..2 {
let err = realm.run("runs++").unwrap_err();
assert_eq!(err.kind, RunErrorKind::Internal);
assert!(err.message.contains("Proxy and Reflect could not be installed"), "{err:?}");
assert!(err.message.contains("the object is not extensible"), "{err:?}");
let missing = if has_proxy { "Reflect" } else { "Proxy" };
assert!(err.message.contains(missing), "{err:?}");
}
}
realm.set_es2015(false);
let check = format!(
"runs === 0 && !Object.isExtensible(this) && this.hasOwnProperty('Proxy') === {has_proxy}
&& this.hasOwnProperty('Reflect') === {has_reflect}
&& (typeof Proxy === 'undefined' || Proxy === 7) && (typeof Reflect === 'undefined' || Reflect === 8)"
);
assert_eq!(realm.run(&check), Ok(JsValue::Bool(true)), "{operation}: {setup}");
}
}
}
// ---- Proxy ----
#[test]
@@ -986,6 +1018,51 @@ fn reflect_construct_allows_distinct_new_targets_for_collections_and_typed_array
);
}
#[test]
fn for_in_keeps_a_proxy_reachable_after_its_own_keys_trap_detaches_it() {
truth_collecting(
"var o, reads = 0;
o = Object.create(new Proxy({ first: 1, second: 2 }, {
ownKeys: function () { Reflect.setPrototypeOf(o, null); return ['first', 'second']; },
getPrototypeOf: function () { reads++; return null; }
}));
var seen = [];
for (var k in o) seen.push(k);
reads === 1 && seen.length === 0 && Object.getPrototypeOf(o) === null",
);
}
#[test]
fn reflect_construct_validates_promise_executors_before_reading_the_prototype() {
for trap in ["return t[k];", "throw 'prototype read';"] {
truth(&format!(
"var reads = 0;
var nt = new Proxy(function () {{}}, {{ get: function (t, k) {{
if (k === 'prototype') {{ reads++; {trap} }} return t[k];
}} }});
var invalid = [undefined, null, false, 1, 'executor', {{}}, new Proxy({{}}, {{}})], rejected = 0;
for (var i = 0; i < invalid.length; i++) {{
if (type_error(function () {{ Reflect.construct(Promise, [invalid[i]], nt); }})) rejected++;
}}
rejected === invalid.length && type_error(function () {{ Reflect.construct(Promise, [], nt); }}) && reads === 0"
));
}
truth_collecting(
"var log = [], proto = {};
var nt = new Proxy(function () {}, { get: function (t, k) {
if (k === 'prototype') { log.push('prototype'); return proto; } return t[k];
} });
var p = Reflect.construct(Promise, [function (resolve) { log.push('executor'); resolve(7); }], nt);
log.join() === 'prototype,executor' && Object.getPrototypeOf(p) === proto",
);
truth(
"var ran = false, marker = {}, caught = false;
var nt = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') throw marker; return t[k]; } });
try { Reflect.construct(Promise, [function () { ran = true; }], nt); } catch (e) { caught = e === marker; }
caught && !ran",
);
}
#[test]
fn for_in_checks_proxy_descriptors_only_when_each_candidate_is_reached() {
truth(
+9 -2
View File
@@ -2859,6 +2859,8 @@ a `for-in` prototype walk count against the heap limit. A trap result that break
or any operation on a revoked proxy, throws a `TypeError`. A
proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets
`Proxy` and `Reflect` at its first `.js` run and keeps them for later `.jsx` runs.
Existing globals with either name are preserved. If a missing global cannot be added because the global object
is nonextensible, sealed or frozen, the run fails with an installation error before the script executes.
An empty-handler proxy forwards construction of built-ins, including `Map` and typed arrays, and reads
the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor
as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object.
@@ -2870,14 +2872,19 @@ and throws `TypeError`. In a realm with `Symbol.toStringTag`, `Reflect` has the
its symbol property is nonwritable, nonenumerable and configurable.
`ArrayBuffer` and typed arrays constructed from primitive lengths convert the length before reading
`newTarget.prototype`. `DataView` validates its buffer, byte offset and byte length before reading that prototype.
A failure during conversion or validation throws before the prototype getter runs. `Reflect.has` and an empty-handler proxy's
A failure during conversion or validation throws before the prototype getter runs. `Reflect.construct(Promise, args, newTarget)`
rejects a missing or noncallable executor with `TypeError` before reading `newTarget.prototype`.
For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call.
`Reflect.has` and an empty-handler proxy's
membership checks use host collection indexers, including numeric indices and named items.
The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating
its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations
and symbol enumeration on a revoked proxy also throw `TypeError`.
`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order,
then other strings in insertion order; an array's `length` precedes its other non-index strings.
A proxy's `ownKeys` trap determines its key order. A `for-in` loop checks each proxy candidate's descriptor
A proxy's `ownKeys` trap determines its key order. A `for-in` prototype walk keeps the current proxy reachable
through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain.
A `for-in` loop checks each proxy candidate's descriptor
when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate
names are rejected; a later getter's exception takes precedence over the duplicate-name error.
Deleting a binding in a `with` scope calls the proxy's `deleteProperty`