Truly independent web browser
LibWeb: Throw binding exceptions in the current realm
Shannon Booth2040a53e3785
diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.hindex 8a2906f8d33..d8aa8d6a4a7 100644--- a/Libraries/LibJS/Runtime/VM.h+++ b/Libraries/LibJS/Runtime/VM.h@@ -327,46 +327,6 @@ public:// Returns the base of the Reference Record, or null if the reference is unresolvable.ThrowCompletionOr<GC::Ptr<Environment>> resolve_binding(Utf16FlyString const&, Strict, GC::Ptr<Environment> = nullptr);- // Has the TypeErrors that are thrown at the execution context stack depth the scope was created at created in- // `realm`, until the scope is restored. Callees that push execution contexts are unaffected.- class TypeErrorRealmScope {- AK_MAKE_NONCOPYABLE(TypeErrorRealmScope);- AK_MAKE_NONMOVABLE(TypeErrorRealmScope);-- public:- TypeErrorRealmScope(VM& vm, Realm& realm)- : m_vm(vm)- , m_previous_realm(vm.engine_head_field<Realm*>(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_OFFSET))- , m_previous_depth(vm.engine_head_field<size_t>(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_DEPTH_OFFSET))- {- vm.set_engine_head_field<Realm*>(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_OFFSET, &realm);- vm.set_engine_head_field<size_t>(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_DEPTH_OFFSET, vm.execution_context_stack_length());- }-- ~TypeErrorRealmScope()- {- restore();- }-- void restore()- {- if (!m_active)- return;- m_vm.set_engine_head_field<Realm*>(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_OFFSET, m_previous_realm.ptr());- m_vm.set_engine_head_field<size_t>(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_DEPTH_OFFSET, m_previous_depth);- m_active = false;- }-- private:- static_assert(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_SIZE == sizeof(Realm*));- static_assert(JS_LAYOUT_VM_TYPE_ERROR_REALM_OVERRIDE_DEPTH_SIZE == sizeof(size_t));-- VM& m_vm;- GC::Ptr<Realm> m_previous_realm;- size_t m_previous_depth { 0 };- bool m_active { true };- };-// 5.2.3.2 Throw an Exception, https://tc39.es/ecma262/#sec-throw-an-exception// The runtime creates the errors of its own constructors, in the current realm or the realm of a TypeErrorRealmScope.template<typename T, typename... Args>diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rsindex d3a20c5bbe0..654c0478f94 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/mod.rs@@ -100,9 +100,7 @@ pub(crate) enum Exception {/// A simple exception with the message, which the bindings create in the current realm.TypeError(Utf16String),RangeError(Utf16String),- /// A DOMException with the name, one of https://webidl.spec.whatwg.org/#dfn-error-names-table, and the message,- /// which the bindings create in the realm of the call context, as the C++ bindings create the DOMExceptions of- /// the implementations they call.+ /// A DOMException with the name, one of https://webidl.spec.whatwg.org/#dfn-error-names-table, and the message.Dom(&'static str, Utf16String),}@@ -129,6 +127,12 @@ impl Exception {Self::Dom("SyntaxError", message)}+ /// https://webidl.spec.whatwg.org/#es-exceptions+ pub(crate) fn throw_in_current_realm(self, vm: &Vm) -> Throw {+ let realm = vm.current_realm().expect("a native function runs in a realm");+ self.throw(&CallContext::new(vm, realm))+ }+pub(crate) fn throw(self, cx: &CallContext) -> Throw {let vm = cx.vm();match self {diff --git a/Meta/Generators/libweb_bindings/REALM_POLICY.md b/Meta/Generators/libweb_bindings/REALM_POLICY.mdindex 5c90139fa76..f4ee37b8ae1 100644--- a/Meta/Generators/libweb_bindings/REALM_POLICY.md+++ b/Meta/Generators/libweb_bindings/REALM_POLICY.md@@ -4,9 +4,9 @@ Generated bindings make one explicit realm decision per IDL member.- Instance operations and attributes default to the validated receiver realm(`this_object_realm`). This realm is used for implementation calls,- DOMException wrapping, JavaScript return-value wrapping, and promise- creation for promise-typed members. A promise-typed member that throws- rejects in the caller/current realm, as WebIDL specifies.+ JavaScript return-value wrapping, and promise creation for promise-typed+ members. Exceptions, and the promises a promise-typed member rejects with+ them, are created in the caller/current realm, as WebIDL specifies.- Generated pair-iterable, async-iterable, maplike, and setlike helpers use thereceiver realm for iterator/container creation and wrapped values.- Static operations, constructors, and namespace members use the caller/current@@ -30,17 +30,6 @@ The shared generator entry point ismember code should use that helper instead of spelling ad-hoc realm policy inindividual emitters.-This deliberately deviates from WebIDL's default exception wording for-instance-member DOMException wrapping: LibWeb wraps DOMExceptions in the-receiver realm so wrapper allocation, exception identity, and return-value-allocation follow the same observable realm. Generated operation and setter-conversion blocks also scope ordinary JavaScript TypeError construction to the-selected member realm. The VM clears that TypeError override whenever-conversion re-enters author script, so nested script still throws in its own-realm. This is intentionally narrower than changing the VM's current realm or-execution context, so conversion failures get uniform realm identity without-running user script under a different realm.-Current `[NeedsCallerRealm]` opt-out categories:- WebAssembly JS API objects and namespace functions: JS-API algorithms creatediff --git a/Meta/Generators/libweb_bindings/arguments.py b/Meta/Generators/libweb_bindings/arguments.pyindex 357cdfadf10..2c095ddd3f5 100644--- a/Meta/Generators/libweb_bindings/arguments.py+++ b/Meta/Generators/libweb_bindings/arguments.py@@ -43,13 +43,12 @@ def write_operation_parameter_conversions(parameters: list[OperationParameter],includes: GeneratedIncludes,context: GenerationContext,- realm_argument: str = "*vm.current_realm()",) -> None:includes.add("LibWeb/WebIDL/ExceptionOrUtils.h")for index, parameter in enumerate(parameters):if parameter.variadic:- write_variadic_operation_parameter_conversion(out, parameter, index, includes, context, realm_argument)+ write_variadic_operation_parameter_conversion(out, parameter, index, includes, context)continueargument_value_name = f"arg{index}"@@ -61,7 +60,7 @@ def write_operation_parameter_conversions(out.write(f""" {operation_parameter_cpp_type(parameter, context)} {parameter_name} {{}};if (!{argument_value_name}.is_undefined())- {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));+ {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));""")@@ -71,14 +70,14 @@ def write_operation_parameter_conversions(out.write(f""" {cpp_value_type(parameter, context)} {parameter_name} = {cpp_default_value_conversion(parameter, context)};if (!{argument_value_name}.is_undefined())- {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));+ {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));""")continueout.write(- f""" auto {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));+ f""" auto {parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));""")@@ -90,7 +89,6 @@ def write_variadic_operation_parameter_conversion(index: int,includes: GeneratedIncludes,context: GenerationContext,- realm_argument: str,) -> None:cpp_type = cpp_type_for_idl_type_details(parameter.type,@@ -107,7 +105,7 @@ def write_variadic_operation_parameter_conversion(if (vm.argument_count() > {index}) {{{parameter_name}.ensure_capacity(vm.argument_count() - {index});for (size_t i = {index}; i < vm.argument_count(); ++i) {{- auto argument = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {to_idl_value(parameter, "vm.argument(i)", includes, context)}; }}));+ auto argument = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, "vm.argument(i)", includes, context)}; }}));{parameter_name}.unchecked_append(move(argument));}}}}diff --git a/Meta/Generators/libweb_bindings/attributes.py b/Meta/Generators/libweb_bindings/attributes.pyindex e31f5a767fe..c8c04243811 100644--- a/Meta/Generators/libweb_bindings/attributes.py+++ b/Meta/Generators/libweb_bindings/attributes.py@@ -366,7 +366,7 @@ def write_attribute_getter(getter_prelude = ""getter_cache_check = ""getter_realm_argument = member_realm_expr(attribute, interface=interface)- getter_steps = f"auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {getter_realm_argument}, [&] {{ return {implementation_attribute_getter_call(interface, attribute, getter_realm_argument)}; }}));"+ getter_steps = f"auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {implementation_attribute_getter_call(interface, attribute, getter_realm_argument)}; }}));"is_reflected = "Reflect" in attribute.extended_attributesis_non_nullable_reflected = is_reflected and not attribute.type.nullableis_non_nullable_reflected_string = is_non_nullable_reflected and is_dom_string_type(attribute)@@ -377,7 +377,7 @@ def write_attribute_getter(if "ImplementedInBindings" in attribute.extended_attributes:includes.add(bindings_glue_header_for_interface(interface))- getter_steps = f"auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {getter_realm_argument}, [&] {{ return {bindings_attribute_getter_call(attribute, getter_realm_argument)}; }}));"+ getter_steps = f"auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {bindings_attribute_getter_call(attribute, getter_realm_argument)}; }}));"elif is_reflected and attribute.type.name == "boolean":getter_steps = f"""{content_attribute_declaration}@@ -797,7 +797,7 @@ def write_attribute_setter(out.write(" [[maybe_unused]] auto& this_object_realm = js_value.as_object().shape().realm();\n\n")setter_realm_argument = member_realm_expr(attribute, interface=interface)- setter_steps = f"TRY(WebIDL::throw_dom_exception_if_needed(vm, {setter_realm_argument}, [&] {{ return {implementation_attribute_setter_call(context, interface, attribute, setter_realm_argument)}; }}));\n return {{}};"+ setter_steps = f"TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {implementation_attribute_setter_call(context, interface, attribute, setter_realm_argument)}; }}));\n return {{}};"is_reflected = "Reflect" in attribute.extended_attributesis_non_nullable_reflected = is_reflected and not attribute.type.nullableis_nullable_reflected_string = is_reflected and attribute.type.nullable and is_dom_string_type(attribute)@@ -827,7 +827,7 @@ def write_attribute_setter(return {{}};"""elif "ImplementedInBindings" in attribute.extended_attributes:includes.add(bindings_glue_header_for_interface(interface))- setter_steps = f"TRY(WebIDL::throw_dom_exception_if_needed(vm, {setter_realm_argument}, [&] {{ return {bindings_attribute_setter_call(context, attribute, setter_realm_argument)}; }}));\n return {{}};"+ setter_steps = f"TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {bindings_attribute_setter_call(context, attribute, setter_realm_argument)}; }}));\n return {{}};"elif is_non_nullable_reflected and attribute.type.name == "unsigned long":setter_steps = f"""{content_attribute_declaration}@@ -897,29 +897,22 @@ def write_attribute_setter(return {{}};"""out.write(""" auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {-"""- )- out.write(- f""" JS::VM::TypeErrorRealmScope conversion_type_error_realm {{ vm, {setter_realm_argument} }};-""")if context.enumeration(attribute.type) is not None:out.write(- f""" auto maybe_idl_value = WebIDL::throw_dom_exception_if_needed(vm, {setter_realm_argument}, [&] {{ return {to_idl_value(attribute, "V", includes, context)}; }});+ f""" auto maybe_idl_value = WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {to_idl_value(attribute, "V", includes, context)}; }});if (maybe_idl_value.is_error())return JS::js_undefined();auto idl_value = maybe_idl_value.release_value();- conversion_type_error_realm.restore();""")else:out.write(- f""" auto idl_value = TRY(WebIDL::throw_dom_exception_if_needed(vm, {setter_realm_argument}, [&] {{ return {to_idl_value(attribute, "V", includes, context)}; }}));- conversion_type_error_realm.restore();+ f""" auto idl_value = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {to_idl_value(attribute, "V", includes, context)}; }}));""")diff --git a/Meta/Generators/libweb_bindings/constructors.py b/Meta/Generators/libweb_bindings/constructors.pyindex 8611e1b42ac..b9441503ae6 100644--- a/Meta/Generators/libweb_bindings/constructors.py+++ b/Meta/Generators/libweb_bindings/constructors.py@@ -132,7 +132,7 @@ def write_constructor_steps(""")write_argument_count_check(out, interface.name, parameter_list_length(constructor.parameters))- write_operation_parameter_conversions(out, constructor.parameters, includes, context, "realm")+ write_operation_parameter_conversions(out, constructor.parameters, includes, context)arguments = ", ".join(idl_identifier_cpp_name(parameter) for parameter in constructor.parameters)arguments_with_leading_comma = f", {arguments}" if arguments else ""arguments_with_vm = f"vm{arguments_with_leading_comma}"diff --git a/Meta/Generators/libweb_bindings/iterables.py b/Meta/Generators/libweb_bindings/iterables.pyindex c8d283225f2..dd7495faee2 100644--- a/Meta/Generators/libweb_bindings/iterables.py+++ b/Meta/Generators/libweb_bindings/iterables.py@@ -195,7 +195,7 @@ def write_pair_iterable_declaration_functions([[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();// 4. Return a newly created default iterator object for definition, with jsValue as its target, "key+value" as its kind, and index set to 0.- return TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::KeyAndValue); }}));+ return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::KeyAndValue); }}));}}JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::keys)@@ -212,7 +212,7 @@ JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::keys)[[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();// 4. Return a newly created default iterator object for definition, with jsValue as its target, "key" as its kind, and index set to 0.- return TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::Key); }}));+ return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::Key); }}));}}JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::values)@@ -229,7 +229,7 @@ JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::values)[[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();// 4. Return a newly created default iterator object for definition, with jsValue as its target, "value" as its kind, and index set to 0.- return TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::Value); }}));+ return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {fully_qualified_name_for_interface(interface)}Iterator::create(this_object_realm, *this_impl, JS::Object::PropertyKind::Value); }}));}}JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::for_each)@@ -299,10 +299,11 @@ static JS::ThrowCompletionOr<{fully_qualified_name_for_interface(interface)}IterJS_DEFINE_NATIVE_FUNCTION({interface.name}IteratorPrototype::next){{+ auto& realm = *vm.current_realm();auto this_value = vm.this_value();auto* impl = TRY({make_name_acceptable_cpp(title_case_to_snake_case(iterator_interface_name))}_impl_from(vm));[[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();- return TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return impl->next(this_object_realm); }}));+ return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return impl->next(this_object_realm); }}));}}""")@@ -338,9 +339,7 @@ def write_async_iterable_declaration_functions(""")- write_operation_parameter_conversions(- out, interface.async_iterable.parameters, includes, context, "this_object_realm"- )+ write_operation_parameter_conversions(out, interface.async_iterable.parameters, includes, context)arguments = ", ".join(idl_identifier_cpp_name(parameter) for parameter in interface.async_iterable.parameters)if arguments:@@ -351,7 +350,7 @@ def write_async_iterable_declaration_functions(create_iterator = "Web::Bindings::values(this_object_realm, *impl"out.write(- f""" return TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return {create_iterator}{arguments}); }}));+ f""" return TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {create_iterator}{arguments}); }}));}}"""@@ -619,7 +618,7 @@ JS_DEFINE_NATIVE_FUNCTION({interface.prototype_class}::set){type_check_idl_value(interface.maplike.value_type, "value", includes, context, interface.name)}// 9. Set map[key] to value.- TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return Web::Bindings::set(this_object_realm, *this_impl, key, value); }}));+ TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return Web::Bindings::set(this_object_realm, *this_impl, key, value); }}));// 10. Return O.return vm.this_value();diff --git a/Meta/Generators/libweb_bindings/named_and_indexed_properties.py b/Meta/Generators/libweb_bindings/named_and_indexed_properties.pyindex afee34dad75..dccc78cc04e 100644--- a/Meta/Generators/libweb_bindings/named_and_indexed_properties.py+++ b/Meta/Generators/libweb_bindings/named_and_indexed_properties.py@@ -802,21 +802,17 @@ def write_indexed_property_getter([[maybe_unused]] auto& realm = *vm.current_realm();auto this_value = vm.this_value();[[maybe_unused]] auto* idl_object = TRY(impl_from(vm, this_value));- auto& this_object_realm = this_value.as_object().shape().realm();+ [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();if (vm.argument_count() < 1)return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "{operation.name}");- JS::VM::TypeErrorRealmScope conversion_type_error_realm {{ vm, {getter_realm_argument} }};-""")- write_operation_parameter_conversions(out, operation.parameters, includes, context, getter_realm_argument)+ write_operation_parameter_conversions(out, operation.parameters, includes, context)out.write(f"""- conversion_type_error_realm.restore();-- auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {getter_realm_argument}, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({parameter_name}); }}));+ auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({parameter_name}); }}));return {to_javascript_value(operation.return_type, "R", includes, context, getter_realm_argument)};}}@@ -850,21 +846,17 @@ def write_named_property_getter([[maybe_unused]] auto& realm = *vm.current_realm();auto this_value = vm.this_value();[[maybe_unused]] auto* idl_object = TRY(impl_from(vm, this_value));- auto& this_object_realm = this_value.as_object().shape().realm();+ [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();if (vm.argument_count() < 1)return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "{operation.name}");- JS::VM::TypeErrorRealmScope conversion_type_error_realm {{ vm, {getter_realm_argument} }};-""")- write_operation_parameter_conversions(out, operation.parameters, includes, context, getter_realm_argument)+ write_operation_parameter_conversions(out, operation.parameters, includes, context)out.write(f"""- conversion_type_error_realm.restore();-- auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {getter_realm_argument}, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({parameter_name}); }}));+ auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({parameter_name}); }}));return {to_javascript_value(operation.return_type, "R", includes, context, getter_realm_argument)};}}@@ -941,24 +933,14 @@ def write_named_property_operation(""")- out.write(- f""" JS::VM::TypeErrorRealmScope conversion_type_error_realm {{ vm, {operation_realm_argument} }};--"""- )- write_operation_parameter_conversions(out, operation.parameters, includes, context, operation_realm_argument)- out.write(- """ conversion_type_error_realm.restore();--"""- )+ write_operation_parameter_conversions(out, operation.parameters, includes, context)operation_returns_undefined = operation.return_type.name == "undefined"if "CEReactions" in operation.extended_attributes:ce_reactions_steps = wrap_with_ce_reactions(includes, "original_steps()", operation_realm_argument)out.write(f""" auto original_steps = [&] {{- return WebIDL::throw_dom_exception_if_needed(vm, {operation_realm_argument}, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({arguments}); }});+ return WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({arguments}); }});}};[[maybe_unused]] auto R = TRY({ce_reactions_steps});@@ -975,7 +957,7 @@ def write_named_property_operation(f"return {to_javascript_value(operation.return_type, 'R', includes, context, operation_realm_argument)};")out.write(- f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {operation_realm_argument}, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({arguments}); }}));+ f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return idl_object->{idl_implementation_cpp_name(operation)}({arguments}); }}));{return_statement}}}diff --git a/Meta/Generators/libweb_bindings/operations.py b/Meta/Generators/libweb_bindings/operations.pyindex edd1c4b9b47..2cc07adbc8d 100644--- a/Meta/Generators/libweb_bindings/operations.py+++ b/Meta/Generators/libweb_bindings/operations.py@@ -409,8 +409,8 @@ def write_stringifier()out.write(f""" auto* idl_object = TRY(impl_from(vm, this_value));- auto& this_object_realm = this_value.as_object().shape().realm();- auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return {stringifier_call}; }}));+ [[maybe_unused]] auto& this_object_realm = this_value.as_object().shape().realm();+ auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {stringifier_call}; }}));return {to_javascript_value(stringifier_type, "R", includes, context, "this_object_realm")};}}@@ -518,19 +518,7 @@ def write_operation(interface=interface,is_static=operation_invokes_as_static,)- if operation.parameters:- out.write(- f""" JS::VM::TypeErrorRealmScope conversion_type_error_realm {{ vm, {realm_argument} }};--"""- )- write_operation_parameter_conversions(out, operation.parameters, includes, context, realm_argument)- if operation.parameters:- out.write(- """ conversion_type_error_realm.restore();--"""- )+ write_operation_parameter_conversions(out, operation.parameters, includes, context)if operation_invokes_as_static:callee = fully_qualified_name_for_interface(interface)@@ -600,7 +588,7 @@ def write_operation(ce_reactions_steps = wrap_with_ce_reactions(includes, "original_steps()", realm_argument)out.write(f""" auto original_steps = [&] {{- return WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {operation_call}; }});+ return WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {operation_call}; }});}};[[maybe_unused]] auto R = TRY({ce_reactions_steps});@@ -625,7 +613,7 @@ def write_operation()out.write(f""" auto promise = WebIDL::create_promise({realm_argument});- TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {operation_call}; }}));+ TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {operation_call}; }}));return promise;}};@@ -645,7 +633,7 @@ def write_operation(returnif should_wrap_promise_rejections:out.write(- f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {operation_call}; }}));+ f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {operation_call}; }}));return R;}};@@ -669,7 +657,7 @@ def write_operation()out.write(f""" auto promise = WebIDL::create_promise({realm_argument});- TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {operation_call}; }}));+ TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {operation_call}; }}));return promise->promise();}}@@ -677,7 +665,7 @@ def write_operation()else:out.write(- f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {operation_call}; }}));+ f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {operation_call}; }}));return {to_javascript_value(operation.return_type, "R", includes, context, realm_argument)};}}@@ -685,7 +673,7 @@ def write_operation()returnout.write(- f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, {realm_argument}, [&] {{ return {operation_call}; }}));+ f""" [[maybe_unused]] auto R = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return {operation_call}; }}));return {to_javascript_value(operation.return_type, "R", includes, context, realm_argument)};}}@@ -701,7 +689,7 @@ def default_to_json_getter_steps(is_reflected = "Reflect" in attribute.extended_attributesif is_reflected and attribute.type.name == "boolean":return f'auto {value_name} = idl_object->has_attribute_ns({{}}, "{reflected_attribute_name(attribute)}"_utf16_fly_string);'- return f"auto {value_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, this_object_realm, [&] {{ return idl_object->{idl_implementation_cpp_name(attribute)}(); }}));"+ return f"auto {value_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] {{ return idl_object->{idl_implementation_cpp_name(attribute)}(); }}));"# https://webidl.spec.whatwg.org/#collect-attribute-valuesdiff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex dabfe77604c..4ceb149bbbf 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -1099,7 +1099,7 @@ def write_rust_async_iterator(out: TextIO, context: GenerationContext, interface// 6. Run the asynchronous iterator initialization steps for definition with jsValue, iterator, and idlArgs, if// any such steps exist.let state = Implementation::{async_iterator.method}(&implementation, &mut cx{arguments})- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;// 7. Return iterator.Ok(create_default_async_iterator::<Implementation>(&cx, state))@@ -1300,7 +1300,7 @@ def write_rust_interface(pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{let {receiver} = {this_check};{caller_realm_context} let result = {call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;{conversion}}}"""@@ -1573,7 +1573,7 @@ def write_rust_namespace(out: TextIO, context: GenerationContext, interface: Intfn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{let mut cx = CallContext::new(vm, vm.current_realm().expect("a native function runs in a realm"));let result = Implementation::{attribute.getter_method}(&mut cx)- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;{conversion}}}"""@@ -1824,11 +1824,9 @@ def write_rust_indexed_property_setter(let steps = || -> ThrowCompletionOr<Value> {{let implementation = implementation_of::<Implementation>(wrapper);let mut cx = CallContext::new(vm, realm);- let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());let value = {conversion}?;- drop(type_error_realm_scope);Implementation::{method}(&implementation, &mut cx, index, value)- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::UNDEFINED)}};RawNativeFunctionResult::from_completion(steps())@@ -1944,11 +1942,9 @@ def write_rust_named_properties(let implementation = implementation_of::<Implementation>(wrapper);let mut cx = CallContext::new(vm, realm);let steps = || -> ThrowCompletionOr<Value> {{- let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());let idl_value = {value_conversion}?;- drop(type_error_realm_scope);Implementation::{setter.method}(&implementation, &mut cx, name, idl_value)- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::UNDEFINED)}};RawNativeFunctionResult::from_completion(steps())@@ -1980,7 +1976,7 @@ def write_rust_named_properties(let mut cx = CallContext::new(vm, realm);let result = Implementation::{deleter.method}(&implementation, &mut cx, name).map(|()| Value::UNDEFINED)- .map_err(|exception| exception.throw(&cx));+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()));RawNativeFunctionResult::from_completion(result)}}"""@@ -1995,7 +1991,7 @@ def write_rust_stringifier(out: TextIO, function: str, method: str) -> None:fn {function}(vm: &Vm) -> ThrowCompletionOr<Value> {{let (implementation, mut cx) = this_implementation(vm)?;let result = Implementation::{method}(&implementation, &mut cx)- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;result.to_js(&cx)}}"""@@ -2023,14 +2019,14 @@ def write_rust_static_operation(steps.write(f""" let promise = crate::bindings::promise::create_promise(cx.vm(), cx.realm());{call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;{conversion}""")elif operation.return_type.name == "undefined" and not operation.return_type.nullable:steps.write(f""" {call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::UNDEFINED)""")@@ -2038,7 +2034,7 @@ def write_rust_static_operation(conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)steps.write(f""" let result = {call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;{conversion}""")@@ -2208,18 +2204,16 @@ def write_css_property_accessors(out: TextIO) -> None:fn property_getter(vm: &Vm, property: &crate::css::css_style_properties::CSSPropertyAccessor) -> ThrowCompletionOr<Value> {let (implementation, mut cx) = this_implementation(vm)?;let result = Implementation::property_value(&implementation, &mut cx, property)- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;result.to_js(&cx)}fn property_setter(vm: &Vm, property: &crate::css::css_style_properties::CSSPropertyAccessor) -> ThrowCompletionOr<Value> {let value = vm.argument(0);let (implementation, mut cx) = this_implementation(vm)?;- let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());let idl_value = to_dom_string_treating_null_as_empty(vm, value)?;- drop(type_error_realm_scope);with_custom_element_reactions(|| Implementation::set_property_value(&implementation, &mut cx, property, idl_value))- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::UNDEFINED)}"""@@ -2264,11 +2258,9 @@ def write_rust_attribute_setter(fn {attribute.setter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{let value = vm.argument(0);let {receiver} = this_implementation(vm)?;-{caller_realm_context} let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());- {conversion}- drop(type_error_realm_scope);+{caller_realm_context} {conversion}{call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::UNDEFINED)}}"""@@ -2312,10 +2304,7 @@ def write_rust_operation(else:steps.write(" let (implementation, mut cx) = this_implementation(vm)?;\n")write_argument_count_check(steps, name, overload.length)- if operation.parameters:- steps.write(" let type_error_realm_scope = vm.type_error_realm_scope(cx.realm());\n")- write_parameter_conversions(steps, what, operation.parameters, context)- steps.write(" drop(type_error_realm_scope);\n")+ write_parameter_conversions(steps, what, operation.parameters, context)arguments = "".join(f", {rust_local_name(parameter.name)}" for parameter in operation.parameters)returns_promise = is_promise_type(operation.return_type) and not operation.return_type.nullableif overload.implementation_parameters is not None:@@ -2337,7 +2326,7 @@ def write_rust_operation(steps.write(f""" let promise = crate::bindings::promise::create_promise(cx.vm(), cx.realm());{call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;{conversion}""")@@ -2345,7 +2334,7 @@ def write_rust_operation(# NB: An operation that returns nothing has no result to name, and the conversion of nothing is undefined.steps.write(f""" {call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::UNDEFINED)""")@@ -2353,7 +2342,7 @@ def write_rust_operation(conversion = rust_to_js_value(operation.return_type, "result", "&cx", context, what)steps.write(f""" let result = {call}- .map_err(|exception| exception.throw(&cx))?;+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;{conversion}""")@@ -2398,7 +2387,7 @@ def write_rust_constructor(out.write(f""" let mut cx = CallContext::new(vm, realm);let implementation =- Implementation::{constructor.method}(&mut cx{arguments}).map_err(|exception| exception.throw(&cx))?;+ Implementation::{constructor.method}(&mut cx{arguments}).map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;Ok(Value::from_object(construct_wrapper::<Implementation>(vm, realm, prototype, implementation)))}}"""diff --git a/Tests/LibWeb/Text/expected/DOM/cross-realm-member-exception-realm.txt b/Tests/LibWeb/Text/expected/DOM/cross-realm-member-exception-realm.txtnew file mode 100644index 00000000000..04568c5640d--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/cross-realm-member-exception-realm.txt@@ -0,0 +1,4 @@+setter DOMException: InvalidStateError in iframe realm+operation DOMException: NotFoundError in iframe realm+conversion TypeError: TypeError in iframe realm+enum conversion TypeError: TypeError in iframe realmdiff --git a/Tests/LibWeb/Text/expected/DOM/instance-member-conversion-receiver-realm.txt b/Tests/LibWeb/Text/expected/DOM/instance-member-conversion-receiver-realm.txtindex 9ef35159215..d50bda56b21 100644--- a/Tests/LibWeb/Text/expected/DOM/instance-member-conversion-receiver-realm.txt+++ b/Tests/LibWeb/Text/expected/DOM/instance-member-conversion-receiver-realm.txt@@ -1,6 +1,6 @@-operation TypeError is parent realm: true-operation TypeError is iframe realm: false-setter TypeError is parent realm: true-setter TypeError is iframe realm: false+operation TypeError is parent realm: false+operation TypeError is iframe realm: true+setter TypeError is parent realm: false+setter TypeError is iframe realm: truenested script TypeError is parent realm: truenested script TypeError is iframe realm: falsediff --git a/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-cross-realm.txt b/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-cross-realm.txtindex 17537bfd552..71b7777e37f 100644--- a/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-cross-realm.txt+++ b/Tests/LibWeb/Text/expected/XHR/XMLHttpRequest-cross-realm.txt@@ -1,5 +1,5 @@-invalid open error is iframe DOMException: true-invalid open error is top DOMException: false+invalid open error is iframe DOMException: false+invalid open error is top DOMException: trueresponse is iframe ArrayBuffer: trueresponse is top ArrayBuffer: falseresponse getter cache is stable: truediff --git a/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txt b/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txtindex aa226989b45..c8442443a2f 100644--- a/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txt+++ b/Tests/LibWeb/Text/expected/media-capabilities-decodingInfo-receiver-realm.txt@@ -1,5 +1,5 @@decodingInfo promise is iframe realm: truedecodingInfo promise is parent realm: false-decodingInfo rejection is iframe realm: false-decodingInfo rejection is parent realm: true+decodingInfo rejection is iframe realm: true+decodingInfo rejection is parent realm: falsedecodingInfo rejection message: Required property type is missing or undefineddiff --git a/Tests/LibWeb/Text/input/DOM/cross-realm-member-exception-realm.html b/Tests/LibWeb/Text/input/DOM/cross-realm-member-exception-realm.htmlnew file mode 100644index 00000000000..e93a598ce2a--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/cross-realm-member-exception-realm.html@@ -0,0 +1,29 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ const other = iframe.contentWindow;++ function thrown(f) {+ try {+ f();+ return "no exception";+ } catch (e) {+ const realm = e instanceof other.Object ? "iframe" : e instanceof Object ? "parent" : "neither";+ return `${e.name} in ${realm} realm`;+ }+ }++ const input = document.createElement("input");+ input.type = "checkbox";+ const valueAsNumberSetter = Object.getOwnPropertyDescriptor(other.HTMLInputElement.prototype, "valueAsNumber").set;+ println(`setter DOMException: ${thrown(() => valueAsNumberSetter.call(input, 1))}`);++ const div = document.createElement("div");+ println(`operation DOMException: ${thrown(() => other.Node.prototype.removeChild.call(div, document.createElement("span")))}`);+ println(`conversion TypeError: ${thrown(() => other.Node.prototype.appendChild.call(div, {}))}`);+ println(`enum conversion TypeError: ${thrown(() => other.Element.prototype.attachShadow.call(div, { mode: "bogus" }))}`);+ });+</script>