diff --git a/crates/perry-runtime/src/object/delete_rest.rs b/crates/perry-runtime/src/object/delete_rest.rs index d55750f3801..fac6bd7a63a 100644 --- a/crates/perry-runtime/src/object/delete_rest.rs +++ b/crates/perry-runtime/src/object/delete_rest.rs @@ -58,8 +58,6 @@ pub extern "C" fn js_object_delete_field( // boundary (HANDLE_BAND_MAX = 0x100000), so the fetch (0x40000..0xE0000) and // zlib (0xE0000..0xF0000) handle bands fell through to the heap path below // and got dereferenced -> SIGSEGV on Linux. Use the centralized predicate. - // A handle simply misses `class_name_for_id` and returns 1, which is the - // correct result for `delete request.foo` (Node: true). if crate::value::addr_class::is_handle_band(obj as usize) { unsafe { if let Some(name) = super::has_own_helpers::str_from_string_header(key) { @@ -68,6 +66,17 @@ pub extern "C" fn js_object_delete_field( super::class_registry::class_delete_own_dynamic_prop(class_id, name); super::class_registry::class_mark_key_deleted(class_id, name); } + // #6363: a native HANDLE's own properties are its user expandos. + // `delete` used to unconditionally report success while LEAVING + // the property in place — `delete headers.foo` returned true and + // `headers.foo` still read back its old value. Actually remove + // it, and reject (false) a non-configurable one, matching + // ordinary `[[Delete]]`. An absent key still reports true, which + // is what `delete request.__nope` must do (Node: true). + return i32::from(super::handle_expando::handle_expando_delete( + obj as usize as i64, + name, + )); } } return 1; diff --git a/crates/perry-runtime/src/object/descriptors.rs b/crates/perry-runtime/src/object/descriptors.rs index 7b9f2926a7d..36a07dfb1d7 100644 --- a/crates/perry-runtime/src/object/descriptors.rs +++ b/crates/perry-runtime/src/object/descriptors.rs @@ -122,6 +122,53 @@ pub extern "C" fn js_object_get_own_property_descriptor(obj_value: f64, key_valu return crate::proxy::js_reflect_get_own_property_descriptor(obj_value, key_value); } + // #6363: a native HANDLE receiver (zlib stream, fetch Headers/Request/ + // Response/Blob, crypto hash, …) is a pointer-tagged registry id, not a + // heap object. Its own properties are exactly the user-assigned expandos + // — from a plain `handle.foo = v` write or an + // `Object.defineProperty(handle, …)`; both land in the `handle_expando` + // table. The handle's TYPED surface (`blob.size`, `response.status`) is + // prototype accessors in Node, so it is deliberately NOT reported here: + // `getOwnPropertyDescriptor(blob, "size")` is `undefined` in Node too. + // Falling through to the ordinary path would deref the id as an + // `ObjectHeader` and report `undefined` for a property that IS defined. + if obj_jv.is_pointer() { + let raw = obj_jv.as_pointer::() as usize; + if crate::value::addr_class::is_small_handle(raw) { + if crate::symbol::js_is_symbol(key_value) != 0 { + return symbol_own_property_descriptor(obj_value, key_value); + } + let Some(name) = metadata_key_to_string(key_value) else { + return f64::from_bits(crate::value::TAG_UNDEFINED); + }; + let hid = raw as i64; + if !crate::object::handle_expando::handle_expando_has(hid, &name) { + return f64::from_bits(crate::value::TAG_UNDEFINED); + } + let attrs = crate::object::handle_expando::handle_expando_attrs(hid, &name); + if let Some(acc) = + crate::object::handle_expando::handle_expando_accessor(hid, &name) + { + // A `0` half means "absent" — reflect it as `undefined`, not 0. + let undef = crate::value::TAG_UNDEFINED; + return build_accessor_descriptor( + f64::from_bits(if acc.get == 0 { undef } else { acc.get }), + f64::from_bits(if acc.set == 0 { undef } else { acc.set }), + attrs.enumerable(), + attrs.configurable(), + ); + } + let value = crate::object::handle_expando::handle_expando_data_get(hid, &name) + .unwrap_or(f64::from_bits(crate::value::TAG_UNDEFINED)); + return build_data_descriptor( + value, + attrs.writable(), + attrs.enumerable(), + attrs.configurable(), + ); + } + } + // A per-evaluation class object (`ClassExprFresh`, #1772/#1787) is a // POINTER-tagged heap object, not a `0x7FFE` class ref, so the // `class_ref_id` branch below never fires for it. Its static METHODS @@ -203,35 +250,7 @@ pub extern "C" fn js_object_get_own_property_descriptor(obj_value: f64, key_valu } if crate::symbol::js_is_symbol(key_value) != 0 { - let owner = crate::symbol::obj_key_from_f64(obj_value); - let sym_key = crate::symbol::sym_key_from_f64(key_value); - if owner == 0 || sym_key == 0 { - return f64::from_bits(crate::value::TAG_UNDEFINED); - } - let attrs = crate::symbol::get_symbol_property_attrs(owner, sym_key) - .unwrap_or(PropertyAttrs::new(true, true, true)); - if let Some((get, set)) = crate::symbol::symbol_accessor_descriptor_bits(owner, sym_key) - { - // A `0` get/set means "absent half" — surface it as `undefined` - // (not the number `0`) so a get-only accessor reflects - // `{ get, set: undefined }`. - let undef = crate::value::TAG_UNDEFINED; - return build_accessor_descriptor( - f64::from_bits(if get == 0 { undef } else { get }), - f64::from_bits(if set == 0 { undef } else { set }), - attrs.enumerable(), - attrs.configurable(), - ); - } - if let Some(value_bits) = crate::symbol::symbol_property_root_bits(owner, sym_key) { - return build_data_descriptor( - f64::from_bits(value_bits), - attrs.writable(), - attrs.enumerable(), - attrs.configurable(), - ); - } - return f64::from_bits(crate::value::TAG_UNDEFINED); + return symbol_own_property_descriptor(obj_value, key_value); } // TypedArrays are Integer-Indexed exotic objects: a canonical numeric @@ -856,6 +875,76 @@ pub extern "C" fn js_object_get_own_property_descriptor(obj_value: f64, key_valu /// Build a `{ value, writable, enumerable, configurable }` data descriptor /// object. Shared by the string-primitive descriptor path (#2818). +/// #6363: the own STRING keys of a native HANDLE, as a NaN-boxed JS array. +/// +/// A handle (zlib stream, fetch Headers/Request/Response/Blob, crypto hash, …) +/// is a registry id, not a heap object; its typed surface (`blob.size`) is +/// prototype accessors in Node and is therefore not an own key. What IS an own +/// key is anything the user attached — a plain `handle.foo = v` write or an +/// `Object.defineProperty(handle, …)` — all of which live in the +/// `handle_expando` table. `enumerable_only` selects the `Object.keys` / +/// for-in / spread surface over the `getOwnPropertyNames` one. +pub(crate) unsafe fn handle_own_names_array(hid: i64, enumerable_only: bool) -> f64 { + let arr = handle_own_names_raw_array(hid, enumerable_only); + f64::from_bits((arr as u64) | 0x7FFD_0000_0000_0000) +} + +/// Raw-`ArrayHeader` sibling of [`handle_own_names_array`], for the enumeration +/// paths that build on `*mut ArrayHeader` rather than NaN-boxed values. +pub(crate) unsafe fn handle_own_names_raw_array( + hid: i64, + enumerable_only: bool, +) -> *mut crate::array::ArrayHeader { + let names = crate::object::handle_expando::handle_expando_own_keys(hid, enumerable_only); + // Exact capacity, so `js_array_push` cannot reallocate under us (the same + // contract `js_object_get_own_property_names`' own name-array builder relies + // on a few lines up). + let arr = crate::array::js_array_alloc(names.len() as u32); + for name in &names { + let s = crate::string::js_string_from_bytes(name.as_ptr(), name.len() as u32); + crate::array::js_array_push(arr, JSValue::string_ptr(s)); + } + arr +} + +/// `[[GetOwnProperty]]` for a SYMBOL key, from the symbol side tables. +/// +/// Both tables are keyed by the receiver's NaN-box PAYLOAD +/// (`symbol::obj_key_from_f64`), never by a dereferenced address, so this works +/// unchanged for a heap object and for a native HANDLE id (#6363) — which is why +/// the handle branch in `js_object_get_own_property_descriptor` delegates here +/// instead of re-deriving the lookup. +pub(crate) unsafe fn symbol_own_property_descriptor(obj_value: f64, key_value: f64) -> f64 { + let owner = crate::symbol::obj_key_from_f64(obj_value); + let sym_key = crate::symbol::sym_key_from_f64(key_value); + if owner == 0 || sym_key == 0 { + return f64::from_bits(crate::value::TAG_UNDEFINED); + } + let attrs = crate::symbol::get_symbol_property_attrs(owner, sym_key) + .unwrap_or(PropertyAttrs::new(true, true, true)); + if let Some((get, set)) = crate::symbol::symbol_accessor_descriptor_bits(owner, sym_key) { + // A `0` get/set means "absent half" — surface it as `undefined` + // (not the number `0`) so a get-only accessor reflects + // `{ get, set: undefined }`. + let undef = crate::value::TAG_UNDEFINED; + return build_accessor_descriptor( + f64::from_bits(if get == 0 { undef } else { get }), + f64::from_bits(if set == 0 { undef } else { set }), + attrs.enumerable(), + attrs.configurable(), + ); + } + if let Some(value_bits) = crate::symbol::symbol_property_root_bits(owner, sym_key) { + return build_data_descriptor( + f64::from_bits(value_bits), + attrs.writable(), + attrs.enumerable(), + attrs.configurable(), + ); + } + f64::from_bits(crate::value::TAG_UNDEFINED) +} + pub(crate) unsafe fn build_data_descriptor( value: f64, writable: bool, @@ -971,8 +1060,10 @@ pub extern "C" fn js_object_get_own_property_names(obj_value: f64) -> f64 { return names; } } - let empty = crate::array::js_array_alloc(0); - return f64::from_bits((empty as u64) | 0x7FFD_0000_0000_0000); + // #6363: the handle's own properties are the user-assigned + // expandos (`handle.foo = v`, `Object.defineProperty(handle, …)`). + // `getOwnPropertyNames` reports them regardless of enumerability. + return handle_own_names_array(raw as i64, false); } } // #5268: a native-module namespace/default object (`fs`, `path`, …) diff --git a/crates/perry-runtime/src/object/field_get_set/enumeration.rs b/crates/perry-runtime/src/object/field_get_set/enumeration.rs index dcf3853095b..09f23158396 100644 --- a/crates/perry-runtime/src/object/field_get_set/enumeration.rs +++ b/crates/perry-runtime/src/object/field_get_set/enumeration.rs @@ -163,28 +163,49 @@ pub extern "C" fn js_object_keys_value(value: f64) -> *mut ArrayHeader { if jv.is_pointer() { let ptr = jv.as_pointer::() as usize; // A POINTER_TAG registry handle (zlib stream, fetch Request/Response/ - // Headers/Blob, …) is not an address. It exposes no own enumerable - // properties — its surface lives on the prototype as accessors — so - // return empty instead of dereferencing unmapped low memory. + // Headers/Blob, …) is not an address — never dereference it. Its TYPED + // surface (`blob.size`, `response.status`) lives on the prototype as + // accessors, so it contributes no own keys; but anything the USER + // attached does (`handle.foo = v`, or an + // `Object.defineProperty(handle, …)` with `enumerable: true`). Node + // treats these as ordinary extensible objects, so enumerate the + // expandos (#6363) plus whatever the stdlib reports as a real own shape + // (`StringDecoder.encoding`). + // + // NB: `is_handle_band` used to return empty BEFORE the `is_small_handle` + // arm below, leaving the `handle_own_property_names_dispatch` lookup + // unreachable — `Object.keys(new StringDecoder())` was `[]` while + // `Object.getOwnPropertyNames` (which does consult it) said + // `["encoding"]`. One branch now, so the two agree. if crate::value::addr_class::is_handle_band(ptr) { - return crate::array::js_array_alloc(0); - } - if crate::value::addr_class::is_small_handle(ptr) { + if !crate::value::addr_class::is_small_handle(ptr) { + return crate::array::js_array_alloc(0); + } + let mut out = crate::array::js_array_alloc(0); if let Some(dispatch) = super::super::class_registry::handle_own_property_names_dispatch() { let names = unsafe { dispatch(ptr as i64) }; - if names.to_bits() != crate::value::TAG_UNDEFINED { - let bits = names.to_bits(); - if bits >> 48 == 0x7FFD { - let arr = (bits & crate::value::POINTER_MASK) as *mut ArrayHeader; - if !arr.is_null() { - return arr; + let bits = names.to_bits(); + if bits != crate::value::TAG_UNDEFINED && bits >> 48 == 0x7FFD { + let arr = (bits & crate::value::POINTER_MASK) as *mut ArrayHeader; + if !arr.is_null() { + let n = crate::array::js_array_length(arr); + for i in 0..n { + let kv = crate::array::js_array_get(arr, i); + out = crate::array::js_array_push_f64(out, f64::from_bits(kv.bits())); } } } } - return crate::array::js_array_alloc(0); + let expandos = + unsafe { super::super::descriptors::handle_own_names_raw_array(ptr as i64, true) }; + let n = crate::array::js_array_length(expandos); + for i in 0..n { + let kv = crate::array::js_array_get(expandos, i); + out = crate::array::js_array_push_f64(out, f64::from_bits(kv.bits())); + } + return out; } if crate::typedarray::lookup_typed_array_kind(ptr).is_some() { return unsafe { @@ -506,12 +527,12 @@ pub extern "C" fn js_object_values_value(value: f64) -> *mut ArrayHeader { } if jv.is_pointer() { let ptr = jv.as_pointer::() as usize; - // A POINTER_TAG registry handle (zlib stream, fetch Request/Response/ - // Headers/Blob, …) is not an address. It exposes no own enumerable - // properties — its surface lives on the prototype as accessors — so - // return empty instead of dereferencing unmapped low memory. + // A POINTER_TAG registry handle — see `js_object_keys_value`. Derive the + // values from its own enumerable keys so a user expando + // (`handle.foo = 1`) shows up here exactly as it does in `Object.keys` + // (#6363), instead of dereferencing unmapped low memory. if crate::value::addr_class::is_handle_band(ptr) { - return crate::array::js_array_alloc(0); + return handle_own_entries(value, HandleEnum::Values); } if crate::typedarray::lookup_typed_array_kind(ptr).is_some() { return unsafe { @@ -528,6 +549,54 @@ pub extern "C" fn js_object_values_value(value: f64) -> *mut ArrayHeader { crate::array::js_array_alloc(0) } +/// Which projection of a handle's own enumerable properties to build. +enum HandleEnum { + Values, + Entries, +} + +/// #6363: `Object.values` / `Object.entries` for a native HANDLE receiver. +/// +/// Reuses `js_object_keys_value`'s own-key list (so all three agree on what a +/// handle owns) and reads each value back through the ordinary dynamic property +/// get — which routes to the handle dispatcher and thus honours both the typed +/// surface and the expando table, including a `defineProperty` getter. +fn handle_own_entries(value: f64, what: HandleEnum) -> *mut ArrayHeader { + let keys = js_object_keys_value(value); + let n = crate::array::js_array_length(keys); + let mut out = crate::array::js_array_alloc(n); + for i in 0..n { + let kv = crate::array::js_array_get(keys, i); + let key_f64 = f64::from_bits(kv.bits()); + let mut scratch = [0u8; crate::value::SHORT_STRING_MAX_LEN]; + let Some(name) = (unsafe { crate::string::js_string_key_bytes(kv, &mut scratch) }) else { + continue; + }; + let v = unsafe { + crate::value::js_dynamic_object_get_property( + value, + name.as_ptr() as *const i8, + name.len(), + ) + }; + match what { + HandleEnum::Values => { + out = crate::array::js_array_push_f64(out, v); + } + HandleEnum::Entries => { + let mut pair = crate::array::js_array_alloc(2); + pair = crate::array::js_array_push_f64(pair, key_f64); + pair = crate::array::js_array_push_f64(pair, v); + out = crate::array::js_array_push_f64( + out, + f64::from_bits(JSValue::pointer(pair as *const u8).bits()), + ); + } + } + } + out +} + /// Tag-dispatching `Object.entries(value)` — see [`js_object_keys_value`]. /// A string yields `[[index, char], …]` (`Object.entries("hi") === /// [["0","h"],["1","i"]]`); objects/arrays delegate to `js_object_entries`; @@ -570,12 +639,10 @@ pub extern "C" fn js_object_entries_value(value: f64) -> *mut ArrayHeader { } if jv.is_pointer() { let ptr = jv.as_pointer::() as usize; - // A POINTER_TAG registry handle (zlib stream, fetch Request/Response/ - // Headers/Blob, …) is not an address. It exposes no own enumerable - // properties — its surface lives on the prototype as accessors — so - // return empty instead of dereferencing unmapped low memory. + // A POINTER_TAG registry handle — see `js_object_keys_value` / the + // `Object.values` twin above (#6363). if crate::value::addr_class::is_handle_band(ptr) { - return crate::array::js_array_alloc(0); + return handle_own_entries(value, HandleEnum::Entries); } if crate::typedarray::lookup_typed_array_kind(ptr).is_some() { return unsafe { diff --git a/crates/perry-runtime/src/object/field_get_set/has_property.rs b/crates/perry-runtime/src/object/field_get_set/has_property.rs index c5107c85cef..93525f0d822 100644 --- a/crates/perry-runtime/src/object/field_get_set/has_property.rs +++ b/crates/perry-runtime/src/object/field_get_set/has_property.rs @@ -208,17 +208,45 @@ pub extern "C" fn js_object_has_property(obj: f64, key: f64) -> f64 { // A Web Fetch / zlib handle-band value (Headers/Request/Response, zlib // streams) at or above the fetch band is a registry id, not a heap object — - // the pointer paths below would dereference the id and segfault. `key in - // ` has no own-property meaning for these, so report `false`. - // Common/small handles (below the fetch band) are intentionally NOT caught - // here: they fall through to the registered small-handle property path later - // in this function. Same family as the string_from_header / inline-`.length` - // guards. + // the pointer paths below would dereference the id and segfault, so this + // arm must resolve `key in ` on its own and return. + // + // #6363: it used to report a flat `false`. That was a guard, not a route: + // a handle DOES have own properties — anything the user attached, via + // `handle.foo = v` or `Object.defineProperty(handle, …)` — and it has the + // typed native surface (`"status" in response`) on top. `hasOwnProperty` + // reports both, so a bare `false` here had `in` contradicting it. Answer + // from the expando table first (authoritative for own properties, and it + // sees a `{ value: undefined }` define that a [[Get]] probe cannot + // distinguish from absent), then fall back to the property dispatcher for + // the typed surface — which is exactly what the common/small-handle band + // already does further down this function. if obj_val.is_pointer() { let addr = (obj_val.bits() & crate::value::POINTER_MASK) as usize; if addr >= crate::value::addr_class::COMMON_HANDLE_BAND_END && crate::value::addr_class::is_handle_band(addr) { + if unsafe { crate::symbol::js_is_symbol(key) } != 0 { + return if unsafe { crate::symbol::js_object_has_own_symbol(obj, key) } { + nanbox_true + } else { + nanbox_false + }; + } + if let Some(name) = unsafe { crate::object::metadata_key_to_string(key) } { + if crate::object::handle_expando::handle_expando_has(addr as i64, &name) { + return nanbox_true; + } + if let Some(dispatch) = super::super::class_registry::handle_property_dispatch() { + let found = unsafe { + dispatch(addr as i64, name.as_ptr(), name.len()).to_bits() + != crate::value::TAG_UNDEFINED + }; + if found { + return nanbox_true; + } + } + } return nanbox_false; } } diff --git a/crates/perry-runtime/src/object/handle_expando.rs b/crates/perry-runtime/src/object/handle_expando.rs index 714bf26dbfa..40943aac798 100644 --- a/crates/perry-runtime/src/object/handle_expando.rs +++ b/crates/perry-runtime/src/object/handle_expando.rs @@ -15,12 +15,28 @@ //! storage that closures get from `CLOSURE_PROPS` (see //! `closure/dynamic_props.rs`), modeled directly on that code. //! +//! Attributes / accessors (#6363): `Object.defineProperty(handle, k, desc)` +//! stores the VALUE here but records the `writable`/`enumerable`/`configurable` +//! bits and any `get`/`set` pair in the ordinary +//! `descriptor_state::{PROPERTY_DESCRIPTORS, ACCESSOR_DESCRIPTORS}` side tables, +//! keyed by the handle id. Those tables are keyed by a plain `usize` and heap +//! addresses always sit above `HANDLE_BAND_MAX`, so a handle id can never +//! collide with a real owner address; their GC scanners leave the key alone +//! (a handle is not a forwardable heap address) and their dead-owner sweep +//! skips it (`attributed_owner_header` rejects an address that belongs to no +//! arena page / malloc header). Reusing them gets attribute + accessor storage, +//! rooting of the accessor closures, and `getOwnPropertyDescriptor` for free. +//! //! GC: handle ids are stable small integers that never move, so — unlike the //! closure table — no metadata re-keying is needed. Only the stored VALUES are //! real JS references, so the registered mutable root scanner traces them in //! every phase (keeping e.g. a stored array and its elements alive) and rewrites //! the stored bits when a copying collection moves the value. +use super::descriptor_state::{ + get_accessor_descriptor, get_property_attrs, PropertyAttrs, ACCESSOR_DESCRIPTORS, + PROPERTY_DESCRIPTORS, +}; use std::cell::RefCell; use std::collections::HashMap; @@ -32,8 +48,13 @@ use std::collections::HashMap; // keeps the side-table aligned with the per-thread GC, matching the documented // threading model. The mutable root scanner is registered once but reads the // CURRENT thread's table on each GC, so each thread traces only its own values. +// +// The per-handle entry is a `Vec<(name, bits)>` rather than a `HashMap` so own +// keys come back in INSERTION order — `Object.keys(handle)` / `{...handle}` are +// ordered in JS, and handles carry a handful of expandos at most, so the linear +// scan is cheaper than hashing. thread_local! { - static HANDLE_EXPANDO_PROPS: RefCell>> = + static HANDLE_EXPANDO_PROPS: RefCell>> = RefCell::new(HashMap::new()); } @@ -46,10 +67,12 @@ pub fn handle_expando_set(handle: i64, name: &str, value: f64) { } let bits = value.to_bits(); HANDLE_EXPANDO_PROPS.with(|cell| { - cell.borrow_mut() - .entry(handle) - .or_default() - .insert(name.to_string(), bits); + let mut map = cell.borrow_mut(); + let props = map.entry(handle).or_default(); + match props.iter_mut().find(|(k, _)| k == name) { + Some(slot) => slot.1 = bits, + None => props.push((name.to_string(), bits)), + } }); // Parent is the (non-heap) handle id, so pass 0 as the parent address — the // scanner traces the value unconditionally, and the barrier only needs to @@ -60,7 +83,37 @@ pub fn handle_expando_set(handle: i64, name: &str, value: f64) { /// Read back an own property previously stored via `handle_expando_set`. /// Returns `None` when no such property exists (caller falls through to its /// `undefined` default). Mirrors `closure_get_own_dynamic_prop`. +/// +/// #6363: an own property installed by `Object.defineProperty(handle, k, {get})` +/// has no stored value — the getter must run instead. This is the single choke +/// point every handle read funnels through (perry-stdlib's +/// `js_handle_property_dispatch` consults it after every typed property misses), +/// so resolving the accessor here makes `handle.accessorProp` work on every read +/// path at once. pub fn handle_expando_get(handle: i64, name: &str) -> Option { + if handle == 0 { + return None; + } + if let Some(acc) = handle_expando_accessor(handle, name) { + if acc.get == 0 { + // Setter-only accessor: reads yield `undefined`, they do NOT fall + // through to a stale data value. + return Some(f64::from_bits(crate::value::TAG_UNDEFINED)); + } + let closure = + (acc.get & crate::value::POINTER_MASK) as *const crate::closure::ClosureHeader; + if closure.is_null() { + return Some(f64::from_bits(crate::value::TAG_UNDEFINED)); + } + return Some(crate::closure::js_closure_call0(closure)); + } + handle_expando_data_get(handle, name) +} + +/// The stored DATA value for `(handle, name)`, ignoring any accessor. Used by +/// `getOwnPropertyDescriptor` (which must report the descriptor without running +/// the getter) and by the accessor-aware [`handle_expando_get`] above. +pub(crate) fn handle_expando_data_get(handle: i64, name: &str) -> Option { if handle == 0 { return None; } @@ -68,13 +121,103 @@ pub fn handle_expando_get(handle: i64, name: &str) -> Option { .with(|cell| { cell.borrow() .get(&handle) - .and_then(|p| p.get(name).copied()) + .and_then(|p| p.iter().find(|(k, _)| k == name).map(|(_, v)| *v)) }) .map(f64::from_bits) } +/// The accessor pair installed on `(handle, name)` by a `defineProperty` +/// accessor descriptor, if any. +pub(crate) fn handle_expando_accessor( + handle: i64, + name: &str, +) -> Option { + if handle == 0 { + return None; + } + get_accessor_descriptor(handle as usize, name) +} + +/// The attributes of the own expando `(handle, name)`. A plain +/// `handle.foo = v` write records no entry, so it defaults — like any ordinary +/// JS assignment — to `{writable, enumerable, configurable}: true`. +pub(crate) fn handle_expando_attrs(handle: i64, name: &str) -> PropertyAttrs { + get_property_attrs(handle as usize, name).unwrap_or(PropertyAttrs::new(true, true, true)) +} + +/// True when `name` is an own expando property of `handle` (data OR accessor). +pub(crate) fn handle_expando_has(handle: i64, name: &str) -> bool { + if handle == 0 { + return false; + } + if handle_expando_accessor(handle, name).is_some() { + return true; + } + HANDLE_EXPANDO_PROPS.with(|cell| { + cell.borrow() + .get(&handle) + .map(|p| p.iter().any(|(k, _)| k == name)) + .unwrap_or(false) + }) +} + +/// Own expando property names of `handle`, in insertion order. When +/// `enumerable_only`, non-enumerable entries (a `defineProperty` default) are +/// filtered out — that is the `Object.keys` / `for-in` / spread surface; +/// `Object.getOwnPropertyNames` passes `false`. +pub(crate) fn handle_expando_own_keys(handle: i64, enumerable_only: bool) -> Vec { + if handle == 0 { + return Vec::new(); + } + let mut keys: Vec = HANDLE_EXPANDO_PROPS.with(|cell| { + cell.borrow() + .get(&handle) + .map(|p| p.iter().map(|(k, _)| k.clone()).collect()) + .unwrap_or_default() + }); + // A pure accessor define stores no data slot, so pick those up from the + // accessor table (appended after the data keys — close enough to insertion + // order for the mixed case, and exact for the common all-data one). + for k in super::descriptor_state::accessor_descriptor_keys_for_obj(handle as usize) { + if !keys.contains(&k) { + keys.push(k); + } + } + if enumerable_only { + keys.retain(|k| handle_expando_attrs(handle, k).enumerable()); + } + keys +} + +/// Remove the own expando `(handle, name)` and its descriptor state. Returns +/// `false` when the property exists but is non-configurable (`[[Delete]]` +/// rejects it), `true` otherwise — the same contract as an ordinary object's +/// `[[Delete]]`, so `delete handle.absent` still reports `true`. +pub(crate) fn handle_expando_delete(handle: i64, name: &str) -> bool { + if handle == 0 { + return true; + } + if !handle_expando_has(handle, name) { + return true; + } + if !handle_expando_attrs(handle, name).configurable() { + return false; + } + HANDLE_EXPANDO_PROPS.with(|cell| { + if let Some(props) = cell.borrow_mut().get_mut(&handle) { + props.retain(|(k, _)| k != name); + } + }); + PROPERTY_DESCRIPTORS.with(|m| { + m.borrow_mut().remove(&(handle as usize, name.to_string())); + }); + ACCESSOR_DESCRIPTORS.with(|m| { + m.borrow_mut().remove(&(handle as usize, name.to_string())); + }); + true +} + /// True when the handle has at least one user-assigned expando property. -/// (`Object.keys` / `in` support can build on this later.) #[allow(dead_code)] pub fn handle_expando_has_any(handle: i64) -> bool { if handle == 0 { @@ -105,7 +248,7 @@ pub fn scan_handle_expando_roots_mut(visitor: &mut crate::gc::RuntimeRootVisitor else { continue; }; - for bits in props.values_mut() { + for (_, bits) in props.iter_mut() { let mut v = f64::from_bits(*bits); visitor.visit_nanbox_f64_slot(&mut v); *bits = v.to_bits(); @@ -115,11 +258,24 @@ pub fn scan_handle_expando_roots_mut(visitor: &mut crate::gc::RuntimeRootVisitor std::collections::hash_map::Entry::Occupied(mut e) => { // A re-entrant set added/updated entries while we held no // borrow; those newer writes must win. Only restore scanned - // keys that were not concurrently re-written. + // keys that were not concurrently re-written, and keep the + // scanned (older) keys FIRST so insertion order survives. let dst = e.get_mut(); - for (k, v) in props { - dst.entry(k).or_insert(v); + for (k, v) in props.iter_mut() { + if let Some(newer) = dst.iter().find(|(nk, _)| nk == k) { + *v = newer.1; + } } + for (k, v) in dst.iter() { + if !props.iter().any(|(pk, _)| pk == k) { + props.push((k.clone(), *v)); + } + } + // GC_STORE_AUDIT(ROOT): HANDLE_EXPANDO_PROPS entries are scanned by + // scan_handle_expando_roots_mut (this function) — the merged vec holds + // values this pass just traced/rewrote, plus any re-entrant write that + // the mutator already barriered on its own way in. + *dst = props; } std::collections::hash_map::Entry::Vacant(e) => { e.insert(props); @@ -169,4 +325,55 @@ mod tests { cell.borrow_mut().remove(&h); }); } + + /// #6363: own keys come back in INSERTION order (`Object.keys(handle)` / + /// `{...handle}` are ordered in JS), and a re-set of an existing key must + /// update in place rather than move it to the back. + #[test] + fn own_keys_preserve_insertion_order() { + let h = 0x4_2426i64; + for name in ["b", "a", "c"] { + handle_expando_set(h, name, f64::from_bits(crate::value::TAG_TRUE)); + } + handle_expando_set(h, "b", f64::from_bits(crate::value::TAG_FALSE)); + assert_eq!(handle_expando_own_keys(h, false), vec!["b", "a", "c"]); + HANDLE_EXPANDO_PROPS.with(|cell| { + cell.borrow_mut().remove(&h); + }); + } + + /// #6363: a `defineProperty` default descriptor is NON-enumerable, so it + /// stays out of the `Object.keys` surface but is still an own property — + /// and being non-configurable, `[[Delete]]` must reject it. + #[test] + fn non_enumerable_define_hides_from_keys_and_rejects_delete() { + let h = 0x4_2427i64; + handle_expando_set(h, "vis", f64::from_bits(crate::value::TAG_TRUE)); + handle_expando_set(h, "hid", f64::from_bits(crate::value::TAG_TRUE)); + super::super::descriptor_state::set_property_attrs( + h as usize, + "hid".to_string(), + PropertyAttrs::new(false, false, false), + ); + + assert!(handle_expando_has(h, "hid")); + assert_eq!(handle_expando_own_keys(h, false), vec!["vis", "hid"]); + assert_eq!(handle_expando_own_keys(h, true), vec!["vis"]); + + // Non-configurable → delete rejects, property survives. + assert!(!handle_expando_delete(h, "hid")); + assert!(handle_expando_has(h, "hid")); + // Absent key → delete reports success (Node: `delete x.__nope` is true). + assert!(handle_expando_delete(h, "__nope")); + // Plain-write default is fully configurable → delete removes it. + assert!(handle_expando_delete(h, "vis")); + assert!(!handle_expando_has(h, "vis")); + + HANDLE_EXPANDO_PROPS.with(|cell| { + cell.borrow_mut().remove(&h); + }); + PROPERTY_DESCRIPTORS.with(|m| { + m.borrow_mut().remove(&(h as usize, "hid".to_string())); + }); + } } diff --git a/crates/perry-runtime/src/object/object_ops/define_properties.rs b/crates/perry-runtime/src/object/object_ops/define_properties.rs index 0cb55ca9ecc..46febc514bc 100644 --- a/crates/perry-runtime/src/object/object_ops/define_properties.rs +++ b/crates/perry-runtime/src/object/object_ops/define_properties.rs @@ -15,8 +15,20 @@ use super::*; pub extern "C" fn js_object_define_properties(target: f64, descriptors: f64) -> f64 { // #2817: target must be an object (or class-ref). Node throws // `Object.defineProperties called on non-object` for primitives. + // + // #6363: a native HANDLE target (a pointer-tagged registry id — zlib stream, + // fetch Headers/Request/Response/Blob, crypto hash, …) is an ordinary + // extensible object in Node but is not a heap `ObjectHeader`, so it fails + // `value_is_object_like` and used to throw here. Let it through: the per-key + // `js_object_define_property` below recognises the handle band and routes + // each descriptor to the handle's own-property storage. let target_is_class_ref = super::super::class_ref_id(target).is_some(); - if !target_is_class_ref && !unsafe { value_is_object_like(target) } { + let target_is_handle = { + let jv = crate::value::JSValue::from_bits(target.to_bits()); + jv.is_pointer() + && crate::value::addr_class::is_small_handle(unsafe { jv.as_pointer::() } as usize) + }; + if !target_is_class_ref && !target_is_handle && !unsafe { value_is_object_like(target) } { throw_object_type_error(b"Object.defineProperties called on non-object"); } // #2817: the properties bag must be coercible to an object. Node throws diff --git a/crates/perry-runtime/src/object/object_ops/define_property.rs b/crates/perry-runtime/src/object/object_ops/define_property.rs index f2a91dfe6df..5776bfbe0c2 100644 --- a/crates/perry-runtime/src/object/object_ops/define_property.rs +++ b/crates/perry-runtime/src/object/object_ops/define_property.rs @@ -99,6 +99,193 @@ unsafe fn define_class_prototype_method(target_cid: u32, name: &str, value_bits: ); } +/// #6363: `[[DefineOwnProperty]]` for a native HANDLE receiver — a pointer-tagged +/// small registry id (zlib stream, fetch Request/Response/Headers/Blob, crypto +/// hash, …), not a heap `ObjectHeader`. +/// +/// Handles get their arbitrary own-property storage from the +/// `handle_expando` side table — the same one a plain `handle.foo = v` write +/// lands in (perry-stdlib's `js_handle_property_set_dispatch` falls back to it +/// once every typed setter has passed). This ROUTES the descriptor there rather +/// than merely tolerating the call: the value round-trips through `handle.key`, +/// the `writable`/`enumerable`/`configurable` bits and any `get`/`set` pair are +/// recorded in the ordinary descriptor side tables (keyed by the handle id), and +/// `getOwnPropertyDescriptor` / `Object.keys` / `delete` read them back. A +/// define that returned `true` and dropped the property would be the same silent +/// no-op the throw replaced. +/// +/// The caller has already established that `hid` is in the handle band and that +/// the receiver is not a Proxy (proxies are handle-band ids too, and are routed +/// to their `[[DefineOwnProperty]]` trap earlier). +unsafe fn define_property_on_handle( + obj_value: f64, + hid: i64, + key_value: f64, + descriptor_value: f64, +) -> f64 { + use crate::object::descriptor_state::{ + set_accessor_descriptor, set_property_attrs, AccessorDescriptor, + }; + use crate::object::handle_expando as hx; + + // A handle IS an object in Node, so the ordinary descriptor validation + // applies: the descriptor must be an object, data and accessor fields can't + // be mixed, and a present `get`/`set` must be callable. + if !value_is_object_like(descriptor_value) || crate::symbol::js_is_symbol(descriptor_value) != 0 + { + let desc = describe_value_for_type_error(descriptor_value); + throw_object_type_error_with_suffix("Property description must be an object: ", &desc); + } + validate_property_descriptor(descriptor_value); + + // A Symbol key goes to the symbol side table (`SYMBOL_PROPERTIES`), which is + // keyed by the NaN-box payload — a handle id works there unchanged, and it's + // the table `handle[sym]` reads back from. String-coercing the symbol would + // file the value under a `"Symbol(x)"` STRING name, unreachable by the + // symbol-keyed reader. (This is the Next.js `PATCHED_SET_HEADER` shape.) + if crate::symbol::js_is_symbol(key_value) != 0 { + let has_get = desc_has_field(descriptor_value, b"get"); + let has_set = desc_has_field(descriptor_value, b"set"); + if has_get || has_set { + let get_field = desc_read_field(descriptor_value, b"get"); + let set_field = desc_read_field(descriptor_value, b"set"); + let get_bits = if !has_get || get_field.is_undefined() { + 0 + } else { + crate::closure::clone_closure_rebind_this(get_field.bits(), obj_value) + }; + let set_bits = if !has_set || set_field.is_undefined() { + 0 + } else { + crate::closure::clone_closure_rebind_this(set_field.bits(), obj_value) + }; + crate::symbol::set_symbol_accessor_property(obj_value, key_value, get_bits, set_bits); + } else if desc_has_field(descriptor_value, b"value") { + let value_field = desc_read_field(descriptor_value, b"value"); + crate::symbol::js_object_set_symbol_property( + obj_value, + key_value, + f64::from_bits(value_field.bits()), + ); + } + let read_flag = |name: &[u8]| -> Option { + desc_has_field(descriptor_value, name).then(|| { + crate::value::js_is_truthy(f64::from_bits( + desc_read_field(descriptor_value, name).bits(), + )) != 0 + }) + }; + crate::symbol::set_symbol_property_attrs( + crate::symbol::obj_key_from_f64(obj_value), + crate::symbol::sym_key_from_f64(key_value), + PropertyAttrs::new( + read_flag(b"writable").unwrap_or(has_get || has_set), + read_flag(b"enumerable").unwrap_or(false), + read_flag(b"configurable").unwrap_or(false), + ), + ); + return obj_value; + } + + let Some(key) = super::super::metadata_key_to_string(key_value) else { + return obj_value; + }; + + // The property's CURRENT shape, captured before any mutation below. + let had_accessor = hx::handle_expando_accessor(hid, &key).is_some(); + let had_data = hx::handle_expando_data_get(hid, &key).is_some(); + // Spec retention (ValidateAndApplyPropertyDescriptor): redefining an + // EXISTING own property keeps the attributes the descriptor omits; a brand + // new one defaults them to `false`. + let existing: Option = + (had_accessor || had_data).then(|| hx::handle_expando_attrs(hid, &key)); + + let has_get = desc_has_field(descriptor_value, b"get"); + let has_set = desc_has_field(descriptor_value, b"set"); + let has_accessor = has_get || has_set; + let has_value = desc_has_field(descriptor_value, b"value"); + + if has_accessor { + // The descriptor literal's `get()`/`set()` shorthands were lowered with + // their reserved `this` slot pointing at the DESCRIPTOR object; rebind to + // the handle so the accessor sees the right receiver — same clone the + // ordinary object path does. + let get_field = desc_read_field(descriptor_value, b"get"); + let set_field = desc_read_field(descriptor_value, b"set"); + let get_bits = if !has_get || get_field.is_undefined() { + 0 + } else { + crate::closure::clone_closure_rebind_this(get_field.bits(), obj_value) + }; + let set_bits = if !has_set || set_field.is_undefined() { + 0 + } else { + crate::closure::clone_closure_rebind_this(set_field.bits(), obj_value) + }; + set_accessor_descriptor( + hid as usize, + key.clone(), + AccessorDescriptor { + get: get_bits, + set: set_bits, + }, + ); + } else { + // A data descriptor (`value`/`writable`) OR a generic one + // (`{ enumerable: true }` alone). Drop any accessor that used to occupy + // the key so the store can't fire a stale setter. + if had_accessor { + crate::object::descriptor_state::ACCESSOR_DESCRIPTORS.with(|m| { + m.borrow_mut().remove(&(hid as usize, key.clone())); + }); + } + // [[Value]] is the descriptor's when present; otherwise it defaults to + // `undefined` for a BRAND-NEW key or an accessor→data conversion (neither + // has a data value to retain). Only a generic redefine of an EXISTING data + // property keeps the current value. + // + // The `undefined` store matters beyond the value itself: it is what makes + // the key an own property at all. `Object.defineProperty(h, "g", { enumerable: + // true })` creates `g` in Node (`getOwnPropertyDescriptor` → `{value: undefined, + // writable: false, enumerable: true, configurable: false}`, `"g" in h` → true); + // recording only the attribute bits would leave every own-key probe reporting + // it absent. + let new_value = if has_value { + Some(f64::from_bits( + desc_read_field(descriptor_value, b"value").bits(), + )) + } else if had_accessor || !had_data { + Some(f64::from_bits(crate::value::TAG_UNDEFINED)) + } else { + None + }; + if let Some(v) = new_value { + hx::handle_expando_set(hid, &key, v); + } + } + + let read_flag = |name: &[u8]| -> Option { + desc_has_field(descriptor_value, name).then(|| { + crate::value::js_is_truthy(f64::from_bits( + desc_read_field(descriptor_value, name).bits(), + )) != 0 + }) + }; + set_property_attrs( + hid as usize, + key, + PropertyAttrs::new( + read_flag(b"writable") + .unwrap_or_else(|| existing.map(|a| a.writable()).unwrap_or(has_accessor)), + read_flag(b"enumerable") + .unwrap_or_else(|| existing.map(|a| a.enumerable()).unwrap_or(false)), + read_flag(b"configurable") + .unwrap_or_else(|| existing.map(|a| a.configurable()).unwrap_or(false)), + ), + ); + obj_value +} + /// Object.defineProperty(obj, key, descriptor) — set the value AND record the /// `writable` / `enumerable` / `configurable` attribute flags in the side table. /// Returns the object (NaN-boxed pointer). @@ -171,55 +358,36 @@ pub extern "C" fn js_object_define_property( // 4. Present `get`/`set` must be callable. let target_is_class_ref = super::super::class_ref_id(obj_value).is_some(); if !target_is_class_ref && !value_is_object_like(obj_value) { - // A native HANDLE target (a small pointer-tagged id — e.g. an http - // ServerResponse, Headers, a timer) is not a heap object, so Perry - // can't attach an arbitrary own property to it the way V8 can. Node - // framework code nonetheless calls `Object.defineProperty(handle, …)`: - // Next.js `patchSetHeaderWithCookieSupport` marks `res` with a Symbol - // (`Object.defineProperty(res, PATCHED_SET_HEADER, { value: true })`). - // Throwing here aborts the whole request (HTTP 500). Instead treat the - // define as a best-effort success: for a string key with a data - // descriptor, route the value through the handle property-set so - // `res[key]` round-trips; symbol keys / accessor descriptors degrade - // to a no-op (the framework's patch is idempotent, so re-running is - // harmless). Matches how `js_object_set_field_by_name` already tolerates - // small-handle receivers. + // A native HANDLE target (a pointer-tagged registry id — a zlib + // stream, a fetch Request/Response/Headers/Blob, a crypto hash, an + // http ServerResponse, a timer) is not a heap `ObjectHeader`, so it + // fails `value_is_object_like`. In Node these are ORDINARY, + // extensible objects and `Object.defineProperty(handle, …)` is + // everyday code (Next.js `patchSetHeaderWithCookieSupport` marks + // `res` with a Symbol; libraries add non-enumerable metadata all the + // time). Route the define to the handle's own-property storage + // instead of throwing — see `define_property_on_handle`. + // + // #6363: the band test here was a hand-typed `p < 0x10000` — one zero + // short of `HANDLE_BAND_MAX` (0x100000), so only the LOW common + // registry (crypto, timers, sockets) was recognised. The fetch band + // (0x40000..0xE0000) and the zlib band (0xE0000..0xF0000) fell past it + // and hit the `throw` below: `Object.defineProperty(gzipStream, …)` / + // `(headers, …)` raised a bogus TypeError. Use the centralized + // predicate — the same correction `js_object_set_field_by_name` and + // `js_delete_property` already carry. let jv = crate::value::JSValue::from_bits(obj_value.to_bits()); - let handle_id = if jv.is_pointer() { - let p = jv.as_pointer::() as usize; - if p >= 1 && p < 0x10000 { - Some(p) - } else { - None - } - } else { - None - }; + let handle_id = jv + .is_pointer() + .then(|| jv.as_pointer::() as usize) + .filter(|p| crate::value::addr_class::is_small_handle(*p)); if let Some(hid) = handle_id { - // Best-effort: store a string-keyed data-descriptor value on the - // handle via the same dispatch `obj.key = value` uses. - let ks = crate::value::js_get_string_pointer_unified(key_value) - as *const crate::StringHeader; - if !ks.is_null() { - if let Some(dispatch) = - super::super::class_handles::handle_property_set_dispatch() - { - let dval = if desc_has_field(descriptor_value, b"value") { - Some(f64::from_bits( - desc_read_field(descriptor_value, b"value").bits(), - )) - } else { - None - }; - if let Some(v) = dval { - let name_ptr = - (ks as *const u8).add(std::mem::size_of::()); - let name_len = (*ks).byte_len as usize; - dispatch(hid as i64, name_ptr, name_len, v); - } - } - } - return obj_value; + return define_property_on_handle( + obj_value, + hid as i64, + key_value, + descriptor_value, + ); } throw_object_type_error(b"Object.defineProperty called on non-object"); } diff --git a/crates/perry-runtime/src/object/object_ops/has_own.rs b/crates/perry-runtime/src/object/object_ops/has_own.rs index 53c3a0ae269..a95e829f083 100644 --- a/crates/perry-runtime/src/object/object_ops/has_own.rs +++ b/crates/perry-runtime/src/object/object_ops/has_own.rs @@ -74,16 +74,29 @@ pub extern "C" fn js_object_has_own(obj_value: f64, key_value: f64) -> f64 { } // A POINTER_TAG registry handle (zlib stream, fetch Request/Response/ - // Headers/Blob, …) is not an address and must never be dereferenced. It - // carries no own properties, so report false. Proxies also live in the - // handle band but are served by the trap branch below (which runs before - // any deref), so leave their sub-band alone. + // Headers/Blob, …) is not an address and must never be dereferenced. Its + // TYPED surface is prototype accessors (not own properties), but a + // user-attached expando IS an own property (#6363) — `handle.foo = v` or + // `Object.defineProperty(handle, …)`. Consult the expando table rather + // than reporting a flat false. Proxies also live in the handle band but + // are served by the trap branch below (which runs before any deref), so + // leave their sub-band alone. if obj_js.is_pointer() { let addr = obj_js.as_pointer::() as usize; if crate::value::addr_class::is_handle_band(addr) && !crate::value::addr_class::is_proxy_id_band(addr) { - return f64::from_bits(TAG_FALSE); + let key_value = super::super::js_to_property_key(key_value); + if crate::symbol::js_is_symbol(key_value) != 0 { + let present = crate::symbol::js_object_has_own_symbol(obj_value, key_value); + return f64::from_bits(if present { TAG_TRUE } else { TAG_FALSE }); + } + let present = super::super::metadata_key_to_string(key_value) + .map(|name| { + super::super::handle_expando::handle_expando_has(addr as i64, &name) + }) + .unwrap_or(false); + return f64::from_bits(if present { TAG_TRUE } else { TAG_FALSE }); } }