Skip to content

Truly independent web browser

LibJS+LibWeb: Read indexed properties of platform objects directly

Andreas Klinga51750d23a2c
diff --git a/Libraries/LibJS/HostClassBuilder.h b/Libraries/LibJS/HostClassBuilder.h
index 71c9544aec2..d93a2b8ecb6 100644
--- a/Libraries/LibJS/HostClassBuilder.h
+++ b/Libraries/LibJS/HostClassBuilder.h
@@ -395,6 +395,11 @@ struct HostObjectHookThunks {
{
Traits::finalize(host_object_from_abi(object));
}
+
+ static JSCompletion get_indexed_value(JSObject* object, u32 index)
+ {
+ return normal_completion_to_abi(value_to_abi(Traits::get_indexed_value(host_object_from_abi(object), index)));
+ }
};
template<typename Traits>
@@ -508,6 +513,8 @@ consteval JSHostObjectHooks make_host_object_hooks()
hooks.error_data = &Thunks::error_data;
if constexpr (requires { &Traits::finalize; })
hooks.finalize = &Thunks::finalize;
+ if constexpr (requires { &Traits::get_indexed_value; })
+ hooks.get_indexed_value = &Thunks::get_indexed_value;
return hooks;
}
diff --git a/Libraries/LibJS/HostObjectABI.h b/Libraries/LibJS/HostObjectABI.h
index 94aaa8d63f2..9632093c1a0 100644
--- a/Libraries/LibJS/HostObjectABI.h
+++ b/Libraries/LibJS/HostObjectABI.h
@@ -185,6 +185,10 @@ typedef struct JSHostObjectHooks {
void* (*error_data)(JSObject*);
// Runs during garbage collection and must not allocate.
void (*finalize)(JSObject*);
+ // Optional, and only for classes without a get hook. Answers [[Get]] of the array index `index` with the value of
+ // the own property there, if the hook can tell without running code; otherwise it returns the empty value, and
+ // [[Get]] goes on as it would without it.
+ JSCompletion (*get_indexed_value)(JSObject*, uint32_t index);
} JSHostObjectHooks;
// The [[Call]] and [[Construct]] behavior of kind JS_HOST_CLASS_FUNCTION, which the engine runs in the function's own
diff --git a/Libraries/LibJS/Rust/generate/layout_header.rs b/Libraries/LibJS/Rust/generate/layout_header.rs
index 43801666b03..1bed8d1dfbd 100644
--- a/Libraries/LibJS/Rust/generate/layout_header.rs
+++ b/Libraries/LibJS/Rust/generate/layout_header.rs
@@ -455,6 +455,7 @@ pub fn generate() -> LayoutHeader {
is_cacheable_for_inherited_property,
error_data,
finalize,
+ get_indexed_value,
});
check_host_object_abi_struct!(w, JSHostFunctionHooks { call, construct, finalize });
check_host_object_abi_struct!(w, JSHostArrayHooks { set, delete_property });
diff --git a/Libraries/LibJS/Rust/src/embedding/host/class_table.rs b/Libraries/LibJS/Rust/src/embedding/host/class_table.rs
index 92d3a593a13..dbdb5e74bc6 100644
--- a/Libraries/LibJS/Rust/src/embedding/host/class_table.rs
+++ b/Libraries/LibJS/Rust/src/embedding/host/class_table.rs
@@ -53,6 +53,7 @@ static HOST_OBJECT_HOOKS_THAT_ARE_ALL_ORDINARY: JSHostObjectHooks = JSHostObject
is_cacheable_for_inherited_property: None,
error_data: None,
finalize: None,
+ get_indexed_value: None,
};
static HOST_ARRAY_HOOKS_THAT_ARE_ALL_ORDINARY: JSHostArrayHooks = JSHostArrayHooks {
diff --git a/Libraries/LibJS/Rust/src/embedding/host/host_object.rs b/Libraries/LibJS/Rust/src/embedding/host/host_object.rs
index b26daab4bff..03e89111e0b 100644
--- a/Libraries/LibJS/Rust/src/embedding/host/host_object.rs
+++ b/Libraries/LibJS/Rust/src/embedding/host/host_object.rs
@@ -146,6 +146,7 @@ fn host_object_methods(table: &'static JSHostClass) -> ObjectMethods {
|| hooks.get_own_property.is_some()
|| hooks.has_property.is_some()
|| hooks.get.is_some()
+ || hooks.get_indexed_value.is_some()
|| hooks.own_property_keys.is_some();
if hooks_answer_instead_of_the_shape
|| table.has_flag(JS_HOST_CLASS_NOT_ELIGIBLE_FOR_OWN_PROPERTY_ENUMERATION_FAST_PATH)
@@ -155,6 +156,14 @@ fn host_object_methods(table: &'static JSHostClass) -> ObjectMethods {
if hooks.error_data.is_some() {
methods.error_data = error_data_through_hook;
}
+ if hooks.get_indexed_value.is_some() {
+ // NB: The hook answers [[Get]] of array indices itself, so a [[Get]] hook would not see them.
+ assert!(
+ hooks.get.is_none(),
+ "a host class has a get_indexed_value hook or a [[Get]] hook"
+ );
+ methods.internal_get = get_through_indexed_value_hook;
+ }
methods
}
@@ -295,6 +304,29 @@ fn has_property_through_hook(object: &Object, _vm: &Vm, key: &PropertyKey) -> Th
bool_completion_from_hook(unsafe { hook(lend_object_to_hook(object), lend_property_key_to_abi(key)) })
}
+/// [[Get]] of a class with a get_indexed_value hook: the hook's value for an array index it answers, and otherwise
+/// OrdinaryGet.
+fn get_through_indexed_value_hook(
+ object: &Object,
+ vm: &Vm,
+ key: &PropertyKey,
+ receiver: Value,
+ cacheable_metadata: Option<&mut CacheableGetPropertyMetadata>,
+ phase: PropertyLookupPhase,
+) -> ThrowCompletionOr<Value> {
+ if key.is_number() {
+ let hook = hooks_of(object)
+ .get_indexed_value
+ .expect("the class has a get_indexed_value hook");
+ // SAFETY: The hook takes an object of its class and an index.
+ let value = completion_from_abi(unsafe { hook(lend_object_to_hook(object), key.as_number()) })?;
+ if !value.is_empty() {
+ return Ok(value);
+ }
+ }
+ object.ordinary_get(vm, key, receiver, cacheable_metadata, phase)
+}
+
fn get_through_hook(
object: &Object,
_vm: &Vm,
diff --git a/Libraries/LibJS/Rust/src/layout/host_class.rs b/Libraries/LibJS/Rust/src/layout/host_class.rs
index 9f2f330d25f..840efd50e19 100644
--- a/Libraries/LibJS/Rust/src/layout/host_class.rs
+++ b/Libraries/LibJS/Rust/src/layout/host_class.rs
@@ -151,6 +151,7 @@ pub struct JSHostObjectHooks {
pub is_cacheable_for_inherited_property: Option<unsafe extern "C" fn(object: *mut JSObject) -> bool>,
pub error_data: Option<unsafe extern "C" fn(object: *mut JSObject) -> *mut c_void>,
pub finalize: Option<unsafe extern "C" fn(object: *mut JSObject)>,
+ pub get_indexed_value: Option<unsafe extern "C" fn(object: *mut JSObject, index: u32) -> JSCompletion>,
}
#[repr(C)]
diff --git a/Libraries/LibWeb/Bindings/PlatformObject.cpp b/Libraries/LibWeb/Bindings/PlatformObject.cpp
index 763c91cd59c..768d6059f45 100644
--- a/Libraries/LibWeb/Bindings/PlatformObject.cpp
+++ b/Libraries/LibWeb/Bindings/PlatformObject.cpp
@@ -678,12 +678,23 @@ JS::HostObject const& legacy_platform_object_from_abi(JSObject* wrapper)
return static_cast<JS::HostObject const&>(*JS::HostABI::object_from_abi(wrapper));
}
+struct IndexedLegacyPlatformObjectTraits : LegacyPlatformObjectTraits {
+ // OPTIMIZATION: [[Get]] of a supported property index returns the value of the indexed property getter, as the
+ // descriptor of LegacyPlatformObjectGetOwnProperty has it, so it is read without one.
+ static JS::Value get_indexed_value(JS::HostObject& wrapper, u32 index)
+ {
+ auto& realm = wrapper_realm(wrapper);
+ return item_value(wrapper, host_defined_wrapper_world(realm), realm, index).value_or(JS::js_special_empty_value());
+ }
+};
+
// The legacy [[GetOwnProperty]] and [[OwnPropertyKeys]] write their results straight into the engine's descriptor and
// key list, rather than returning them from traits functions for the hook thunks to copy, because indexed access to
// collections and their enumeration are hot.
+template<typename Traits>
consteval JSHostObjectHooks make_legacy_platform_object_hooks()
{
- auto hooks = JS::make_host_object_hooks<LegacyPlatformObjectTraits>();
+ auto hooks = JS::make_host_object_hooks<Traits>();
hooks.get_own_property = [](JSObject* wrapper, JSPropertyKey property_name, JSPropertyDescriptor* descriptor) {
return JS::HostABI::completion_to_abi(legacy_platform_object_internal_get_own_property(legacy_platform_object_from_abi(wrapper), JS::HostABI::property_key_from_abi(property_name), *descriptor));
};
@@ -698,6 +709,7 @@ consteval JSHostObjectHooks make_legacy_platform_object_hooks()
constexpr JSHostObjectHooks platform_object_hooks = JS::make_host_object_hooks<PlatformObjectTraits>();
constexpr JSHostObjectHooks global_platform_object_hooks = JS::make_host_object_hooks<GlobalPlatformObjectTraits>();
constexpr JSHostObjectHooks dom_exception_wrapper_hooks = JS::make_host_object_hooks<DOMExceptionWrapperTraits>();
-constexpr JSHostObjectHooks legacy_platform_object_hooks = make_legacy_platform_object_hooks();
+constexpr JSHostObjectHooks legacy_platform_object_hooks = make_legacy_platform_object_hooks<LegacyPlatformObjectTraits>();
+constexpr JSHostObjectHooks indexed_legacy_platform_object_hooks = make_legacy_platform_object_hooks<IndexedLegacyPlatformObjectTraits>();
}
diff --git a/Libraries/LibWeb/Bindings/PlatformObject.h b/Libraries/LibWeb/Bindings/PlatformObject.h
index b1717de59fb..11c8c76a0b4 100644
--- a/Libraries/LibWeb/Bindings/PlatformObject.h
+++ b/Libraries/LibWeb/Bindings/PlatformObject.h
@@ -90,13 +90,15 @@ template<typename Implementation>
// The internal methods of wrapper host classes. Wrappers of [Global] interfaces and of interfaces without special
// operations have the ordinary internal methods, but preserve the wrapper once script gives it state of its own: a new
// own property, another prototype or non-extensibility. A [Global] wrapper's prototype is immutable through its host
-// class flags instead. Legacy platform objects have the internal methods that WebIDL defines for them. A DOMException
-// wrapper is an ordinary wrapper that also exposes the error data of its implementation object.
+// class flags instead. Legacy platform objects have the internal methods that WebIDL defines for them, and those that
+// support indexed properties also read them for [[Get]] directly. A DOMException wrapper is an ordinary wrapper that
+// also exposes the error data of its implementation object.
//
// Outside LibWeb, their addresses are not constant expressions on Windows, where the tables are imported from a DLL.
extern WEB_API JSHostObjectHooks const platform_object_hooks;
extern WEB_API JSHostObjectHooks const global_platform_object_hooks;
extern WEB_API JSHostObjectHooks const legacy_platform_object_hooks;
+extern WEB_API JSHostObjectHooks const indexed_legacy_platform_object_hooks;
extern JSHostObjectHooks const dom_exception_wrapper_hooks;
// The finalize hook of every wrapper host class calls this to remove the wrapper from its world.
diff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.py
index 46cbb3a4f58..56a041e7be9 100644
--- a/Meta/Generators/libweb_bindings/rust_bindings.py
+++ b/Meta/Generators/libweb_bindings/rust_bindings.py
@@ -226,7 +226,7 @@ static constexpr LegacyPlatformObjectInfo {legacy_info} {{
// The wrappers are legacy platform objects, whose indexed properties the Rust bindings read: their implementation is a
// cell in their host data, not an implementation object in their wrappable slot.
constexpr JSHostClass {wrapper_host_class_symbol(interface)} = JS::make_host_class(JS_HOST_CLASS_OBJECT, "{interface.name}"sv,
- &{parent_host_class}, &legacy_platform_object_hooks, &{legacy_info},
+ &{parent_host_class}, &indexed_legacy_platform_object_hooks, &{legacy_info},
platform_object_host_class_flags | JS_HOST_CLASS_NOT_CACHEABLE_FOR_INDEXED_PROPERTY_ABSENCE);
"""
)
diff --git a/Meta/Generators/libweb_bindings/wrappers.py b/Meta/Generators/libweb_bindings/wrappers.py
index 134f5cc0658..a87b407016d 100644
--- a/Meta/Generators/libweb_bindings/wrappers.py
+++ b/Meta/Generators/libweb_bindings/wrappers.py
@@ -195,4 +195,6 @@ def wrapper_host_class_hooks(context: GenerationContext, interface: Interface) -
return "platform_object_hooks"
if "has_global_interface_extended_attribute" in legacy_platform_object_info_fields_of_wrapper:
return "global_platform_object_hooks"
+ if "supports_indexed_properties" in legacy_platform_object_info_fields_of_wrapper:
+ return "indexed_legacy_platform_object_hooks"
return "legacy_platform_object_hooks"
diff --git a/Tests/LibWeb/Text/expected/collection-indexed-get.txt b/Tests/LibWeb/Text/expected/collection-indexed-get.txt
new file mode 100644
index 00000000000..98eb425a60c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/collection-indexed-get.txt
@@ -0,0 +1,17 @@
+NodeList:
+ indices: #text, a, b, c, #text, SCRIPT, #text, SCRIPT, #text, out
+ [length]: undefined
+ [-1]: undefined
+ [100]: inherited
+ ["0"] is [0]: true
+ for-of: #text, a, b, c, #text, SCRIPT, #text, SCRIPT, #text, out
+ Reflect.get with a receiver: true
+HTMLCollection:
+ indices: a, b, c
+ [length]: undefined
+ [-1]: undefined
+ [100]: inherited
+ ["0"] is [0]: true
+ for-of: a, b, c
+ Reflect.get with a receiver: true
+after a removal: 2 b undefined
diff --git a/Tests/LibWeb/Text/input/collection-indexed-get.html b/Tests/LibWeb/Text/input/collection-indexed-get.html
new file mode 100644
index 00000000000..68a80688b30
--- /dev/null
+++ b/Tests/LibWeb/Text/input/collection-indexed-get.html
@@ -0,0 +1,32 @@
+<!doctype html>
+<body>
+ <span id="a"></span><span id="b"></span><span id="c"></span>
+</body>
+<script src="include.js"></script>
+<script>
+ test(() => {
+ const collections = [
+ ["NodeList", document.body.childNodes],
+ ["HTMLCollection", document.getElementsByTagName("span")],
+ ];
+ Object.prototype[100] = "inherited";
+ for (const [name, collection] of collections) {
+ println(`${name}:`);
+ const ids = [];
+ for (let i = 0; i < collection.length; ++i) ids.push(collection[i].id || collection[i].nodeName);
+ println(` indices: ${ids.join(", ")}`);
+ println(` [length]: ${collection[collection.length]}`);
+ println(` [-1]: ${collection[-1]}`);
+ println(` [100]: ${collection[100]}`);
+ println(` ["0"] is [0]: ${collection["0"] === collection[0]}`);
+ println(` for-of: ${Array.from(collection, node => node.id || node.nodeName).join(", ")}`);
+ println(` Reflect.get with a receiver: ${Reflect.get(collection, 0, {}) === collection[0]}`);
+ }
+ delete Object.prototype[100];
+
+ const spans = document.getElementsByTagName("span");
+ const first = spans[0];
+ first.remove();
+ println(`after a removal: ${spans.length} ${spans[0].id} ${spans[2]}`);
+ });
+</script>