Skip to content

Truly independent web browser

LibWeb: Lend the strings of String arguments to the bindings

Andreas Kling523b9b507f05
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
index 406dabaf6a9..a272a69ee25 100644
--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp
@@ -202,7 +202,7 @@ GC::Ref<ValidityState const> FormAssociatedElement::validity() const
}
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
-void FormAssociatedElement::set_custom_validity(Utf16String& error)
+void FormAssociatedElement::set_custom_validity(Utf16String error)
{
// The setCustomValidity(error) method steps are:
diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.h b/Libraries/LibWeb/HTML/FormAssociatedElement.h
index 6c30101bc45..d2c74594664 100644
--- a/Libraries/LibWeb/HTML/FormAssociatedElement.h
+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.h
@@ -132,7 +132,7 @@ public:
GC::Ref<ValidityState const> validity() const;
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
- void set_custom_validity(Utf16String& error);
+ void set_custom_validity(Utf16String error);
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#mutability
virtual bool is_mutable() const { return true; }
diff --git a/Libraries/LibWeb/WebIDL/AbstractOperations.cpp b/Libraries/LibWeb/WebIDL/AbstractOperations.cpp
index 220a466126a..5136ccf8caf 100644
--- a/Libraries/LibWeb/WebIDL/AbstractOperations.cpp
+++ b/Libraries/LibWeb/WebIDL/AbstractOperations.cpp
@@ -288,6 +288,16 @@ JS::ThrowCompletionOr<Utf16String> to_utf16_usv_string(JS::VM& vm, JS::Value val
return TRY(value.to_utf16_string(vm)).to_well_formed();
}
+JS::ThrowCompletionOr<StringArgument> to_usv_string_argument(JS::VM& vm, JS::Value value)
+{
+ if (value.is_string()) {
+ auto const& string = value.as_string().utf16_string();
+ if (string.utf16_view().validate())
+ return StringArgument::borrowed(string);
+ }
+ return StringArgument::owned(TRY(to_utf16_usv_string(vm, value)));
+}
+
// https://webidl.spec.whatwg.org/#invoke-a-callback-function
// https://whatpr.org/webidl/1437.html#invoke-a-callback-function
template<typename ReturnSteps>
diff --git a/Libraries/LibWeb/WebIDL/AbstractOperations.h b/Libraries/LibWeb/WebIDL/AbstractOperations.h
index c0d26c3e011..0c583938a70 100644
--- a/Libraries/LibWeb/WebIDL/AbstractOperations.h
+++ b/Libraries/LibWeb/WebIDL/AbstractOperations.h
@@ -16,6 +16,7 @@
#include <LibJS/Forward.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/FunctionObject.h>
+#include <LibJS/Runtime/PrimitiveString.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/WebIDL/Buffers.h>
@@ -40,6 +41,37 @@ WEB_API JS::ThrowCompletionOr<Utf16String> to_utf16_string(JS::VM&, JS::Value);
JS::ThrowCompletionOr<Utf16String> to_utf16_usv_string(JS::VM&, JS::Value);
JS::ThrowCompletionOr<String> to_byte_string(JS::VM&, JS::Value);
+// The string that a JavaScript value converts to, for an operation or a setter that takes a string.
+// OPTIMIZATION: A String value lends the string it holds, which takes no reference to it. That string stays where it
+// is, unchanged, for as long as the value lives, and a call keeps its arguments alive until it returns.
+class StringArgument {
+public:
+ static StringArgument borrowed(Utf16String const& string) { return StringArgument { &string, {} }; }
+ static StringArgument borrowed(Utf16String const&&) = delete;
+ static StringArgument owned(Utf16String string) { return StringArgument { nullptr, move(string) }; }
+
+ Utf16String const& string() const { return m_borrowed ? *m_borrowed : m_owned; }
+
+private:
+ StringArgument(Utf16String const* borrowed, Utf16String owned)
+ : m_borrowed(borrowed)
+ , m_owned(move(owned))
+ {
+ }
+
+ Utf16String const* m_borrowed { nullptr };
+ Utf16String m_owned;
+};
+
+ALWAYS_INLINE JS::ThrowCompletionOr<StringArgument> to_string_argument(JS::VM& vm, JS::Value value)
+{
+ if (value.is_string())
+ return StringArgument::borrowed(value.as_string().utf16_string());
+ return StringArgument::owned(TRY(to_utf16_string(vm, value)));
+}
+
+JS::ThrowCompletionOr<StringArgument> to_usv_string_argument(JS::VM&, JS::Value);
+
template<typename T>
GC::Ref<JS::PrimitiveString> primitive_string_from_string(JS::VM& vm, T&& value)
{
diff --git a/Meta/Generators/libweb_bindings/arguments.py b/Meta/Generators/libweb_bindings/arguments.py
index 2c095ddd3f5..46e868a0ed8 100644
--- a/Meta/Generators/libweb_bindings/arguments.py
+++ b/Meta/Generators/libweb_bindings/arguments.py
@@ -13,6 +13,7 @@ from Generators.libweb_bindings.cpp_types import cpp_value_type
from Generators.libweb_bindings.cpp_types import idl_identifier_cpp_name
from Generators.libweb_bindings.default_values import cpp_default_value_conversion
from Generators.libweb_bindings.includes import GeneratedIncludes
+from Generators.libweb_bindings.to_idl_value import string_argument_to_idl_value
from Generators.libweb_bindings.to_idl_value import to_idl_value
from Utils.webidl_parser import OperationParameter
@@ -72,6 +73,16 @@ def write_operation_parameter_conversions(
if (!{argument_value_name}.is_undefined())
{parameter_name} = TRY(WebIDL::throw_dom_exception_if_needed(vm, *vm.current_realm(), [&] {{ return {to_idl_value(parameter, argument_value_name, includes, context)}; }}));
+"""
+ )
+ continue
+
+ string_argument = string_argument_to_idl_value(parameter, argument_value_name, includes)
+ if string_argument is not None:
+ out.write(
+ f""" auto {argument_value_name}_string = {string_argument};
+ auto const& {parameter_name} = {argument_value_name}_string.string();
+
"""
)
continue
diff --git a/Meta/Generators/libweb_bindings/attributes.py b/Meta/Generators/libweb_bindings/attributes.py
index 9ab934513db..be532fc5179 100644
--- a/Meta/Generators/libweb_bindings/attributes.py
+++ b/Meta/Generators/libweb_bindings/attributes.py
@@ -24,6 +24,7 @@ from Generators.libweb_bindings.security_checks import on_the_window
from Generators.libweb_bindings.security_checks import perform_a_security_check
from Generators.libweb_bindings.security_checks import the_remote_window
from Generators.libweb_bindings.security_checks import window_member_is_cross_origin_accessible
+from Generators.libweb_bindings.to_idl_value import string_argument_to_idl_value
from Generators.libweb_bindings.to_idl_value import to_idl_value
from Generators.libweb_bindings.to_js_value import to_javascript_value
from Utils.webidl_parser import Attribute
@@ -909,6 +910,13 @@ def write_attribute_setter(
auto idl_value = maybe_idl_value.release_value();
+"""
+ )
+ elif (string_argument := string_argument_to_idl_value(attribute, "V", includes)) is not None:
+ out.write(
+ f""" auto V_string = {string_argument};
+ auto const& idl_value = V_string.string();
+
"""
)
else:
diff --git a/Meta/Generators/libweb_bindings/to_idl_value.py b/Meta/Generators/libweb_bindings/to_idl_value.py
index 9b3fc8241cf..e92d0fad06c 100644
--- a/Meta/Generators/libweb_bindings/to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/to_idl_value.py
@@ -1580,6 +1580,33 @@ def to_idl_value(
)
+def string_argument_to_idl_value(
+ member: DictionaryMemberOrAttribute,
+ value_name: str,
+ includes: GeneratedIncludes,
+) -> Optional[str]:
+ """The conversion of a value to a WebIDL::StringArgument, which lends the string of a String value rather than
+ taking a reference to it, or None where the member is not a plain string."""
+ extended_attributes = getattr(member, "extended_attributes", {})
+ if member.type.nullable or isinstance(member.type, (IDLParameterizedType, IDLUnionType)):
+ return None
+ if cpp_type_name_for_string(member.type.name, extended_attributes) != "Utf16String":
+ return None
+
+ if member.type.name in ("CSSOMString", "DOMString"):
+ conversion = f"WebIDL::to_string_argument(vm, {value_name})"
+ elif member.type.name == "USVString":
+ conversion = f"WebIDL::to_usv_string_argument(vm, {value_name})"
+ else:
+ return None
+
+ includes.add("LibJS/Runtime/Value.h")
+ includes.add("LibWeb/WebIDL/AbstractOperations.h")
+ if "LegacyNullToEmptyString" in extended_attributes:
+ return f"{value_name}.is_null() ? WebIDL::StringArgument::owned({{}}) : TRY({conversion})"
+ return f"TRY({conversion})"
+
+
def type_check_idl_value(
idl_type: IDLType,
value_name: str,
diff --git a/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt b/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt
new file mode 100644
index 00000000000..cfba9576ff5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebIDL/string-argument-outlives-collection-in-call.txt
@@ -0,0 +1,12 @@
+string-argument-concatenated-concatenated-1
+string-argument-sliced-from-a-longer-string-2
+short-3
+string-argument-converted-4
+string-argument-applied-applied
+collections during the calls: 5
+className: 42
+id: id-5
+well-formed-6=value-7&lone-surrogate-%EF%BF%BD-8=%EF%BF%BD-9
+color: red
+color after null: ""
+RangeError: thrown by toString
diff --git a/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html b/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html
new file mode 100644
index 00000000000..fbc1e3d6d5d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebIDL/string-argument-outlives-collection-in-call.html
@@ -0,0 +1,78 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // An operation reads the string of a String argument where the argument holds it. These calls run script that
+ // collects garbage while the operation still has to read a string that only its argument keeps alive.
+ test(() => {
+ let count = 0;
+ let collections = 0;
+ function collectingConstructor() {
+ return class extends HTMLElement {
+ // NB: define() reads observedAttributes only of a class with an attributeChangedCallback.
+ attributeChangedCallback() {}
+ static get observedAttributes() {
+ for (let i = 0; i < 1000; ++i)
+ "garbage-".repeat(3) + i;
+ internals.gc();
+ ++collections;
+ return [];
+ }
+ };
+ }
+ function suffix() {
+ return `-${++count}`;
+ }
+
+ const concatenated = collectingConstructor();
+ customElements.define("string-argument" + "-concatenated".repeat(2) + suffix(), concatenated);
+ println(customElements.getName(concatenated));
+
+ const sliced = collectingConstructor();
+ customElements.define(("not a name: string-argument-sliced-from-a-longer-string" + suffix()).substring(12), sliced);
+ println(customElements.getName(sliced));
+
+ const short = collectingConstructor();
+ customElements.define("short" + suffix(), short);
+ println(customElements.getName(short));
+
+ const converted = collectingConstructor();
+ customElements.define({ toString: () => "string-argument-converted" + suffix() }, converted);
+ println(customElements.getName(converted));
+
+ // The arguments of a call stay alive when its script drops the array they came from.
+ const applied = collectingConstructor();
+ const appliedArguments = ["string-argument" + "-applied".repeat(2)];
+ appliedArguments.push(class extends applied {
+ static get observedAttributes() {
+ appliedArguments.length = 0;
+ return super.observedAttributes;
+ }
+ });
+ const appliedConstructor = appliedArguments[1];
+ customElements.define.apply(customElements, appliedArguments);
+ println(customElements.getName(appliedConstructor));
+ println(`collections during the calls: ${collections}`);
+
+ const element = document.createElement("div");
+ element.className = 42;
+ println(`className: ${element.className}`);
+ element.id = "id" + suffix();
+ println(`id: ${element.id}`);
+
+ const parameters = new URLSearchParams();
+ parameters.append("well-formed" + suffix(), "value" + suffix());
+ parameters.append("lone-surrogate-\ud800" + suffix(), "\udc00" + suffix());
+ println(parameters.toString());
+
+ element.style.setProperty("color", "red");
+ println(`color: ${element.style.color}`);
+ element.style.setProperty("color", null);
+ println(`color after null: "${element.style.color}"`);
+
+ try {
+ element.id = { toString() { throw new RangeError("thrown by toString"); } };
+ } catch (error) {
+ println(`${error.name}: ${error.message}`);
+ }
+ });
+</script>