Truly independent web browser
Everywhere: Trace the captures of every GC::Function precisely
Andreas Klinga3e1fb6cbda8
diff --git a/Libraries/LibAudio/AudioDevices.h b/Libraries/LibAudio/AudioDevices.hindex 327ee2c3e9c..cd68bd38b05 100644--- a/Libraries/LibAudio/AudioDevices.h+++ b/Libraries/LibAudio/AudioDevices.h@@ -13,6 +13,7 @@#include <AK/Vector.h>#include <AK/kmalloc.h>#include <LibAudio/Export.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>namespace Audio {@@ -78,3 +79,5 @@ template<>AUDIO_API ErrorOr<Audio::AudioDeviceInfo> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Audio::AudioDeviceInfo);diff --git a/Libraries/LibGC/Function.h b/Libraries/LibGC/Function.hindex 047b6caeb53..204c5045c1a 100644--- a/Libraries/LibGC/Function.h+++ b/Libraries/LibGC/Function.h@@ -7,18 +7,14 @@#pragma once-#include <AK/Array.h>#include <AK/Function.h>-#include <AK/Optional.h>#include <AK/ScopeGuard.h>#include <AK/StdLibExtras.h>-#include <AK/Variant.h>#include <LibGC/CaptureTraits.h>#include <LibGC/Cell.h>#include <LibGC/FunctionTable.h>#include <LibGC/Heap.h>#include <LibGC/Member.h>-#include <LibGC/NanBoxedValue.h>#include <LibGC/Ptr.h>#include <typeinfo>@@ -287,18 +283,6 @@ class Function<R(Args...)> final : public Cell {public:using Operations = FunctionOperationsFor<R, Args...>;- using Lambda = AK::Function<R(Args...)>;-- static Ref<Function> create(Heap& heap, ESCAPING AK::Function<R(Args...)>&& function)- {- // NB: The function is allocated before its box, so a collection that the allocation runs still finds the- // captures where the caller holds them.- auto cell = heap.allocate<Function>();- auto allocation = heap.function_table().allocate(lambda_operations, sizeof(Lambda));- new (allocation.box) Lambda(move(function));- cell->m_handle = allocation.handle;- return cell;- }template<typename Callable, typename... Values>static Ref<Function> create(Heap& heap, CaptureList<Values...>&& captures, Callable&&)@@ -357,18 +341,6 @@ private:slot.operations->visit_edges(slot.box, visitor);}- // A function made from an AK::Function, whose captures are opaque and visited as possible cell pointers.- static constexpr Operations lambda_operations {- {- .signature = &Detail::function_signature<R(Args...)>,- .visit_edges = [](void* box, Visitor& visitor) { visitor.visit_possible_values(static_cast<Lambda*>(box)->raw_capture_range()); },- .destroy = [](void* box) { static_cast<Lambda*>(box)->~Lambda(); },- },- [](void* box, Args... args) -> R {- return (*static_cast<Lambda*>(box))(forward<Args>(args)...);- },- };-template<typename Callback, typename Box>struct CaptureOperations {static constexpr Operations operations {@@ -398,7 +370,7 @@ private:// NB: No template argument can be given for the leading pack, so a function type given explicitly selects the overload// below instead of being taken as the type of the first capture.template<int&... ExplicitArgumentBarrier, typename... Values, typename Callable, typename T = typename Detail::DropParameters<sizeof...(Values), typename Detail::CallableTypeWithCaptures<RemoveCVReference<Callable>, typename Detail::CaptureStorage<Values>::Type...>::Type>::Type>-static Ref<Function<T>> create_function(Heap& heap, CaptureList<Values...>&& captures, ESCAPING Callable&& callable)+static Ref<Function<T>> create_function(Heap& heap, CaptureList<Values...>&& captures, Callable&& callable){return Function<T>::create(heap, move(captures), forward<Callable>(callable));}@@ -406,19 +378,17 @@ static Ref<Function<T>> create_function(Heap& heap, CaptureList<Values...>&& cap// The same, for a callable whose type does not name the function type, such as one that takes its own parameters as auto.template<typename T, typename... Values, typename Callable>requires(IsFunction<T>)-static Ref<Function<T>> create_function(Heap& heap, CaptureList<Values...>&& captures, ESCAPING Callable&& callable)+static Ref<Function<T>> create_function(Heap& heap, CaptureList<Values...>&& captures, Callable&& callable){return Function<T>::create(heap, move(captures), forward<Callable>(callable));}+// Makes a function of a callable that captures nothing.template<typename Callable, typename T = EquivalentFunctionType<RemoveCVReference<Callable>>>-static Ref<Function<T>> create_function(Heap& heap, ESCAPING Callable&& function)+static Ref<Function<T>> create_function(Heap& heap, Callable&& function){- // NB: A callable that captures nothing needs no AK::Function, and has nothing to visit.- if constexpr (Detail::CapturesNothing<RemoveCVReference<Callable>>)- return Function<T>::create(heap, CaptureList<> {}, forward<Callable>(function));- else- return Function<T>::create(heap, AK::Function<T> { forward<Callable>(function) });+ static_assert(Detail::CapturesNothing<RemoveCVReference<Callable>>, "A GC::Function callable captures nothing; name what it uses with GC::captures() and take it as parameters");+ return Function<T>::create(heap, CaptureList<> {}, forward<Callable>(function));}template<typename R, typename... Args>diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 09f5ae3fa5d..2cde932924a 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -559,9 +559,9 @@ static void add_possible_value(PossiblePointers& possible_pointers, FlatPtr datapossible_pointers.pointers.set(possible_pointer, move(origin));}-// Adds the possible values in the captures of a GC::Function. Its captures start 8-byte aligned, but may end with a-// lone compressed cell pointer, as a capture of nothing but one member does. That one is no half of a whole word, so it-// is added on its own. A member elsewhere in the captures is either half of one of the whole words.+// Adds the possible values in the captures of an AK::Function that a cell visits. Its captures start 8-byte aligned, but+// may end with a lone compressed cell pointer, as a capture of nothing but one member does. That one is no half of a+// whole word, so it is added on its own. A member elsewhere in the captures is either half of one of the whole words.static void add_possible_captured_values(PossiblePointers& possible_pointers, ReadonlyBytes bytes, PossiblePointerBounds const& bounds){HeapRoot const origin { .type = HeapRoot::Type::HeapFunctionCapturedPointer };diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex 030cfdeb037..67415e883a3 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -92,7 +92,7 @@ public:NEVER_INLINE AK::JsonObject dump_graph();// How a cell on a retaining path reaches the next one: through a field it visits, or through a word a conservative- // scan of its contents (a GC::Function's captures, for example) took for a pointer, whole or as either 32-bit half.+ // scan of its contents (the captures of an AK::Function, for example) took for a pointer, whole or as either 32-bit half.enum class RetainingEdgeKind : u8 {Precise,ConservativeWord,diff --git a/Libraries/LibGfx/DecodedImageFrame.h b/Libraries/LibGfx/DecodedImageFrame.hindex 102df1dc027..6e48b04799d 100644--- a/Libraries/LibGfx/DecodedImageFrame.h+++ b/Libraries/LibGfx/DecodedImageFrame.h@@ -10,6 +10,7 @@#include <AK/Atomic.h>#include <AK/NonnullRefPtr.h>#include <AK/kmalloc.h>+#include <LibGC/Forward.h>#include <LibGfx/Bitmap.h>#include <LibGfx/ColorSpace.h>#include <LibGfx/Forward.h>@@ -89,3 +90,5 @@ template<>ErrorOr<Gfx::DecodedImageFrame> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Gfx::DecodedImageFrame);diff --git a/Libraries/LibJS/Debugger.cpp b/Libraries/LibJS/Debugger.cppindex fc3e864d6e5..37f35a6d5cf 100644--- a/Libraries/LibJS/Debugger.cpp+++ b/Libraries/LibJS/Debugger.cpp@@ -106,14 +106,13 @@ static void call_pause_callback(void* context, JSVM*, JSDebuggerPauseInfo const*pause_callback.function()(pause_info_from_abi(*pause_info));}-void Debugger::set_pause_callback(Function<void(PauseInfo const&)> callback)+void Debugger::set_pause_callback(GC::Ptr<PauseCallback> callback){if (!callback) {js_debugger_set_pause_callback(vm_to_abi(vm()), nullptr, nullptr);return;}- auto pause_callback = PauseCallback::create(vm().heap(), move(callback));- js_debugger_set_pause_callback(vm_to_abi(vm()), call_pause_callback, static_cast<GC::Cell*>(pause_callback.ptr()));+ js_debugger_set_pause_callback(vm_to_abi(vm()), call_pause_callback, static_cast<GC::Cell*>(callback.ptr()));}void Debugger::continue_execution(ResumeMode resume_mode)diff --git a/Libraries/LibJS/Debugger.h b/Libraries/LibJS/Debugger.hindex a0039d661f4..58b08fa074a 100644--- a/Libraries/LibJS/Debugger.h+++ b/Libraries/LibJS/Debugger.h@@ -11,6 +11,7 @@#include <AK/Utf16View.h>#include <AK/Vector.h>#include <LibGC/ConservativeVector.h>+#include <LibGC/Function.h>#include <LibGC/Root.h>#include <LibGC/WeakHashSet.h>#include <LibJS/Breakpoint.h>@@ -74,7 +75,7 @@ public:// The callback must call continue_execution() before it returns. It may evaluate JavaScript,// in which case any pause triggered by that evaluation is ignored.- void set_pause_callback(Function<void(PauseInfo const&)> callback);+ void set_pause_callback(GC::Ptr<GC::Function<void(PauseInfo const&)>> callback);void continue_execution(ResumeMode = ResumeMode::Continue);// Continue after the host filters out a pause without cancelling an active step operation.diff --git a/Libraries/LibJS/Runtime/ExecutionContext.h b/Libraries/LibJS/Runtime/ExecutionContext.hindex 460a478ce83..4533c02fede 100644--- a/Libraries/LibJS/Runtime/ExecutionContext.h+++ b/Libraries/LibJS/Runtime/ExecutionContext.h@@ -75,6 +75,13 @@ public:return visitor(empty);}+ void visit_edges(GC::Cell::Visitor& visitor) const+ {+ visit(+ [](Empty) { },+ [&](auto const& script_or_module) { visitor.visit(script_or_module); });+ }+bool operator==(ScriptOrModule const&) const = default;private:diff --git a/Libraries/LibJS/Runtime/NativeFunction.cpp b/Libraries/LibJS/Runtime/NativeFunction.cppindex 593f222b4ab..f4b47e9f72a 100644--- a/Libraries/LibJS/Runtime/NativeFunction.cpp+++ b/Libraries/LibJS/Runtime/NativeFunction.cpp@@ -14,15 +14,12 @@ namespace JS {using namespace EmbeddingABI;-// A closure's behaviour lives in a cell of the embedder's heap, which the function keeps alive, and whose captures the-// garbage collector scans conservatively.+// A closure's behaviour lives in a cell of the embedder's heap, which the function keeps alive.using NativeFunctionBehaviour = GC::Function<ThrowCompletionOr<Value>(VM&)>;-static void* behaviour_cell_to_abi(VM& vm, Function<ThrowCompletionOr<Value>(VM&)> behaviour)+static void* behaviour_cell_to_abi(GC::Ref<NativeFunctionBehaviour> behaviour){- VERIFY(behaviour);- auto cell = NativeFunctionBehaviour::create(vm.heap(), move(behaviour));- return static_cast<GC::Cell*>(cell.ptr());+ return static_cast<GC::Cell*>(behaviour.ptr());}// The runtime's VM pointer is the address of the embedder's JS::VM, which holds the runtime's VM in its first bytes.@@ -38,11 +35,11 @@ static NativeFunction& native_function_from_abi(JSObject* function)}// 10.3.4 CreateBuiltinFunction ( behaviour, length, name, additionalInternalSlotsList [ , realm [ , prototype [ , prefix ] ] ] ), https://tc39.es/ecma262/#sec-createbuiltinfunction-GC::Ref<NativeFunction> NativeFunction::create(Realm& allocating_realm, Function<ThrowCompletionOr<Value>(VM&)> behaviour, i32 length, PropertyKey const& name, Optional<GC::Ptr<Realm>> realm, Optional<StringView> const& prefix)+GC::Ref<NativeFunction> NativeFunction::create(Realm& allocating_realm, GC::Ref<GC::Function<ThrowCompletionOr<Value>(VM&)>> behaviour, i32 length, PropertyKey const& name, Optional<GC::Ptr<Realm>> realm, Optional<StringView> const& prefix){auto& vm = allocating_realm.vm();PrefixForABI abi_prefix { prefix };- auto* behaviour_cell = behaviour_cell_to_abi(vm, move(behaviour));+ auto* behaviour_cell = behaviour_cell_to_abi(behaviour);return native_function_from_abi(js_function_create_closure(vm_to_abi(vm), call_behaviour_cell, behaviour_cell, length, property_key_to_abi(name), builtin_function_realm_to_abi(realm), abi_prefix.characters, abi_prefix.length));}@@ -53,10 +50,10 @@ GC::Ref<NativeFunction> NativeFunction::create(Realm& allocating_realm, NativeFureturn native_function_from_abi(js_function_create_native(vm_to_abi(vm), native_function_to_abi(behaviour), length, property_key_to_abi(name), builtin_function_realm_to_abi(realm), abi_prefix.characters, abi_prefix.length));}-GC::Ref<NativeFunction> NativeFunction::create(Realm& realm, Utf16FlyString const& name, Function<ThrowCompletionOr<Value>(VM&)> behaviour)+GC::Ref<NativeFunction> NativeFunction::create(Realm& realm, Utf16FlyString const& name, GC::Ref<GC::Function<ThrowCompletionOr<Value>(VM&)>> behaviour){auto& vm = realm.vm();- auto* behaviour_cell = behaviour_cell_to_abi(vm, move(behaviour));+ auto* behaviour_cell = behaviour_cell_to_abi(behaviour);return native_function_from_abi(js_function_create_closure_with_name(vm_to_abi(vm), cell_to_abi<JSRealm>(realm), utf16_view_to_abi(name.view()), call_behaviour_cell, behaviour_cell));}diff --git a/Libraries/LibJS/Runtime/NativeFunction.h b/Libraries/LibJS/Runtime/NativeFunction.hindex 8e2f8a7df39..f743671efdb 100644--- a/Libraries/LibJS/Runtime/NativeFunction.h+++ b/Libraries/LibJS/Runtime/NativeFunction.h@@ -10,6 +10,7 @@#include <AK/Badge.h>#include <AK/Function.h>#include <AK/Optional.h>+#include <LibGC/Function.h>#include <LibGC/Member.h>#include <LibJS/Export.h>#include <LibJS/Runtime/Completion.h>@@ -22,9 +23,9 @@ namespace JS {// runtime calls directly, or a closure, which the function keeps in a GC::Function of the embedder's heap.class JS_API NativeFunction : public FunctionObject {public:- static GC::Ref<NativeFunction> create(Realm&, ESCAPING Function<ThrowCompletionOr<Value>(VM&)> behaviour, i32 length, PropertyKey const& name = Utf16FlyString {}, Optional<GC::Ptr<Realm>> = {}, Optional<StringView> const& prefix = {});+ static GC::Ref<NativeFunction> create(Realm&, GC::Ref<GC::Function<ThrowCompletionOr<Value>(VM&)>> behaviour, i32 length, PropertyKey const& name = Utf16FlyString {}, Optional<GC::Ptr<Realm>> = {}, Optional<StringView> const& prefix = {});static GC::Ref<NativeFunction> create(Realm&, NativeFunctionPointer behaviour, i32 length, PropertyKey const& name = Utf16FlyString {}, Optional<GC::Ptr<Realm>> = {}, Optional<StringView> const& prefix = {});- static GC::Ref<NativeFunction> create(Realm&, Utf16FlyString const& name, ESCAPING Function<ThrowCompletionOr<Value>(VM&)>);+ static GC::Ref<NativeFunction> create(Realm&, Utf16FlyString const& name, GC::Ref<GC::Function<ThrowCompletionOr<Value>(VM&)>>);static bool is_engine_class_of(Object const& object) { return object.is_of_engine_class_or_subclass(JS_LAYOUT_CLASS_ID_NATIVE_FUNCTION); }};diff --git a/Libraries/LibJS/Runtime/Object.cpp b/Libraries/LibJS/Runtime/Object.cppindex 7b02233e7e6..6eb73634404 100644--- a/Libraries/LibJS/Runtime/Object.cpp+++ b/Libraries/LibJS/Runtime/Object.cpp@@ -334,9 +334,9 @@ void Object::define_native_function(Realm& realm, PropertyKey const& property_kejs_object_define_native_function(vm_of(*this), object_to_abi(*this), cell_to_abi<JSRealm>(realm), property_key_to_abi(property_key), native_function_to_abi(native_function), length, attributes.bits());}-void Object::define_native_function(Realm& realm, PropertyKey const& property_key, Function<ThrowCompletionOr<Value>(VM&)> native_function, i32 length, PropertyAttributes attributes)+void Object::define_native_function(Realm& realm, PropertyKey const& property_key, GC::Ref<GC::Function<ThrowCompletionOr<Value>(VM&)>> native_function, i32 length, PropertyAttributes attributes){- auto function = NativeFunction::create(realm, move(native_function), length, property_key, &realm);+ auto function = NativeFunction::create(realm, native_function, length, property_key, &realm);define_direct_property(property_key, function, attributes);}@@ -345,14 +345,14 @@ void Object::define_native_accessor(Realm& realm, PropertyKey const& property_kejs_object_define_native_accessor(vm_of(*this), object_to_abi(*this), cell_to_abi<JSRealm>(realm), property_key_to_abi(property_key), getter ? native_function_to_abi(getter) : nullptr, setter ? native_function_to_abi(setter) : nullptr, attributes.bits());}-void Object::define_native_accessor(Realm& realm, PropertyKey const& property_key, Function<ThrowCompletionOr<Value>(VM&)> getter, Function<ThrowCompletionOr<Value>(VM&)> setter, PropertyAttributes attributes)+void Object::define_native_accessor(Realm& realm, PropertyKey const& property_key, GC::Ptr<GC::Function<ThrowCompletionOr<Value>(VM&)>> getter, GC::Ptr<GC::Function<ThrowCompletionOr<Value>(VM&)>> setter, PropertyAttributes attributes){GC::Ptr<FunctionObject> getter_function;if (getter)- getter_function = NativeFunction::create(realm, move(getter), 0, property_key, &realm, "get"sv);+ getter_function = NativeFunction::create(realm, *getter, 0, property_key, &realm, "get"sv);GC::Ptr<FunctionObject> setter_function;if (setter)- setter_function = NativeFunction::create(realm, move(setter), 1, property_key, &realm, "set"sv);+ setter_function = NativeFunction::create(realm, *setter, 1, property_key, &realm, "set"sv);define_direct_accessor(property_key, getter_function, setter_function, attributes);}diff --git a/Libraries/LibJS/Runtime/Object.h b/Libraries/LibJS/Runtime/Object.hindex 43267a4b067..0aaffc656ea 100644--- a/Libraries/LibJS/Runtime/Object.h+++ b/Libraries/LibJS/Runtime/Object.h@@ -13,6 +13,7 @@#include <AK/StringView.h>#include <LibGC/CellAllocator.h>#include <LibGC/CompressedPointer.h>+#include <LibGC/Forward.h>#include <LibGC/RootVector.h>#include <LibJS/Embedding/Layout.h>#include <LibJS/Export.h>@@ -150,9 +151,9 @@ public:void define_intrinsic_accessor(PropertyKey const&, PropertyAttributes attributes, IntrinsicAccessor accessor);void define_native_function(Realm&, PropertyKey const&, NativeFunctionPointer, i32 length, PropertyAttributes attributes);- void define_native_function(Realm&, PropertyKey const&, ESCAPING Function<ThrowCompletionOr<Value>(VM&)>, i32 length, PropertyAttributes attributes);+ void define_native_function(Realm&, PropertyKey const&, GC::Ref<GC::Function<ThrowCompletionOr<Value>(VM&)>>, i32 length, PropertyAttributes attributes);void define_native_accessor(Realm&, PropertyKey const&, NativeFunctionPointer getter, NativeFunctionPointer setter, PropertyAttributes attributes);- void define_native_accessor(Realm&, PropertyKey const&, ESCAPING Function<ThrowCompletionOr<Value>(VM&)> getter, ESCAPING Function<ThrowCompletionOr<Value>(VM&)> setter, PropertyAttributes attributes);+ void define_native_accessor(Realm&, PropertyKey const&, GC::Ptr<GC::Function<ThrowCompletionOr<Value>(VM&)>> getter, GC::Ptr<GC::Function<ThrowCompletionOr<Value>(VM&)>> setter, PropertyAttributes attributes);[[nodiscard]] bool is_function() const { return has_engine_object_flag(JS_LAYOUT_OBJECT_FLAG_IS_FUNCTION); }bool is_date() const;diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cppindex 5d783e83048..c6a4d1d1f61 100644--- a/Libraries/LibJS/Runtime/VM.cpp+++ b/Libraries/LibJS/Runtime/VM.cpp@@ -145,6 +145,18 @@ static void append_utf16_string_to_sink(JSStringSink const& sink, Utf16View strisink.append(sink.context, code_units.data(), code_units.size());}+// The goal of a spin of the event loop, which the runtime keeps on its own stack, and which holds no cell edges.+struct SpinGoalCondition {+ JSGoalCondition condition;+ void* context;+};++}++GC_UNTRACED_CAPTURE(JS::SpinGoalCondition);++namespace JS {+// The runtime calls the VM's host hooks and its agent through these, each with the facade's VM or agent as its data.struct HostHookThunks {static VM& vm_of(void* data)@@ -262,8 +274,8 @@ struct HostHookThunks {static void spin_event_loop_until(void* data, JSVM*, JSGoalCondition goal_condition, void* goal_context){auto& agent = *static_cast<Agent*>(data);- agent.spin_event_loop_until(GC::create_function(VM::the().heap(), [goal_condition, goal_context] {- return goal_condition(goal_context);+ agent.spin_event_loop_until(GC::create_function(VM::the().heap(), GC::captures(SpinGoalCondition { goal_condition, goal_context }), [](SpinGoalCondition& goal) {+ return goal.condition(goal.context);}));}};diff --git a/Libraries/LibTest/JavaScriptTestRunner.h b/Libraries/LibTest/JavaScriptTestRunner.hindex 76274a779a1..0cabbb731e1 100644--- a/Libraries/LibTest/JavaScriptTestRunner.h+++ b/Libraries/LibTest/JavaScriptTestRunner.h@@ -19,6 +19,7 @@#include <AK/Tuple.h>#include <LibCore/DirIterator.h>#include <LibCore/File.h>+#include <LibGC/Function.h>#include <LibGC/Root.h>#include <LibJS/ParserError.h>#include <LibJS/Runtime/Array.h>@@ -179,21 +180,19 @@ inline void define_test_runner_globals(JS::Realm& realm, bool prints_test_timingglobal_object.define_native_function(realm,"__reportTest__"_utf16,- [prints_test_timings](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ GC::create_function(realm.heap(), GC::captures(prints_test_timings), [](bool prints_test_timings, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {if (!prints_test_timings)return JS::js_undefined();auto test_name = TRY(vm.argument(0).to_utf16_string(vm)).to_utf8_but_should_be_ported_to_utf16();print_test_timings(test_name, vm.argument(1));return JS::js_undefined();- },+ }),2, JS::default_attributes);for (auto& entry : s_exposed_global_functions) {global_object.define_native_function(realm,entry.key,- [fn = entry.value.function](auto& vm) {- return fn(vm);- },+ entry.value.function,entry.value.length, JS::default_attributes);}}diff --git a/Libraries/LibWeb/Animations/Animation.cpp b/Libraries/LibWeb/Animations/Animation.cppindex e0529673cea..506d81b9bda 100644--- a/Libraries/LibWeb/Animations/Animation.cpp+++ b/Libraries/LibWeb/Animations/Animation.cpp@@ -885,8 +885,8 @@ void Animation::cancel(ShouldInvalidate should_invalidate)scheduled_event_time = m_timeline->convert_a_timeline_time_to_an_origin_relative_time(m_timeline->current_time());document->append_pending_animation_event({ cancel_event, *this, *this, scheduled_event_time });} else {- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function(GC::Heap::the(), [this, cancel_event]() {- dispatch_event(cancel_event);+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(*this, cancel_event), [](auto& self, auto& cancel_event) {+ self.dispatch_event(cancel_event);}));}}@@ -1596,14 +1596,14 @@ void Animation::update_finished_state(DidSeek did_seek, SynchronouslyNotify sync// steps:if (current_finished_state && !m_is_finished) {// 1. Let finish notification steps refer to the following procedure:- auto finish_notification_steps = GC::create_function(GC::Heap::the(), [this, &realm]() {+ auto finish_notification_steps = GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, realm), [](Animation& self, auto& realm) {// 1. If animation’s play state is not equal to finished, abort these steps.- if (play_state() != AnimationPlayState::Finished)+ if (self.play_state() != AnimationPlayState::Finished)return;// 2. Resolve animation’s current finished promise object with animation.- Bindings::resolve_animation_promise(current_finished_promise(), *this);- m_is_finished = true;+ Bindings::resolve_animation_promise(self.current_finished_promise(), self);+ self.m_is_finished = true;// 3. Create an AnimationPlaybackEvent, finishEvent.// 4. Set finishEvent’s type attribute to finish.@@ -1612,21 +1612,21 @@ void Animation::update_finished_state(DidSeek did_seek, SynchronouslyNotify sync// associated. If animation is not associated with a timeline, or the timeline is inactive, let// timelineTime be null.AnimationPlaybackEventInit init;- init.current_time = current_time()->as_css_numberish();- if (m_timeline && !m_timeline->is_inactive())- init.timeline_time = m_timeline->current_time()->as_css_numberish();+ init.current_time = self.current_time()->as_css_numberish();+ if (self.m_timeline && !self.m_timeline->is_inactive())+ init.timeline_time = self.m_timeline->current_time()->as_css_numberish();auto finish_event = AnimationPlaybackEvent::create(HTML::EventNames::finish, init, HighResolutionTime::current_high_resolution_time(realm.global_object()));// 7. If animation has a document for timing, then append finishEvent to its document for timing's pending// animation event queue along with its target, animation. For the scheduled event time, use the result// of converting animation’s associated effect end to an origin-relative time.- if (auto document_for_timing = this->document_for_timing()) {+ if (auto document_for_timing = self.document_for_timing()) {document_for_timing->append_pending_animation_event({.event = finish_event,- .animation = *this,- .target = *this,- .scheduled_event_time = convert_a_timeline_time_to_an_origin_relative_time(associated_effect_end()),+ .animation = self,+ .target = self,+ .scheduled_event_time = self.convert_a_timeline_time_to_an_origin_relative_time(self.associated_effect_end()),});}// Otherwise, queue a task to dispatch finishEvent at animation. The task source for this task is the DOM@@ -1635,10 +1635,10 @@ void Animation::update_finished_state(DidSeek did_seek, SynchronouslyNotify sync// Manually create a task so its ID can be savedauto& document = HTML::relevant_window(realm.global_object()).associated_document();auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document,- GC::create_function(GC::Heap::the(), [this, finish_event]() {- dispatch_event(finish_event);+ GC::create_function(GC::Heap::the(), GC::captures(self, finish_event), [](auto& self, auto& finish_event) {+ self.dispatch_event(finish_event);}));- m_pending_finish_microtask_id = task->id();+ self.m_pending_finish_microtask_id = task->id();(void)HTML::main_thread_event_loop().task_queue().add(task);}});@@ -1658,7 +1658,7 @@ void Animation::update_finished_state(DidSeek did_seek, SynchronouslyNotify syncelse if (!m_pending_finish_microtask_id.has_value()) {auto& document = HTML::relevant_window(realm.global_object()).associated_document();- auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document, GC::create_function(GC::Heap::the(), [finish_notification_steps, &realm]() {+ auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document, GC::create_function(GC::Heap::the(), GC::captures(finish_notification_steps, realm), [](auto& finish_notification_steps, auto& realm) {HTML::TemporaryExecutionContext context { realm };finish_notification_steps->function()();}));diff --git a/Libraries/LibWeb/Bindings/Intrinsics.cpp b/Libraries/LibWeb/Bindings/Intrinsics.cppindex 9e28ee2ed99..5b67d5c62d8 100644--- a/Libraries/LibWeb/Bindings/Intrinsics.cpp+++ b/Libraries/LibWeb/Bindings/Intrinsics.cpp@@ -38,14 +38,14 @@ Intrinsics& host_defined_intrinsics(JS::Realm& realm)GC::Ref<JS::NativeFunction> Intrinsics::ensure_web_unforgeable_function(Utf16FlyString const& interface_name,Utf16FlyString const& attribute_name,- Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> behaviour,+ JS::NativeFunctionPointer behaviour,UnforgeableKey::Type type){UnforgeableKey key { interface_name, attribute_name, type };if (auto it = m_unforgeable_functions.find(key); it != m_unforgeable_functions.end())return *it->value;- auto function = JS::NativeFunction::create(*m_realm, move(behaviour), type == UnforgeableKey::Type::Setter ? 1 : 0, attribute_name, m_realm, type == UnforgeableKey::Type::Setter ? "set"sv : "get"sv);+ auto function = JS::NativeFunction::create(*m_realm, behaviour, type == UnforgeableKey::Type::Setter ? 1 : 0, attribute_name, m_realm, type == UnforgeableKey::Type::Setter ? "set"sv : "get"sv);m_unforgeable_functions.set(key, *function);return *function;}diff --git a/Libraries/LibWeb/Bindings/Intrinsics.h b/Libraries/LibWeb/Bindings/Intrinsics.hindex 4f41dc693b9..5d901435fbd 100644--- a/Libraries/LibWeb/Bindings/Intrinsics.h+++ b/Libraries/LibWeb/Bindings/Intrinsics.h@@ -116,7 +116,7 @@ public:GC::Ref<JS::NativeFunction> ensure_web_unforgeable_function(Utf16FlyString const& interface_name,Utf16FlyString const& attribute_name,- Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> behaviour,+ JS::NativeFunctionPointer behaviour,UnforgeableKey::Type);private:diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cppindex 630c7e5f641..d2ef4f69c03 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp@@ -88,6 +88,9 @@#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWebCommon/Page/QueuedInputEvent.h>+// NB: A module request holds strings only.+GC_UNTRACED_CAPTURE(JS::ModuleRequest);+namespace Web::Bindings {GC_DEFINE_ALLOCATOR(WebEngineCustomJobCallbackData);@@ -287,7 +290,7 @@ void initialize_agent(HTML::AgentType type)// with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.auto& global_object = settings_object.global_object();auto& realm = settings_object.realm();- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global_object, GC::create_function(GC::Heap::the(), [&global, &promise, &realm] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global_object, GC::create_function(GC::Heap::the(), GC::captures(global, promise, realm), [](auto& global, auto& promise, auto& realm) {HTML::PromiseRejectionEventInit event_init {{}, // Initialize the inherited EventInit/* .promise = */ promise,@@ -349,7 +352,7 @@ void initialize_agent(HTML::AgentType type)auto& global = finalization_registry.realm().global_object();// 2. Queue a global task on the JavaScript engine task source given global to perform the following steps:- HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, GC::create_function(GC::Heap::the(), [&finalization_registry] {+ HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, GC::create_function(GC::Heap::the(), GC::captures(finalization_registry), [](auto& finalization_registry) {// 1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]]'s environment settings object.// AD-HOC: The spec assumes [[Callback]] has a [[Realm]] internal slot, but Proxy and BoundFunction// exotic objects do not. Use GetFunctionRealm to unwrap these exotic objects, falling back to@@ -395,7 +398,9 @@ void initialize_agent(HTML::AgentType type)// Do note that "implied document" from the spec is handwavy and the spec authors are trying to get rid of it: https://github.com/whatwg/html/issues/4980auto* script = active_script();- HTML::queue_a_microtask(script ? script->settings_object().responsible_document().ptr() : nullptr, GC::create_function(GC::Heap::the(), [&vm, job_settings, job = move(job), script_or_module = move(script_or_module)] {+ HTML::queue_a_microtask(script ? script->settings_object().responsible_document().ptr() : nullptr, GC::create_function(GC::Heap::the(), GC::captures(job_settings, move(job), move(script_or_module)), [](auto& job_settings, auto& job, auto& script_or_module) {+ auto& vm = JS::VM::the();+// The dummy execution context has to be kept up here to keep it alive for the duration of the function.OwnPtr<JS::ExecutionContext> dummy_execution_context;@@ -496,7 +501,7 @@ void initialize_agent(HTML::AgentType type)auto url_string = module_script.base_url()->serialize();// 4. Let steps be the following steps, given the argument specifier:- auto steps = [&realm, module_script = GC::Ref { module_script }](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto steps = GC::create_function(GC::Heap::the(), GC::captures(realm, GC::Ref { module_script }), [](auto& realm, auto& module_script, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {auto specifier = vm.argument(0);// 1. Set specifier to ? ToString(specifier).@@ -509,10 +514,10 @@ void initialize_agent(HTML::AgentType type)// 3. Return the serialization of url.return JS::PrimitiveString::create(vm, Utf16String::from_utf8(url.serialize()));- };+ });// 4. Let resolveFunction be ! CreateBuiltinFunction(steps, 1, "resolve", « »).- auto resolve_function = JS::NativeFunction::create(realm, move(steps), 1, vm.names.resolve);+ auto resolve_function = JS::NativeFunction::create(realm, steps, 1, vm.names.resolve);// 5. Return « Record { [[Key]]: "url", [[Value]]: urlString }, Record { [[Key]]: "resolve", [[Value]]: resolveFunction } ».GC::RootHashMap<JS::PropertyKey, JS::Value> meta;@@ -692,7 +697,7 @@ void initialize_agent(HTML::AgentType type)perform_fetch = fetch_context.perform_fetch;}- auto on_single_fetch_complete = HTML::create_on_fetch_script_complete(settings_object->heap(), [referrer, settings_object, load_state, module_request, payload](GC::Ptr<HTML::Script> const& module_script) -> void {+ auto on_single_fetch_complete = HTML::create_on_fetch_script_complete(settings_object->heap(), GC::captures(referrer, settings_object, load_state, module_request, payload), [](auto& referrer, auto& settings_object, auto& load_state, auto& module_request, auto& payload, GC::Ptr<HTML::Script> const& module_script) -> void {auto& realm = settings_object->realm();// onSingleFetchComplete given moduleScript is the following algorithm:// 1. Let completion be null.diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex eb85a20c59a..f67068f9415 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -292,7 +292,7 @@ void web_bindings_queue_a_microtask(void* realm, JSObject* function){GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);GC::Ref<JS::FunctionObject> steps = as<JS::FunctionObject>(*JS::HostABI::object_from_abi(function));- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [js_realm, steps] {+ HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), GC::captures(js_realm, steps), [](auto& js_realm, auto& steps) {HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// NB: The steps cannot fail, but they can run into the abort of the script that they call.auto& vm = steps->vm();@@ -304,10 +304,10 @@ void web_bindings_queue_a_microtask(void* realm, JSObject* function)void web_bindings_run_in_parallel(void* realm, void* cell, void (*steps)(JSVM*, void*)){GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);- // NB: The function's captures, which the collector scans, keep the cell alive until the steps run.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [js_realm, cell, steps] {+ // NB: The function's captures, which the collector traces, keep the cell alive until the steps run.+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(js_realm, GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& js_realm, auto& cell, auto& steps) {HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell);+ steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell.ptr());}));}@@ -320,19 +320,19 @@ static_assert(to_underlying(HTML::Task::Source::Storage) == 29);void web_bindings_queue_a_task(void* realm, u8 task_source, void* cell, void (*steps)(JSVM*, void*)){GC::Ref<JS::Realm> js_realm = *static_cast<JS::Realm*>(realm);- // NB: The task's captures, which the collector scans, keep the cell alive until the steps run.- HTML::queue_a_task(static_cast<HTML::Task::Source>(task_source), nullptr, nullptr, GC::create_function(GC::Heap::the(), [js_realm, cell, steps] {+ // NB: The task's captures, which the collector traces, keep the cell alive until the steps run.+ HTML::queue_a_task(static_cast<HTML::Task::Source>(task_source), nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(js_realm, GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& js_realm, auto& cell, auto& steps) {HTML::TemporaryExecutionContext execution_context { js_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell);+ steps(JS::HostABI::vm_to_abi(js_realm->vm()), cell.ptr());}));}u64 web_bindings_queue_a_global_task(JSObject* global_object, u8 task_source, void* cell, void (*steps)(JSVM*, void*)){auto& global = *JS::HostABI::object_from_abi(global_object);- // NB: The task's captures, which the collector scans, keep the cell alive until the steps run.- auto task_id = HTML::queue_global_task(static_cast<HTML::Task::Source>(task_source), global, GC::create_function(GC::Heap::the(), [&vm = global.vm(), cell, steps] {- steps(JS::HostABI::vm_to_abi(vm), cell);+ // NB: The task's captures, which the collector traces, keep the cell alive until the steps run.+ auto task_id = HTML::queue_global_task(static_cast<HTML::Task::Source>(task_source), global, GC::create_function(GC::Heap::the(), GC::captures(global, GC::Ref { *static_cast<GC::Cell*>(cell) }, steps), [](auto& global, auto& cell, auto& steps) {+ steps(JS::HostABI::vm_to_abi(global.vm()), cell.ptr());}));return task_id.value();}diff --git a/Libraries/LibWeb/CSS/Fetch.cpp b/Libraries/LibWeb/CSS/Fetch.cppindex 4613c80b5aa..0688081bde7 100644--- a/Libraries/LibWeb/CSS/Fetch.cpp+++ b/Libraries/LibWeb/CSS/Fetch.cpp@@ -146,7 +146,7 @@ static RefPtr<Fetch::Infrastructure::Request> fetch_a_style_resource_impl(StyleR}// https://drafts.csswg.org/css-values-4/#fetch-a-style-resource-GC::Ptr<Fetch::Infrastructure::FetchController> fetch_a_style_resource(StyleResourceURL const& url_value, RuleOrDeclaration css_rule_or_declaration, Fetch::Infrastructure::Request::Destination destination, CorsMode cors_mode, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction process_response)+GC::Ptr<Fetch::Infrastructure::FetchController> fetch_a_style_resource(StyleResourceURL const& url_value, RuleOrDeclaration css_rule_or_declaration, Fetch::Infrastructure::Request::Destination destination, CorsMode cors_mode, GC::Ref<GC::Function<Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction::FunctionType>> process_response){auto request = fetch_a_style_resource_impl(url_value, css_rule_or_declaration, destination, cors_mode);if (!request)@@ -155,7 +155,7 @@ GC::Ptr<Fetch::Infrastructure::FetchController> fetch_a_style_resource(StyleResoauto& environment_settings = *css_rule_or_declaration.environment_settings_object;Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = move(process_response);+ fetch_algorithms_input.process_response_consume_body = process_response;return Fetch::Fetching::fetch(environment_settings.realm(), *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}diff --git a/Libraries/LibWeb/CSS/Fetch.h b/Libraries/LibWeb/CSS/Fetch.hindex c74967df464..85aa3de362c 100644--- a/Libraries/LibWeb/CSS/Fetch.h+++ b/Libraries/LibWeb/CSS/Fetch.h@@ -46,7 +46,7 @@ struct RuleOrDeclaration {Optional<::URL::URL> resolve_a_style_resource_url(StyleResourceURL const&, RuleOrDeclaration);// https://drafts.csswg.org/css-values-4/#fetch-a-style-resource-GC::Ptr<Fetch::Infrastructure::FetchController> fetch_a_style_resource(StyleResourceURL const& url, RuleOrDeclaration, Fetch::Infrastructure::Request::Destination, CorsMode, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction process_response);+GC::Ptr<Fetch::Infrastructure::FetchController> fetch_a_style_resource(StyleResourceURL const& url, RuleOrDeclaration, Fetch::Infrastructure::Request::Destination, CorsMode, GC::Ref<GC::Function<Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction::FunctionType>> process_response);// https://drafts.csswg.org/css-images-4/#fetch-an-external-image-for-a-stylesheetGC::Ptr<HTML::SharedResourceRequest> fetch_an_external_image_for_a_stylesheet(StyleResourceURL const&, RuleOrDeclaration, DOM::Document&);diff --git a/Libraries/LibWeb/CSS/FontComputer.cpp b/Libraries/LibWeb/CSS/FontComputer.cppindex f607cef0e0a..4ca8702816a 100644--- a/Libraries/LibWeb/CSS/FontComputer.cpp+++ b/Libraries/LibWeb/CSS/FontComputer.cpp@@ -159,7 +159,7 @@ void FontLoader::start_loading_next_source()// failure or a byte stream stream:m_has_received_font_data = false;m_fetch_controller = fetch_a_style_resource(m_sources.take_first().get<URL>(), m_rule_or_declaration, Fetch::Infrastructure::Request::Destination::Font, CorsMode::Cors,- [loader = this](auto response, auto stream) {+ GC::create_function(heap(), GC::captures(this), [](FontLoader* loader, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes stream) {// 1. If stream is null, return.// 2. Load a font from stream according to its type.@@ -226,7 +226,7 @@ void FontLoader::start_loading_next_source()}loader->font_did_load_or_fail(maybe_typeface.release_value()); });- });+ }));if (m_fetch_controller || m_has_completed)return;diff --git a/Libraries/LibWeb/CSS/FontFace.cpp b/Libraries/LibWeb/CSS/FontFace.cppindex e499e11e612..f3f8d834dcb 100644--- a/Libraries/LibWeb/CSS/FontFace.cpp+++ b/Libraries/LibWeb/CSS/FontFace.cpp@@ -307,7 +307,7 @@ GC::Ref<FontFace> FontFaceState::create_for_constructor(JS::Object& relevant_gloif (font_face->m_binary_data.is_empty())return cssom_font_face;- HTML::queue_global_task(HTML::Task::Source::FontLoading, font_face->task_global_object(), GC::create_function(GC::Heap::the(), [font_root = font_face->keep_alive_during_load()] {+ HTML::queue_global_task(HTML::Task::Source::FontLoading, font_face->task_global_object(), GC::create_function(GC::Heap::the(), GC::captures(font_face->keep_alive_during_load()), [](auto& font_root) {auto font_face = font_root->elements().first();HTML::TemporaryExecutionContext context(*font_face->m_environment, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 1. Set font face’s status attribute to "loading".@@ -326,7 +326,7 @@ GC::Ref<FontFace> FontFaceState::create_for_constructor(JS::Object& relevant_glofont_face->m_font_load_promise->when_resolved([font_root = GC::make_root(font_face->keep_alive_during_load())](auto const& vector_font) -> ErrorOr<void> {auto font = font_root->elements().first();- HTML::queue_global_task(HTML::Task::Source::FontLoading, font->task_global_object(), GC::create_function(GC::Heap::the(), [font_root = GC::Ref { *font_root }, vector_font] {+ HTML::queue_global_task(HTML::Task::Source::FontLoading, font->task_global_object(), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *font_root }, vector_font), [](auto& font_root, auto& vector_font) {auto font = font_root->elements().first();HTML::TemporaryExecutionContext context(*font->m_environment, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 1. If the load was successful, font face now represents the parsed font;@@ -350,12 +350,12 @@ GC::Ref<FontFace> FontFaceState::create_for_constructor(JS::Object& relevant_glo});font_face->m_font_load_promise->when_rejected([font_root = GC::make_root(font_face->keep_alive_during_load())](auto const& error) {auto font = font_root->elements().first();- HTML::queue_global_task(HTML::Task::Source::FontLoading, font->task_global_object(), GC::create_function(GC::Heap::the(), [font_root = GC::Ref { *font_root }, error = Error::copy(error)] {+ HTML::queue_global_task(HTML::Task::Source::FontLoading, font->task_global_object(), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *font_root }, Utf16String::formatted("Failed to load font: {}", error)), [](auto& font_root, auto& message) {auto font = font_root->elements().first();HTML::TemporaryExecutionContext context(*font->m_environment, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 2. Otherwise, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError"// and set font face’s status attribute to "error".- font->reject_status_promise(WebIDL::SyntaxError::create(Utf16String::formatted("Failed to load font: {}", error)));+ font->reject_status_promise(WebIDL::SyntaxError::create(message));font->did_finish_loading_in_containing_sets(false);@@ -760,7 +760,7 @@ void FontFaceState::update_font_display_period()if (!next_deadline.has_value() || m_font_display_time_for_testing.has_value())return;if (!m_font_download_timer) {- m_font_download_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(0), GC::create_function(GC::Heap::the(), [font_root = keep_alive_during_load()] {+ m_font_download_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(0), GC::create_function(GC::Heap::the(), GC::captures(keep_alive_during_load()), [](auto& font_root) {font_root->elements().first()->update_font_display_period();}));}@@ -928,7 +928,7 @@ void FontFaceState::load_for_style()// as if it was the value of a @font-face rule’s src descriptor.// 5. When the load operation completes, successfully or not, queue a task to run the following steps synchronously:- auto on_load = GC::create_function(GC::Heap::the(), [font_root = keep_alive_during_load()](RefPtr<Gfx::Typeface const> maybe_typeface) {+ auto on_load = GC::create_function(GC::Heap::the(), GC::captures(keep_alive_during_load()), [](auto& font_root, RefPtr<Gfx::Typeface const> maybe_typeface) {auto& font = *font_root->elements().first();// NB: A resident typeface is available to synchronous layout immediately. Keep the// observable load status, promise settlement, and FontFaceSet notifications in@@ -944,7 +944,7 @@ void FontFaceState::load_for_style()if (auto font_computer = font.font_computer(); font_computer.has_value())font_computer->did_load_font(font.matching_key());}- HTML::queue_global_task(HTML::Task::Source::FontLoading, font.task_global_object(), GC::create_function(GC::Heap::the(), [font_root, maybe_typeface] {+ HTML::queue_global_task(HTML::Task::Source::FontLoading, font.task_global_object(), GC::create_function(GC::Heap::the(), GC::captures(font_root, maybe_typeface), [](auto& font_root, auto& maybe_typeface) {font_root->elements().first()->did_load(maybe_typeface);}));});diff --git a/Libraries/LibWeb/CSS/ImageStyleValueResourceKey.h b/Libraries/LibWeb/CSS/ImageStyleValueResourceKey.hindex 437e5c46986..41abcdcbbc2 100644--- a/Libraries/LibWeb/CSS/ImageStyleValueResourceKey.h+++ b/Libraries/LibWeb/CSS/ImageStyleValueResourceKey.h@@ -10,6 +10,7 @@#include <AK/Optional.h>#include <AK/Traits.h>#include <AK/Utf16FlyString.h>+#include <LibGC/Forward.h>#include <LibURL/URL.h>#include <LibWeb/CSS/Enums.h>#include <LibWeb/CSS/URL.h>@@ -65,3 +66,5 @@ struct AK::Traits<Web::CSS::ImageStyleValueResourceKey> : public AK::DefaultTraireturn hash;}};++GC_UNTRACED_CAPTURE(Web::CSS::ImageStyleValueResourceKey);diff --git a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.hindex 124b99beecc..6e1dc9cb547 100644--- a/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h+++ b/Libraries/LibWeb/CSS/Parser/RustSyntaxParsing.h@@ -8,6 +8,7 @@#include <AK/Function.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>#include <LibWeb/CSS/DescriptorNameAndID.h>#include <LibWeb/CSS/Parser/RuleContext.h>#include <LibWeb/CSS/RustDeclarationBlock.h>@@ -59,3 +60,5 @@ inline ValueParserFFI::FfiUtf16View ffi_utf16_view(Utf16View view)}}++GC_UNTRACED_CAPTURE(Web::CSS::Parser::RustStyleSheetParse);diff --git a/Libraries/LibWeb/CSS/StyleScope.cpp b/Libraries/LibWeb/CSS/StyleScope.cppindex 5be154cb95e..eb96863e346 100644--- a/Libraries/LibWeb/CSS/StyleScope.cpp+++ b/Libraries/LibWeb/CSS/StyleScope.cpp@@ -367,7 +367,7 @@ void StyleScope::prepare_user_agent_rules(DOM::Document& document)if (prepared || !Core::EventLoop::is_running())return;prepared = true;- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(document.heap(), [document = GC::Ref { document }] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(document.heap(), GC::captures(GC::Ref { document }), [](auto& document) {auto& sheet = default_stylesheet();publish_user_agent_sheet(sheet, document);MediaEnvironmentSnapshot environment { document };diff --git a/Libraries/LibWeb/CSS/StyleSheetImport.cpp b/Libraries/LibWeb/CSS/StyleSheetImport.cppindex 209c6c21615..87c7ce686d4 100644--- a/Libraries/LibWeb/CSS/StyleSheetImport.cpp+++ b/Libraries/LibWeb/CSS/StyleSheetImport.cpp@@ -243,7 +243,7 @@ void StyleSheetImport::fetch().parent_style_sheet_origin_clean = {},};(void)fetch_a_style_resource(URL { href() }, rule_or_declaration, Fetch::Infrastructure::Request::Destination::Style, CorsMode::NoCors,- [strong_this = NonnullRefPtr { *this }, parent_style_sheet = NonnullRefPtr { parent_style_sheet }, document = m_document, load_event_delayer = DOM::DocumentLoadEventDelayer(*m_document, DOM::DocumentLoadEventDelayerReason::StyleSheetRequest)](auto response, auto maybe_byte_stream) mutable {+ GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { *this }, NonnullRefPtr { parent_style_sheet }, m_document, DOM::DocumentLoadEventDelayer(*m_document, DOM::DocumentLoadEventDelayerReason::StyleSheetRequest)), [](auto& strong_this, auto& parent_style_sheet, auto& document, auto& load_event_delayer, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes maybe_byte_stream) {// AD-HOC: Stop delaying the load event.auto finish_loading = [strong_this, document, load_event_delayer = move(load_event_delayer)] {auto imported_sheet = strong_this->m_style_sheet;@@ -324,7 +324,7 @@ void StyleSheetImport::fetch()strong_this->set_style_sheet(imported_style_sheet);});guard.disarm();- });+ }));}void StyleSheetImport::set_style_sheet(NonnullRefPtr<StyleSheetState> style_sheet)diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cppindex ef50e85efe8..d5060b9f884 100644--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp@@ -317,7 +317,7 @@ GC::Ref<WebIDL::Promise> StyleSheetState::replace(Utf16String text)auto& realm = HTML::relevant_realm(*constructor_document());auto promise = WebIDL::create_promise_for(*constructor_document());set_disallow_modification(true);- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(realm.heap(), [sheet = GC::Ref { cssom_sheet() }, &realm, text = move(text), promise = GC::Root(promise)] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(realm.heap(), GC::captures(GC::Ref { cssom_sheet() }, realm, move(text), GC::Root(promise)), [](auto& sheet, auto& realm, auto& text, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };auto& state = sheet->state();diff --git a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cppindex 5fcd7e2a9a5..54d7fac27a9 100644--- a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp+++ b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp@@ -47,13 +47,13 @@ ImageStyleValueResource::ImageStyleValueResource(ImageStyleValueResourceKey key,, m_resource_request(move(request)){m_resource_request->add_callbacks(- [weak_document = GC::Weak(document), key = m_key] {+ GC::create_function(GC::Heap::the(), GC::captures(GC::Weak(document), m_key), [](auto& weak_document, auto& key) {// FIXME: Can we directly access the resource (i.e. this) here instead of looking it up in the document?if (auto document = weak_document.ptr()) {if (auto* resource = document->css_image_resource(key))resource->on_decoded_image_data_loaded();}- },+ }),nullptr);}diff --git a/Libraries/LibWeb/Clipboard/Clipboard.cpp b/Libraries/LibWeb/Clipboard/Clipboard.cppindex 1fefa240a46..67788fea76b 100644--- a/Libraries/LibWeb/Clipboard/Clipboard.cpp+++ b/Libraries/LibWeb/Clipboard/Clipboard.cpp@@ -207,7 +207,7 @@ void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<Web}// 4. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, promise, formats = move(formats)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(formats)), [](auto& realm, auto& promise, auto& formats) {// 1. Let r be the result of running check clipboard read permission.auto result = check_clipboard_read_permission(realm);@@ -215,7 +215,7 @@ void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<Webif (!result) {// 1. Queue a global task on the permission task source, given realm’s global object, to reject p with// "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise]() mutable {+ queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard reading is only allowed through user activation"_utf16));}));@@ -225,7 +225,7 @@ void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<Web}// 3. Let data be the system clipboard data.- HTML::relevant_window(realm.global_object()).page().request_clipboard_entries(GC::create_function(GC::Heap::the(), [&realm, promise, formats = move(formats)](Vector<SystemClipboardItem> data) mutable {+ HTML::relevant_window(realm.global_object()).page().request_clipboard_entries(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(formats)), [](auto& realm, auto& promise, auto& formats, Vector<SystemClipboardItem> data) {HTML::TemporaryExecutionContext execution_context { realm };// 4. Let snapshotChangeCount be the current clipboard change count.@@ -239,6 +239,8 @@ void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<Webstruct ReadItem {GC::Ref<ClipboardItem> item;Optional<SystemClipboardItem> originating;++ void visit_edges(GC::Cell::Visitor& visitor) const { visitor.visit(item); }};GC::ConservativeVector<ReadItem> items;@@ -294,7 +296,7 @@ void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<Web}// 9. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise, formats = move(formats), snapshot_change_count, items = move(items)]() mutable {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(formats), snapshot_change_count, move(static_cast<Vector<ReadItem>&>(items))), [](auto& realm, auto& promise, auto& formats, auto& snapshot_change_count, auto& items) {HTML::TemporaryExecutionContext execution_context { realm };// 1. Let clipboardItems be a sequence<ClipboardItem>.@@ -331,7 +333,7 @@ void Clipboard::read(JS::Realm& realm, ClipboardReadOptions formats, GC::Ref<Webvoid Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise){// 3. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, promise]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {// 1. Let r be the result of running check clipboard read permission.auto result = check_clipboard_read_permission(realm);@@ -339,7 +341,7 @@ void Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)if (!result) {// 1. Queue a global task on the permission task source, given realm’s global object, to reject p with// "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise]() mutable {+ queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard reading is only allowed through user activation"_utf16));}));@@ -349,9 +351,9 @@ void Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)}// 3. Let data be a copy of the system clipboard data.- HTML::relevant_window(realm.global_object()).page().request_clipboard_entries(GC::create_function(GC::Heap::the(), [&realm, promise](Vector<SystemClipboardItem> data) mutable {+ HTML::relevant_window(realm.global_object()).page().request_clipboard_entries(GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, Vector<SystemClipboardItem> data) {// 4. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise, data = move(data)]() mutable {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {HTML::TemporaryExecutionContext execution_context { realm };// 1. For each systemClipboardItem in data:@@ -359,7 +361,7 @@ void Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)// 1. For each systemClipboardRepresentation in systemClipboardItem:for (auto const& system_clipboard_representation : system_clipboard_item.system_clipboard_representations) {// AD-HOC: We do not expose file-backed clipboard entries to scripts.- auto const* data = system_clipboard_representation.data.get_pointer<ByteString>();+ auto const* data = system_clipboard_representation.data.template get_pointer<ByteString>();if (!data)continue;@@ -415,7 +417,7 @@ void Clipboard::read_text(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> const& data, GC::Ref<WebIDL::Promise> promise){// 3. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, promise, data = move(data)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {// 1. Let r be the result of running check clipboard write permission.auto result = check_clipboard_write_permission(realm);@@ -423,7 +425,7 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> cif (!result) {// 1. Queue a global task on the permission task source, given realm’s global object, to reject p with// "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise]() mutable {+ queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard writing is only allowed through user activation"_utf16));}));@@ -433,7 +435,7 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> c}// 3. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise, data = move(data)]() mutable {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Let itemList and cleanItemList be an empty sequence<Blob>.@@ -449,7 +451,8 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> c// 4. For each clipboardItem in dataList:for (auto const& clipboard_item : data_list) {- IGNORE_USE_IN_ESCAPING_LAMBDA GC::RootVector<GC::Ref<FileAPI::Blob>> item_list;+ // NB: The reaction steps append to itemList, which these steps read after them, so it is a cell they share.+ auto item_list = GC::Heap::the().allocate<GC::HeapVector<GC::Ref<FileAPI::Blob>>>();GC::RootVector<GC::Ref<FileAPI::Blob>> clean_item_list;// 1. For each representation in clipboardItem’s clipboard item's list of representations:@@ -460,7 +463,7 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> c// 2. React to representationDataPromise:auto reaction = WebIDL::react_to_promise(representation_data_promise,// 1. If representationDataPromise was fulfilled with value v, then:- GC::create_function(GC::Heap::the(), [&item_list, mime_type = representation.mime_type](JS::Value value) mutable -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(item_list, representation.mime_type), [](auto& item_list, auto& mime_type, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {// 1. If v is a DOMString, then follow the below steps:if (value.is_string()) {// 1. Let dataAsBytes be the result of UTF-8 encoding v.@@ -470,19 +473,19 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> cauto blob_data = FileAPI::Blob::create(MUST(ByteBuffer::copy(data_as_bytes.bytes())), mime_type);// 3. Add blobData to itemList.- item_list.append(blob_data);+ item_list->elements().append(blob_data);}// 2. If v is a Blob, then add v to itemList.else if (value.is_object()) {if (auto blob = clipboard_item_data_blob(value))- item_list.append(*blob);+ item_list->elements().append(*blob);}return JS::js_undefined();}),// 2. If representationDataPromise was rejected, then:- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext execution_context { realm };// 1. Reject p with "NotAllowedError" DOMException in realm.@@ -499,7 +502,7 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> c// https://github.com/w3c/clipboard-apis/issues/237auto& reaction_promise = as<JS::Promise>(*reaction->promise());- HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), [&reaction_promise]() {+ HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(reaction_promise), [](auto& reaction_promise) {return reaction_promise.state() != JS::Promise::State::Pending;}));@@ -508,7 +511,7 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> c}// 2. For each blob in itemList:- for (auto blob : item_list) {+ for (auto blob : item_list->elements()) {// 1. Let type be the blob’s type.auto const& type = blob->type();@@ -547,7 +550,7 @@ void Clipboard::write(JS::Realm& realm, GC::RootVector<GC::Ref<ClipboardItem>> cvoid Clipboard::write_text(JS::Realm& realm, Utf16String data, GC::Ref<WebIDL::Promise> promise){// 3. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, promise, data = move(data)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {// 1. Let r be the result of running check clipboard write permission.auto result = check_clipboard_write_permission(realm);@@ -555,7 +558,7 @@ void Clipboard::write_text(JS::Realm& realm, Utf16String data, GC::Ref<WebIDL::Pif (!result) {// 1. Queue a global task on the permission task source, given realm’s global object, to reject p with// "NotAllowedError" DOMException in realm.- queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise]() mutable {+ queue_global_task(HTML::Task::Source::Permissions, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::reject_promise(promise, WebIDL::NotAllowedError::create("Clipboard writing is only allowed through user activation"_utf16));}));@@ -565,7 +568,7 @@ void Clipboard::write_text(JS::Realm& realm, Utf16String data, GC::Ref<WebIDL::P}// 3. Queue a global task on the clipboard task source, given realm’s global object, to perform the below steps:- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise, data = move(data)]() mutable {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(data)), [](auto& realm, auto& promise, auto& data) {// 1. Let itemList be an empty sequence<Blob>.GC::RootVector<GC::Ref<FileAPI::Blob>> item_list;diff --git a/Libraries/LibWeb/Clipboard/ClipboardItem.cpp b/Libraries/LibWeb/Clipboard/ClipboardItem.cppindex 87448402411..4c520fd3d40 100644--- a/Libraries/LibWeb/Clipboard/ClipboardItem.cpp+++ b/Libraries/LibWeb/Clipboard/ClipboardItem.cpp@@ -197,15 +197,15 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm&m_representations_with_resolvers.set(key, promise);// 4. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, promise, mime_type = mime_type.release_value(), is_custom]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, realm, promise, mime_type.release_value(), is_custom), [](ClipboardItem& self, auto& realm, GC::Ref<WebIDL::Promise>& promise, MimeSniff::MimeType& mime_type, bool& is_custom) {// 1. Let clipboardItem be this’s originating system clipboard item.- auto const& clipboard_item = m_originating_system_clipboard_item;+ auto const& clipboard_item = self.m_originating_system_clipboard_item;// 2. If clipboardItem is null, then queue a global task on the clipboard task source, given realm’s// global object, to reject p with an "InvalidStateError" DOMException in realm, then abort these// steps.if (!clipboard_item.has_value()) {- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise]() {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("This clipboard item is missing an originating system clipboard entry"_utf16));}));@@ -242,7 +242,7 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm&});if (!clipboard_representation.has_value()) {- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise, os_format_name]() {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, os_format_name), [](auto& realm, auto& promise, auto& os_format_name) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::reject_promise(promise, WebIDL::NotFoundError::create(realm, Utf16String::formatted("No data found for MIME type: {}", os_format_name)));}));@@ -253,7 +253,7 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm&auto const& raw_data = clipboard_representation->data;// 7. Let cleanData be a copy of rawData.- auto clean_data = MUST(ByteBuffer::copy(raw_data.get<ByteString>().bytes()));+ auto clean_data = MUST(ByteBuffer::copy(raw_data.template get<ByteString>().bytes()));// FIXME: 8. If mimeType’s essence is in this’s unsanitized MIME types and mimeType’s essence is in the// optional unsanitized data types list, then do nothing.@@ -263,7 +263,7 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm&auto blob = FileAPI::Blob::create(move(clean_data), mime_type.serialized_as_utf16());// 11. Queue a global task on the clipboard task source, given realm’s global object, to resolve p with blob.- queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, promise, blob]() {+ queue_global_task(HTML::Task::Source::Clipboard, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, promise, blob), [](auto& realm, auto& promise, auto& blob) {HTML::TemporaryExecutionContext execution_context { realm };resolve_clipboard_item_blob_promise(realm, promise, blob);}));@@ -277,7 +277,7 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm&WebIDL::react_to_promise(*representation_data_promise,// 1. If representationDataPromise was fulfilled with value v, then:- GC::create_function(GC::Heap::the(), [&realm, promise, mime_type_serialized](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise, mime_type_serialized), [](auto& realm, auto& promise, auto& mime_type_serialized, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {// 1. If v is a DOMString, then follow the below steps:if (value.is_string()) {// 1. Let dataAsBytes be the result of UTF-8 encoding v.@@ -299,7 +299,7 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> ClipboardItem::get_type(JS::Realm&return JS::js_undefined();}),// 2. If representationDataPromise was rejected, then:- GC::create_function(GC::Heap::the(), [&realm, type, promise](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, type, promise), [](auto& realm, auto& type, auto& promise, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {// 1. Reject p with "NotFoundError" DOMException in realm.WebIDL::reject_promise(promise, WebIDL::NotFoundError::create(realm, Utf16String::formatted("No data found for MIME type: {}", type)));diff --git a/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp b/Libraries/LibWeb/ContentSecurityPolicy/Violation.cppindex 0445e05aeb2..5a58e0527dc 100644--- a/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp+++ b/Libraries/LibWeb/ContentSecurityPolicy/Violation.cpp@@ -298,7 +298,7 @@ void Violation::report_a_violation(JS::Realm& realm)// 3. Queue a task to run the following steps:// Spec Note: We "queue a task" here to ensure that the event targeting and dispatch happens after JavaScript// completes execution of the task responsible for a given violation (which might manipulate the DOM).- HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this, global_scope, target, &realm] {+ HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, global_scope, target, realm), [](Violation& self, GC::Ptr<DOM::EventTarget>& global_scope, GC::Ptr<DOM::Element>& target, auto& realm) {GC::Ptr<DOM::EventTarget> event_target = target;// 1. If target is not null, and global is a Window, and target’s shadow-including root is not global’s@@ -345,56 +345,56 @@ void Violation::report_a_violation(JS::Realm& realm)// documentURI// The result of executing § 5.4 Strip URL for use in reports on violation's url.- event_init.document_uri = Utf16String::from_utf8(strip_url_for_use_in_reports(url()));+ event_init.document_uri = Utf16String::from_utf8(strip_url_for_use_in_reports(self.url()));// referrer// The result of executing § 5.4 Strip URL for use in reports on violation's referrer.// FIXME: File spec issue for referrer being potentially null.- event_init.referrer = m_referrer.has_value() ? Utf16String::from_utf8(strip_url_for_use_in_reports(m_referrer.value())) : Utf16String {};+ event_init.referrer = self.m_referrer.has_value() ? Utf16String::from_utf8(strip_url_for_use_in_reports(self.m_referrer.value())) : Utf16String {};// blockedURI// The result of executing § 5.2 Obtain the blockedURI of a violation's resource on violation’s// resource.- event_init.blocked_uri = Utf16String::from_utf8(obtain_the_blocked_uri_of_resource());+ event_init.blocked_uri = Utf16String::from_utf8(self.obtain_the_blocked_uri_of_resource());// effectiveDirective// violation's effective directive- event_init.effective_directive = m_effective_directive;+ event_init.effective_directive = self.m_effective_directive;// violatedDirective// violation's effective directive// Spec Note: Both effectiveDirective and violatedDirective are the same value. This is intentional// to maintain backwards compatibility.- event_init.violated_directive = m_effective_directive;+ event_init.violated_directive = self.m_effective_directive;// originalPolicy// The serialization of violation's policy- event_init.original_policy = Utf16String::from_utf8(m_policy->pre_parsed_policy_string());+ event_init.original_policy = Utf16String::from_utf8(self.m_policy->pre_parsed_policy_string());// disposition// violation's disposition- event_init.disposition = disposition();+ event_init.disposition = self.disposition();// sourceFile// The result of executing § 5.4 Strip URL for use in reports on violation’s source file, if// violation's source file is not null, or null otherwise.- event_init.source_file = m_source_file.has_value() ? Utf16String::from_utf8(strip_url_for_use_in_reports(m_source_file.value())) : Utf16String {};+ event_init.source_file = self.m_source_file.has_value() ? Utf16String::from_utf8(strip_url_for_use_in_reports(self.m_source_file.value())) : Utf16String {};// statusCode// violation's status- event_init.status_code = m_status;+ event_init.status_code = self.m_status;// lineNumber// violation’s line number- event_init.line_number = m_line_number;+ event_init.line_number = self.m_line_number;// columnNumber// violation’s column number- event_init.column_number = m_column_number;+ event_init.column_number = self.m_column_number;// sample// violation's sample- event_init.sample = m_sample;+ event_init.sample = self.m_sample;auto event = SecurityPolicyViolationEvent::create(HTML::EventNames::securitypolicyviolation, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object()));event->set_is_trusted(true);@@ -402,15 +402,15 @@ void Violation::report_a_violation(JS::Realm& realm)}// 4. If violation’s policy’s directive set contains a directive named "report-uri" directive:- if (auto report_uri_directive = m_policy->get_directive_by_name(Directives::Names::ReportUri)) {+ if (auto report_uri_directive = self.m_policy->get_directive_by_name(Directives::Names::ReportUri)) {// 1. If violation’s policy’s directive set contains a directive named "report-to", skip the remaining// substeps.- if (!m_policy->contains_directive_with_name(Directives::Names::ReportTo)) {+ if (!self.m_policy->contains_directive_with_name(Directives::Names::ReportTo)) {// 1. For each token of directive’s value:for (auto const& token : report_uri_directive->value()) {// 1. Let endpoint be the result of executing the URL parser with token as the input, and// violation’s url as the base URL.- auto endpoint = DOMURL::parse(token, url());+ auto endpoint = DOMURL::parse(token, self.url());// 2. If endpoint is not a valid URL, skip the remaining substeps.if (endpoint.has_value()) {@@ -466,7 +466,7 @@ void Violation::report_a_violation(JS::Realm& realm)// body// The result of executing § 5.3 Obtain the deprecated serialization of violation on// violation- request->set_body(obtain_the_deprecated_serialization(realm));+ request->set_body(self.obtain_the_deprecated_serialization(realm));// redirect mode// "error"@@ -479,7 +479,7 @@ void Violation::report_a_violation(JS::Realm& realm)}// 5. If violation's policy's directive set contains a directive named "report-to" directive:- if (auto report_to_directive = m_policy->get_directive_by_name(Directives::Names::ReportTo)) {+ if (auto report_to_directive = self.m_policy->get_directive_by_name(Directives::Names::ReportTo)) {(void)report_to_directive;dbgln("FIXME: Implement report-to directive in violation reporting");}diff --git a/Libraries/LibWeb/CookieStore/CookieStore.cpp b/Libraries/LibWeb/CookieStore/CookieStore.cppindex dc06c497a0a..2c5c2cfb63a 100644--- a/Libraries/LibWeb/CookieStore/CookieStore.cpp+++ b/Libraries/LibWeb/CookieStore/CookieStore.cpp@@ -153,10 +153,10 @@ static Optional<URL::URL> validate_cookie_store_mutation(WebIDL::Promise& promisstatic GC::Ref<CookieListCompletionSteps> create_cookie_list_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise, FirstItemOnly first_item_only){- return GC::Function<void(Vector<CookieListItem>)>::create(GC::Heap::the(), [global = GC::Ref { global }, promise, first_item_only](Vector<CookieListItem> cookie_list) mutable {+ return GC::create_function(GC::Heap::the(), GC::captures(global, promise, first_item_only), [](auto& global, auto& promise, auto& first_item_only, Vector<CookieListItem> cookie_list) {// AD-HOC: Queue a global task to perform the next steps// Spec issue: https://github.com/whatwg/cookiestore/issues/239- HTML::queue_global_task(HTML::Task::Source::Unspecified, global, GC::create_function(GC::Heap::the(), [promise, cookie_list = move(cookie_list), first_item_only]() {+ HTML::queue_global_task(HTML::Task::Source::Unspecified, global, GC::create_function(GC::Heap::the(), GC::captures(promise, move(cookie_list), first_item_only), [](auto& promise, auto& cookie_list, auto& first_item_only) {auto& realm = WebIDL::promise_realm(promise);HTML::TemporaryExecutionContext execution_context { realm };if (first_item_only == FirstItemOnly::Yes)@@ -167,15 +167,15 @@ static GC::Ref<CookieListCompletionSteps> create_cookie_list_completion_steps(JS});}-static GC::Ref<CookieMutationCompletionSteps> create_cookie_mutation_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise, Utf16View failure_message)+static GC::Ref<CookieMutationCompletionSteps> create_cookie_mutation_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise, Utf16String failure_message){- return GC::Function<void(bool)>::create(GC::Heap::the(), [global = GC::Ref { global }, promise, failure_message](bool result) {+ return GC::create_function(GC::Heap::the(), GC::captures(global, promise, move(failure_message)), [](auto& global, auto& promise, auto& failure_message, bool result) {// NB: The UI's notification of this mutation's cookie changes is handled from a deferred invocation scheduled while// waiting for its reply. Queue the task below after that, so the change event is fired first.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [global, promise, result, failure_message] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(global, promise, result, failure_message), [](auto& global, auto& promise, auto& result, auto& failure_message) {// AD-HOC: Queue a global task to perform the next steps// Spec issue: https://github.com/whatwg/cookiestore/issues/239- HTML::queue_global_task(HTML::Task::Source::Unspecified, global, GC::create_function(GC::Heap::the(), [promise, result, failure_message] {+ HTML::queue_global_task(HTML::Task::Source::Unspecified, global, GC::create_function(GC::Heap::the(), GC::captures(promise, result, failure_message), [](auto& promise, auto& result, auto& failure_message) {auto& realm = WebIDL::promise_realm(promise);HTML::TemporaryExecutionContext execution_context { realm };if (!result)@@ -288,9 +288,9 @@ GC::Ref<WebIDL::Promise> CookieStore::get(JS::Realm& realm, Utf16String name)void CookieStore::get(HTML::EnvironmentId environment_id, URL::URL url, Optional<Utf16String> name, GC::Ref<CookieListCompletionSteps> completion_steps){// 8. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, completion_steps, environment_id, url = move(url), name = move(name)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), move(name)), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& name) {// 1. Let list be the results of running query cookies with url and options["name"] with default null.- auto list = query_cookies(environment_id, url, name);+ auto list = self.query_cookies(environment_id, url, name);completion_steps->function()(move(list));}));}@@ -326,9 +326,9 @@ GC::Ref<WebIDL::Promise> CookieStore::get_all(JS::Realm& realm, Utf16String namevoid CookieStore::get_all(HTML::EnvironmentId environment_id, URL::URL url, Optional<Utf16String> name, GC::Ref<CookieListCompletionSteps> completion_steps){// 7. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, completion_steps, environment_id, url = move(url), name = move(name)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), move(name)), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& name) {// 1. Let list be the results of running query cookies with url and options["name"] with default null.- auto list = query_cookies(environment_id, url, name);+ auto list = self.query_cookies(environment_id, url, name);completion_steps->function()(move(list));}));}@@ -549,7 +549,7 @@ GC::Ref<WebIDL::Promise> CookieStore::set(JS::Realm& realm, CookieInit const& opif (!url.has_value())return promise;- set(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, u"Name, value, domain or path are malformed"sv));+ set(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name, value, domain or path are malformed"_utf16));return promise;}@@ -569,17 +569,17 @@ GC::Ref<WebIDL::Promise> CookieStore::set(JS::Realm& realm, Utf16String name, Utif (!url.has_value())return promise;- set(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, u"Name or value are malformed"sv));+ set(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name or value are malformed"_utf16));return promise;}void CookieStore::set(HTML::EnvironmentId environment_id, URL::URL url, CookieInit const& options, GC::Ref<CookieMutationCompletionSteps> completion_steps){// 6. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, completion_steps, environment_id, url = move(url), options = options]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), options), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& options) {// 1. Let r be the result of running set a cookie with url, options["name"], options["value"], options["expires"],// options["domain"], options["path"], options["sameSite"], and options["partitioned"].- auto result = set_a_cookie(environment_id, url, options.name, options.value, options.expires, options.domain, options.path, same_site_from_bindings(options.same_site), options.partitioned);+ auto result = self.set_a_cookie(environment_id, url, options.name, options.value, options.expires, options.domain, options.path, same_site_from_bindings(options.same_site), options.partitioned);completion_steps->function()(result);}));}@@ -613,7 +613,7 @@ GC::Ref<WebIDL::Promise> CookieStore::delete_(JS::Realm& realm, CookieStoreDeletif (!url.has_value())return promise;- delete_(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, u"Name is malformed"sv));+ delete_(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name is malformed"_utf16));return promise;}@@ -630,17 +630,17 @@ GC::Ref<WebIDL::Promise> CookieStore::delete_(JS::Realm& realm, Utf16String nameif (!url.has_value())return promise;- delete_(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, u"Name is malformed"sv));+ delete_(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name is malformed"_utf16));return promise;}void CookieStore::delete_(HTML::EnvironmentId environment_id, URL::URL url, CookieStoreDeleteOptions const& options, GC::Ref<CookieMutationCompletionSteps> completion_steps){// 6. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, completion_steps, environment_id, url = move(url), options = options]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), options), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& options) {// 1. Let r be the result of running delete a cookie with url, options["name"], options["domain"], options["path"],// and options["partitioned"].- auto result = delete_a_cookie(environment_id, url, options.name, options.domain, options.path, options.partitioned);+ auto result = self.delete_a_cookie(environment_id, url, options.name, options.domain, options.path, options.partitioned);completion_steps->function()(result);}));}@@ -666,6 +666,12 @@ struct CookieChange {Type type;};+}++GC_UNTRACED_CAPTURE(Web::CookieStore::CookieChange);++namespace Web::CookieStore {+// https://cookiestore.spec.whatwg.org/#observable-changesstatic Vector<CookieChange> observable_changes(Vector<HTTP::Cookie::Cookie> changes){@@ -739,7 +745,7 @@ void CookieStore::process_cookie_changes(JS::Object& relevant_global_object, Vec// 4. Queue a global task on the DOM manipulation task source given window to fire a change event named "change"// with changes at window’s CookieStore.- queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object, GC::create_function(GC::Heap::the(), [this, relevant_global_object = GC::Ref(relevant_global_object), changes = move(changes)]() {+ queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(*this, relevant_global_object, move(changes)), [](auto& self, auto& relevant_global_object, auto& changes) {auto& realm = HTML::relevant_realm(relevant_global_object);HTML::TemporaryExecutionContext execution_context { realm };// https://cookiestore.spec.whatwg.org/#fire-a-change-event@@ -762,7 +768,7 @@ void CookieStore::process_cookie_changes(JS::Object& relevant_global_object, Vecevent->set_cancelable(false);// 7. Dispatch event at target.- this->dispatch_event(event);+ self.dispatch_event(event);}));}diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.hindex 8eec3f9d85f..ba036758a8d 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h@@ -12,6 +12,7 @@#include <AK/String.h>#include <AK/Utf16String.h>#include <LibCrypto/BigInt/UnsignedBigInteger.h>+#include <LibGC/Forward.h>#include <LibGC/Ptr.h>#include <LibJS/Forward.h>#include <LibWeb/Crypto/CryptoBindings.h>@@ -964,3 +965,5 @@ WebIDL::ExceptionOr<ByteBuffer> base64_url_bytes_decode(JS::Realm&, Utf16StringWebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm&, Utf16String const& base64_url_string);}++GC_UNTRACED_CAPTURE(Web::Crypto::EncapsulatedBits);diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppindex f8b3f032265..245e8c0eb3f 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp@@ -161,7 +161,6 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encrypt(JS::Realm& realm, AlgorithmIdenti{auto& vm = realm.vm();auto& global = realm.global_object();- auto& heap = GC::Heap::the();// 1. Let algorithm and key be the algorithm and key parameters passed to the encrypt() method, respectively.@@ -184,13 +183,14 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encrypt(JS::Realm& realm, AlgorithmIdentiauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &global, &heap, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& data) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -216,7 +216,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encrypt(JS::Realm& realm, AlgorithmIdenti}// 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, cipher_text_bytes = cipher_text.release_value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, cipher_text.release_value()), [](auto& realm, auto& promise, auto& cipher_text_bytes) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 13. Let result be the result of creating an ArrayBuffer in realm, containing ciphertext.@@ -233,7 +233,6 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decrypt(JS::Realm& realm, AlgorithmIdenti{auto& vm = realm.vm();auto& global = realm.global_object();- auto& heap = GC::Heap::the();// 1. Let algorithm and key be the algorithm and key parameters passed to the decrypt() method, respectively.@@ -256,13 +255,14 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decrypt(JS::Realm& realm, AlgorithmIdentiauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &global, &heap, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& data) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -288,7 +288,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decrypt(JS::Realm& realm, AlgorithmIdenti}// 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, plain_text_bytes = plain_text.release_value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, plain_text.release_value()), [](auto& realm, auto& promise, auto& plain_text_bytes) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 13. Let result be the result of creating an ArrayBuffer in realm, containing plaintext.@@ -305,7 +305,6 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::digest(JS::Realm& realm, AlgorithmIdentif{auto& vm = realm.vm();auto& global = realm.global_object();- auto& heap = GC::Heap::the();// 1. Let algorithm be the algorithm parameter passed to the digest() method.@@ -329,13 +328,14 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::digest(JS::Realm& realm, AlgorithmIdentifauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &global, &heap, algorithm_object = normalized_algorithm.release_value(), promise, data_buffer = move(data_buffer)]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, move(data_buffer)), [](auto& realm, auto& global, auto& algorithm_object, auto& promise, auto& data_buffer) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -350,7 +350,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::digest(JS::Realm& realm, AlgorithmIdentif}// 10. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, digest_bytes = digest.release_value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, digest.release_value()), [](auto& realm, auto& promise, auto& digest_bytes) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 11. Let result be the result of creating an ArrayBuffer in realm, containing digest.@@ -380,7 +380,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::generate_key(JS::Realm& realm, AlgorithmIauto promise = WebIDL::create_promise(realm);// 5. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, extractable, key_usages = move(key_usages)]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, normalized_algorithm.release_value(), promise, extractable, move(key_usages)), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& extractable, auto& key_usages) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 6. If the following steps or referenced procedures say to throw an error, reject promise with// the returned error and then terminate the algorithm.@@ -469,7 +469,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::import_key(JS::Realm& realm, KeyFormat foauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, real_key_data = move(real_key_data), normalized_algorithm = normalized_algorithm.release_value(), promise, format, extractable, key_usages = move(key_usages), algorithm = move(algorithm)]() mutable -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, move(real_key_data), normalized_algorithm.release_value(), promise, format, extractable, move(key_usages)), [](auto& realm, auto& real_key_data, auto& normalized_algorithm, auto& promise, auto& format, auto& extractable, auto& key_usages) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// FIXME: 8. If the following steps or referenced procedures say to throw an error, queue a global task on the@@ -478,7 +478,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::import_key(JS::Realm& realm, KeyFormat fo// 9. Let result be the CryptoKey object that results from performing the import key operation// specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.- auto maybe_result = normalized_algorithm.methods->import_key(realm, *normalized_algorithm.parameter, format, real_key_data.downcast<CryptoKey::ImportKeyData>(), extractable, key_usages);+ auto maybe_result = normalized_algorithm.methods->import_key(realm, *normalized_algorithm.parameter, format, real_key_data.template downcast<CryptoKey::ImportKeyData>(), extractable, key_usages);if (maybe_result.is_error()) {WebIDL::reject_promise_with_exception(promise, maybe_result.release_error());return;@@ -516,7 +516,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::export_key(JS::Realm& realm, KeyFormat foauto promise = WebIDL::create_promise(realm);// 3. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, key, promise, format]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, key, promise, format), [](auto& realm, auto& key, auto& promise, auto& format) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 4. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.@@ -561,7 +561,6 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::sign(JS::Realm& realm, AlgorithmIdentifie{auto& vm = realm.vm();auto& global = realm.global_object();- auto& heap = GC::Heap::the();// 1. Let algorithm and key be the algorithm and key parameters passed to the sign() method, respectively.@@ -584,14 +583,15 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::sign(JS::Realm& realm, AlgorithmIdentifieauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &global, &heap, normalized_algorithm = normalized_algorithm.release_value(), promise, key, data = move(data)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& data) {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error; and then// terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -619,7 +619,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::sign(JS::Realm& realm, AlgorithmIdentifie}// 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, signature_bytes = signature.release_value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, signature.release_value()), [](auto& realm, auto& promise, auto& signature_bytes) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 13. Let result be the result of creating an ArrayBuffer in realm, containing signature.@@ -636,7 +636,6 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::verify(JS::Realm& realm, AlgorithmIdentif{auto& vm = realm.vm();auto& global = realm.global_object();- auto& heap = GC::Heap::the();// 1. Let algorithm and key be the algorithm and key parameters passed to the verify() method, respectively.@@ -665,14 +664,15 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::verify(JS::Realm& realm, AlgorithmIdentifauto promise = WebIDL::create_promise(realm);// 8. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &global, &heap, normalized_algorithm = normalized_algorithm.release_value(), promise, key, signature = move(signature), data = move(data)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(signature), move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& signature, auto& data) {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);// 9. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error; and then// terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -700,7 +700,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::verify(JS::Realm& realm, AlgorithmIdentif}// 13. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, verification_result = result.release_value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, result.release_value()), [](auto& realm, auto& promise, auto& verification_result) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 14. Resolve promise with result.@@ -727,7 +727,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::derive_bits(JS::Realm& realm, AlgorithmIdauto promise = WebIDL::create_promise(realm);// 5. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, base_key, length_optional]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, normalized_algorithm.release_value(), promise, base_key, length_optional), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& base_key, auto& length_optional) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 6. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.@@ -787,7 +787,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::derive_key(JS::Realm& realm, AlgorithmIdeauto promise = WebIDL::create_promise(realm);// 9. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, normalized_algorithm = normalized_algorithm.release_value(), promise, normalized_derived_key_algorithm_import = normalized_derived_key_algorithm_import.release_value(), normalized_derived_key_algorithm_length = normalized_derived_key_algorithm_length.release_value(), base_key = move(base_key), extractable, key_usages = move(key_usages)]() mutable -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, normalized_algorithm.release_value(), promise, normalized_derived_key_algorithm_import.release_value(), normalized_derived_key_algorithm_length.release_value(), move(base_key), extractable, move(key_usages)), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& normalized_derived_key_algorithm_import, auto& normalized_derived_key_algorithm_length, auto& base_key, auto& extractable, auto& key_usages) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 10. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.@@ -853,7 +853,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::wrap_key(JS::Realm& realm, KeyFormat form// 5. Let realm be the relevant realm of this.// 1. Let format, key, wrappingKey and algorithm be the format, key, wrappingKey and wrapAlgorithm parameters passed to the wrapKey() method, respectively.- StringView operation;+ String operation;auto normalized_algorithm_or_error = [&]() -> WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> {// 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "wrapKey".auto normalized_algorithm_wrap_key_or_error = normalize_an_algorithm(realm, algorithm, "wrapKey"_string);@@ -865,10 +865,10 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::wrap_key(JS::Realm& realm, KeyFormat formif (normalized_algorithm_encrypt_or_error.is_error())return normalized_algorithm_encrypt_or_error.release_error();- operation = "encrypt"sv;+ operation = "encrypt"_string;return normalized_algorithm_encrypt_or_error.release_value();} else {- operation = "wrapKey"sv;+ operation = "wrapKey"_string;return normalized_algorithm_wrap_key_or_error.release_value();}}();@@ -881,7 +881,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::wrap_key(JS::Realm& realm, KeyFormat formauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, normalized_algorithm = move(normalized_algorithm), promise, wrapping_key = move(wrapping_key), key = move(key), format, operation]() mutable -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, move(normalized_algorithm), promise, move(wrapping_key), move(key), format, operation), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& wrapping_key, auto& key, auto& format, auto& operation) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// FIXME: 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.@@ -985,7 +985,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::unwrap_key(JS::Realm& realm, KeyFormat fo// 1. Let format, unwrappingKey, algorithm, unwrappedKeyAlgorithm, extractable and usages, be the format, unwrappingKey, unwrapAlgorithm,// unwrappedKeyAlgorithm, extractable and keyUsages parameters passed to the unwrapKey() method, respectively.- StringView operation;+ String operation;auto normalized_algorithm_or_error = [&]() -> WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> {// 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "unwrapKey".auto normalized_algorithm_unwrap_key_or_error = normalize_an_algorithm(realm, algorithm, "unwrapKey"_string);@@ -997,10 +997,10 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::unwrap_key(JS::Realm& realm, KeyFormat foif (normalized_algorithm_decrypt_or_error.is_error())return normalized_algorithm_decrypt_or_error.release_error();- operation = "decrypt"sv;+ operation = "decrypt"_string;return normalized_algorithm_decrypt_or_error.release_value();} else {- operation = "unwrapKey"sv;+ operation = "unwrapKey"_string;return normalized_algorithm_unwrap_key_or_error.release_value();}}();@@ -1028,7 +1028,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::unwrap_key(JS::Realm& realm, KeyFormat foauto promise = WebIDL::create_promise(realm);// 10. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, normalized_algorithm = move(normalized_algorithm), promise, unwrapping_key = unwrapping_key, real_wrapped_key = move(real_wrapped_key), operation, format, extractable, key_usages = move(key_usages), normalized_key_algorithm = move(normalized_key_algorithm)]() mutable -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, move(normalized_algorithm), promise, unwrapping_key, move(real_wrapped_key), operation, format, extractable, move(key_usages), move(normalized_key_algorithm)), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& unwrapping_key, auto& real_wrapped_key, auto& operation, auto& format, auto& extractable, auto& key_usages, auto& normalized_key_algorithm) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// FIXME: 11. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.@@ -1160,12 +1160,13 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encapsulate_key(JS::Realm& realm, Algoritauto promise = WebIDL::create_promise(realm);// 8. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, [&realm, &global, &heap, normalized_encapsulation_algorithm = move(normalized_encapsulation_algorithm), encapsulation_key = encapsulation_key, promise, normalized_shared_key_algorithm = move(normalized_shared_key_algorithm), extractable, usages = move(key_usages)]() mutable -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, move(normalized_encapsulation_algorithm), encapsulation_key, promise, move(normalized_shared_key_algorithm), extractable, move(key_usages)), [](auto& realm, auto& global, auto& normalized_encapsulation_algorithm, auto& encapsulation_key, auto& promise, auto& normalized_shared_key_algorithm, auto& extractable, auto& usages) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 9. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -1217,10 +1218,11 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encapsulate_key(JS::Realm& realm, Algorit// 16. Let encapsulatedKey be a new EncapsulatedKey dictionary with sharedKey set to sharedKey and ciphertext set// to the ciphertext field of encapsulatedBits.- auto encapsulated_key = EncapsulatedKey { shared_key, encapsulated_bits.ciphertext };+ // NB: The task makes encapsulatedKey of the captured sharedKey and ciphertext, as the dictionary roots its key.// 17. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, encapsulated_key] mutable {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, shared_key, encapsulated_bits.ciphertext), [](auto& realm, auto& promise, auto& shared_key, auto& ciphertext) {+ auto encapsulated_key = EncapsulatedKey { shared_key, ciphertext };HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 18. Let result be the result of converting encapsulatedKey to an ECMAScript Object in realm, as defined by [WebIDL].auto maybe_result = ::Web::Crypto::encapsulated_key(realm, encapsulated_key);@@ -1263,12 +1265,13 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encapsulate_bits(JS::Realm& realm, Algoriauto promise = WebIDL::create_promise(realm);// 6. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, [&realm, &global, &heap, normalized_encapsulation_algorithm = move(normalized_encapsulation_algorithm), promise, encapsulation_key = encapsulation_key]() mutable -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, move(normalized_encapsulation_algorithm), promise, encapsulation_key), [](auto& realm, auto& global, auto& normalized_encapsulation_algorithm, auto& promise, auto& encapsulation_key) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -1298,7 +1301,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::encapsulate_bits(JS::Realm& realm, Algoriauto encapsulated_bits = maybe_encapsulated_bits.release_value();// 11. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, encapsulated_bits] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, encapsulated_bits), [](auto& realm, auto& promise, auto& encapsulated_bits) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 12. Let result be the result of converting encapsulatedBits to an ECMAScript Object in realm, as defined by [WebIDL].@@ -1358,12 +1361,13 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decapsulate_key(JS::Realm& realm, Algoritauto promise = WebIDL::create_promise(realm);// 9. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, [&realm, &global, &heap, normalized_decapsulation_algorithm = normalized_decapsulation_algorithm.release_value(), promise, decapsulation_key, cipher_text = move(cipher_text), normalized_shared_key_algorithm = normalized_shared_key_algorithm.release_value(), extractable, usages]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, normalized_decapsulation_algorithm.release_value(), promise, decapsulation_key, move(cipher_text), normalized_shared_key_algorithm.release_value(), extractable, usages), [](auto& realm, auto& global, auto& normalized_decapsulation_algorithm, auto& promise, auto& decapsulation_key, auto& cipher_text, auto& normalized_shared_key_algorithm, auto& extractable, auto& usages) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 10. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -1416,7 +1420,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decapsulate_key(JS::Realm& realm, Algoritshared_key->set_usages(normalized_key_usages(usages));// 17. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, shared_key] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, shared_key), [](auto& realm, auto& promise, auto& shared_key) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 18. Let result be the result of converting sharedKey to an ECMAScript Object in realm, as defined by [WebIDL].// 19. Resolve promise with result.@@ -1458,12 +1462,13 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decapsulate_bits(JS::Realm& realm, Algoriauto promise = WebIDL::create_promise(realm);// 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, [&realm, &global, &heap, normalized_decapsulation_algorithm = normalized_decapsulation_algorithm.release_value(), promise, decapsulation_key, cipher_text = move(cipher_text)]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, normalized_decapsulation_algorithm.release_value(), promise, decapsulation_key, move(cipher_text)), [](auto& realm, auto& global, auto& normalized_decapsulation_algorithm, auto& promise, auto& decapsulation_key, auto& cipher_text) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -1496,7 +1501,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::decapsulate_bits(JS::Realm& realm, Algoriauto const decapsulated_bits = maybe_decapsulated_bits.release_value();// 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, decapsulated_bits] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, decapsulated_bits), [](auto& realm, auto& promise, auto& decapsulated_bits) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 13. Let result be the result of creating an ArrayBuffer in realm, containing decapsulatedBits.// 14. Resolve promise with result.@@ -1584,14 +1589,15 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::get_public_key(JS::Realm& realm, GC::Ref<auto promise = WebIDL::create_promise(realm);// 6. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, [&realm, &global, &heap, promise, key, key_usages = move(key_usages), public_key_usages = *public_key_usages]() -> void {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, promise, key, move(key_usages), Vector<KeyUsage>(*public_key_usages)), [](auto& realm, auto& global, auto& promise, auto& key, auto& key_usages, auto& public_key_usages) -> void {+ auto& heap = GC::Heap::the();HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);// 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto// task source, given realm's global object, to reject promise with the returned error; and then terminate// the algorithm.auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, value = completion.value()] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(promise, value);}));@@ -1637,7 +1643,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::get_public_key(JS::Realm& realm, GC::Ref<// 16. Queue a global task on the crypto task source, given realm's global object, to perform the remaining// steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, [&realm, promise, public_key] {+ HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, public_key), [](auto& realm, auto& promise, auto& public_key) {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 17. Let result be the result of converting publicKey to an ECMAScript Object in realm, as defined bydiff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.h b/Libraries/LibWeb/Crypto/SubtleCrypto.hindex d28167e5837..3386e1cf72f 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.h+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.h@@ -9,6 +9,7 @@#include <AK/String.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>#include <LibJS/Forward.h>#include <LibJS/Runtime/Completion.h>#include <LibWeb/Bindings/Wrappable.h>@@ -80,3 +81,6 @@ WEB_API GC::Ref<WebIDL::Promise> encapsulate_key(JS::Realm&, Crypto::SubtleCryptWEB_API GC::Ref<WebIDL::Promise> decapsulate_key(JS::Realm&, Crypto::SubtleCrypto&, Crypto::AlgorithmIdentifier, GC::Ref<Crypto::CryptoKey>, WebIDL::BufferSourceVariant const&, Crypto::AlgorithmIdentifier, bool extractable, Vector<KeyUsage>);}++// NB: The methods and parameters of an algorithm are not cells, and keep any cell they use in a GC::Root.+GC_UNTRACED_CAPTURE(Web::Crypto::NormalizedAlgorithmAndParameter);diff --git a/Libraries/LibWeb/DOM/AbortSignal.cpp b/Libraries/LibWeb/DOM/AbortSignal.cppindex eb92d8e9b36..b125d120674 100644--- a/Libraries/LibWeb/DOM/AbortSignal.cpp+++ b/Libraries/LibWeb/DOM/AbortSignal.cpp@@ -47,14 +47,14 @@ AbortSignal::AbortSignal()}// https://dom.spec.whatwg.org/#abortsignal-add-Optional<AbortSignal::AbortAlgorithmID> AbortSignal::add_abort_algorithm(Function<void()> abort_algorithm)+Optional<AbortSignal::AbortAlgorithmID> AbortSignal::add_abort_algorithm(GC::Ref<GC::Function<void()>> abort_algorithm){// 1. If signal is aborted, then return.if (aborted())return {};// 2. Append algorithm to signal’s abort algorithms.- m_abort_algorithms.set(++m_next_abort_algorithm_id, GC::create_function(GC::Heap::the(), move(abort_algorithm)));+ m_abort_algorithms.set(++m_next_abort_algorithm_id, abort_algorithm);return m_next_abort_algorithm_id;}@@ -182,13 +182,13 @@ WebIDL::ExceptionOr<GC::Ref<AbortSignal>> AbortSignal::timeout(JS::Realm& realm,VERIFY(window_or_worker);// 3. Run steps after a timeout given global, "AbortSignal-timeout", milliseconds, and the following step:- window_or_worker->run_steps_after_a_timeout(milliseconds, [&realm, &global, signal]() {+ window_or_worker->run_steps_after_a_timeout(milliseconds, GC::create_function(GC::Heap::the(), GC::captures(realm, global, signal), [](auto& realm, auto& global, auto& signal) {// 1. Queue a global task on the timer task source given global to signal abort given signal and a new "TimeoutError" DOMException.- HTML::queue_global_task(HTML::Task::Source::TimerTask, global, GC::create_function(GC::Heap::the(), [&realm, &global, signal]() mutable {+ HTML::queue_global_task(HTML::Task::Source::TimerTask, global, GC::create_function(GC::Heap::the(), GC::captures(realm, global, signal), [](auto& realm, auto& global, auto& signal) {auto reason = throw_completion(realm, WebIDL::TimeoutError::create("Signal timed out"_utf16)).value();signal->signal_abort(reason, global);}));- });+ }));// 4. Return signal.return signal;@@ -280,12 +280,12 @@ JSValue web_dom_abort_signal_reason(DOM::AbortSignal* signal)bool web_dom_abort_signal_add_algorithm(DOM::AbortSignal* signal, JSObject* function, u64* id){GC::Ref<JS::FunctionObject> algorithm = as<JS::FunctionObject>(*JS::HostABI::object_from_abi(function));- auto algorithm_id = signal->add_abort_algorithm([algorithm] {+ auto algorithm_id = signal->add_abort_algorithm(GC::create_function(GC::Heap::the(), GC::captures(algorithm), [](GC::Ref<JS::FunctionObject> algorithm) {// NB: The algorithm cannot fail, but it can run into the abort of the script that it calls.auto& vm = algorithm->vm();auto result = JS::call(vm, *algorithm, JS::js_undefined());VERIFY(!result.is_error() || vm.interrupt_requested());- });+ }));if (!algorithm_id.has_value())return false;*id = algorithm_id.value();diff --git a/Libraries/LibWeb/DOM/AbortSignal.h b/Libraries/LibWeb/DOM/AbortSignal.hindex 514ed355ee0..7491ec262e7 100644--- a/Libraries/LibWeb/DOM/AbortSignal.h+++ b/Libraries/LibWeb/DOM/AbortSignal.h@@ -28,7 +28,7 @@ public:virtual ~AbortSignal() override = default;using AbortAlgorithmID = u64;- Optional<AbortAlgorithmID> add_abort_algorithm(Function<void()>);+ Optional<AbortAlgorithmID> add_abort_algorithm(GC::Ref<GC::Function<void()>>);void remove_abort_algorithm(AbortAlgorithmID);// https://dom.spec.whatwg.org/#dom-abortsignal-aborteddiff --git a/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp b/Libraries/LibWeb/DOM/AdoptedStyleSheets.cppindex bbac9137298..6545a9505e8 100644--- a/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp+++ b/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp@@ -27,7 +27,7 @@ GC::Ref<WebIDL::ObservableArray> create_adopted_style_sheets_list(Node& document{auto& realm = document_or_shadow_root.document().relevant_settings_object().realm();auto adopted_style_sheets = WebIDL::ObservableArray::create(realm);- adopted_style_sheets->set_on_set_an_indexed_value_callback([&document_or_shadow_root, adopted_style_sheets](u32 index, JS::Value& value) -> WebIDL::ExceptionOr<void> {+ adopted_style_sheets->set_on_set_an_indexed_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root, adopted_style_sheets), [](Node& document_or_shadow_root, GC::Ref<WebIDL::ObservableArray>& adopted_style_sheets, u32 index, JS::Value& value) -> WebIDL::ExceptionOr<void> {auto& vm = document_or_shadow_root.vm();auto style_sheet = CSS::css_style_sheet_from_value(value);if (!style_sheet)@@ -51,14 +51,14 @@ GC::Ref<WebIDL::ObservableArray> create_adopted_style_sheets_list(Node& documentCSS::record_stylesheet_attached(*style_sheet, document_or_shadow_root, before);CSS::Invalidation::invalidate_style_after_adopting_style_sheet(document_or_shadow_root, *style_sheet);return {};- });- adopted_style_sheets->set_on_delete_an_indexed_value_callback([&document_or_shadow_root](JS::Value value) -> WebIDL::ExceptionOr<void> {+ }));+ adopted_style_sheets->set_on_delete_an_indexed_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root), [](Node& document_or_shadow_root, JS::Value value) -> WebIDL::ExceptionOr<void> {auto* style_sheet = CSS::css_style_sheet_from_value(value);VERIFY(style_sheet);CSS::record_stylesheet_detached(*style_sheet, document_or_shadow_root);CSS::Invalidation::invalidate_style_after_removing_adopted_style_sheet(document_or_shadow_root, *style_sheet);return {};- });+ }));return adopted_style_sheets;}diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex ce16cdc85ee..37833ddb7a2 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -5320,7 +5320,7 @@ void Document::schedule_text_fragment_search_after_parser_progress(Badge<HTML::Hreturn;m_text_fragment_parser_progress_search_pending = true;- HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), GC::create_function(heap(), [document = GC::Ref { *this }] {+ HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), GC::create_function(heap(), GC::captures(GC::Ref { *this }), [](auto& document) {document->m_text_fragment_parser_progress_search_pending = false;if (!document->m_pending_text_directives.has_value()|| document->m_pending_text_directives->is_empty()@@ -6862,9 +6862,9 @@ struct DocumentLifecycleState : public GC::Cell {: remaining_children(remaining), document(document), finish_callback(finish_callback)- , timeout(Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(TIMEOUT_MS), GC::create_function(GC::Heap::the(), [this] {- if (remaining_children > 0)- dbgln("FIXME: Document unload/destruction timed out with {} remaining children", remaining_children);+ , timeout(Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(TIMEOUT_MS), GC::create_function(GC::Heap::the(), GC::captures(*this), [](DocumentLifecycleState& self) {+ if (self.remaining_children > 0)+ dbgln("FIXME: Document unload/destruction timed out with {} remaining children", self.remaining_children);}))){timeout->start();@@ -6916,9 +6916,9 @@ void Document::destroy_a_document_and_its_descendants(GC::Ptr<GC::Function<void(// 6. Queue a global task on the navigation and traversal task source given document's relevant global object to// perform the following steps:- auto finish_callback = GC::create_function(GC::Heap::the(), [document = this, after_all_destruction] {+ auto finish_callback = GC::create_function(GC::Heap::the(), GC::captures(*this, after_all_destruction), [](auto& document, auto& after_all_destruction) {// 1. Destroy document.- document->destroy();+ document.destroy();// 2. If afterAllDestruction was given, then run it.if (after_all_destruction)@@ -6941,14 +6941,14 @@ void Document::destroy_a_document_and_its_descendants(GC::Ptr<GC::Function<void(// the parent starts destruction. In that case there is no global task target; it is already// destroyed for the purposes of this algorithm.auto active_window = child_navigable->active_window();- auto increment_destroyed = GC::create_function(GC::Heap::the(), [destruction_state] { destruction_state->did_process_child(); });+ auto increment_destroyed = GC::create_function(GC::Heap::the(), GC::captures(destruction_state), [](auto& destruction_state) { destruction_state->did_process_child(); });if (!active_window) {increment_destroyed->function()();continue;}queue_global_task(HTML::Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window),- GC::create_function(GC::Heap::the(), [child_navigable, increment_destroyed] {+ GC::create_function(GC::Heap::the(), GC::captures(child_navigable, increment_destroyed), [](auto& child_navigable, auto& increment_destroyed) {// 1. Destroy a document and its descendants given childNavigable's active document and incrementDestroyed.if (auto active_document = child_navigable->active_document())active_document->destroy_a_document_and_its_descendants(increment_destroyed);@@ -7053,7 +7053,7 @@ void Document::abort_a_document_and_its_descendants()page().client().page_did_request_remote_document_abort(remote_navigable->id());continue;}- HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*descendant_navigable->active_window()), GC::create_function(GC::Heap::the(), [this, descendant_navigable] {+ HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*descendant_navigable->active_window()), GC::create_function(GC::Heap::the(), GC::captures(*this, descendant_navigable), [](Document& self, HTML::LocalNavigable* descendant_navigable) {// NOTE: This is not in the spec but we need to abort ongoing navigations in all descendant navigables.// See https://github.com/whatwg/html/issues/9711descendant_navigable->set_ongoing_navigation({});@@ -7063,7 +7063,7 @@ void Document::abort_a_document_and_its_descendants()// 2. If descendantNavigable's active document's salvageable is false, then set document's salvageable to false.if (!descendant_navigable->active_document()->m_salvageable)- m_salvageable = false;+ self.m_salvageable = false;}));}@@ -7799,7 +7799,7 @@ void Document::make_active()// NB: A document whose title element was parsed before it became active, such as an error page made from// inline content, hasn't reported its title yet. It's reported in a task, after the page has learned of// the new active document, which resets the title it shows.- HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), GC::create_function(heap(), [document = GC::Ref { *this }] {+ HTML::queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), GC::create_function(heap(), GC::captures(GC::Ref { *this }), [](auto& document) {auto navigable = document->navigable();if (!navigable || !navigable->is_top_level_traversable() || !document->is_active())return;@@ -7947,14 +7947,14 @@ void Document::queue_intersection_observer_task()m_intersection_observer_task_queued = true;// 3. Queue a task on the IntersectionObserver task source associated with the document's event loop to notify intersection observers.- HTML::queue_global_task(HTML::Task::Source::IntersectionObserver, HTML::relevant_global_object(*window), GC::create_function(GC::Heap::the(), [this]() {+ HTML::queue_global_task(HTML::Task::Source::IntersectionObserver, HTML::relevant_global_object(*window), GC::create_function(GC::Heap::the(), GC::captures(*this), [](Document& self) {// https://www.w3.org/TR/intersection-observer/#notify-intersection-observers// 1. Set document’s IntersectionObserverTaskQueued flag to false.- m_intersection_observer_task_queued = false;+ self.m_intersection_observer_task_queued = false;// 2. Let notify list be a list of all IntersectionObservers whose root is in the DOM tree of document.GC::RootVector<GC::Ref<IntersectionObserver::IntersectionObserver>> notify_list;- for (auto& observer : m_intersection_observers)+ for (auto& observer : self.m_intersection_observers)notify_list.append(observer);// 3. For each IntersectionObserver object observer in notify list, run these steps:@@ -8410,7 +8410,7 @@ void Document::shared_declarative_refresh_steps(Utf16View input, GC::Ptr<HTML::H// AD-HOC: Navigate from a task, so that the refresh comes after the tasks that "completely finish loading"// queued, such as the one that fires the load event at the container, as the refresh is due only// after the document has completely loaded.- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(*this), GC::create_function(heap(), [document = GC::Ref { *this }, has_meta_element, url_record] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(*this), GC::create_function(heap(), GC::captures(GC::Ref { *this }, has_meta_element, url_record), [](auto& document, auto& has_meta_element, auto& url_record) {if (has_meta_element && has_flag(document->active_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedAutomaticFeatures))return;@@ -8590,7 +8590,7 @@ void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHientry->url().serialize(),HighResolutionTime::current_high_resolution_time(relevant_global_object));hashchange_event->set_is_trusted(true);- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object, GC::create_function(GC::Heap::the(), [hashchange_event, &window]() {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(hashchange_event, window), [](auto& hashchange_event, auto& window) {window.dispatch_event(hashchange_event);}));}@@ -10250,7 +10250,7 @@ void Document::remove_replaced_animations()// Otherwise, queue a task to dispatch removeEvent at animation. The task source for this task is the DOM// manipulation task source.else {- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), [animation, remove_event]() {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(animation, remove_event), [](auto& animation, auto& remove_event) {animation->dispatch_event(remove_event);}));}@@ -12643,19 +12643,19 @@ void Document::view_transition_page_visibility_change_steps()// 1. Queue a global task on the DOM manipulation task source, given document’s relevant global object, to// perform the following steps:- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(*this), GC::create_function(GC::Heap::the(), [&] {- HTML::TemporaryExecutionContext context(relevant_settings_object());+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(*this), GC::create_function(GC::Heap::the(), GC::captures(*this), [](Document& self) {+ HTML::TemporaryExecutionContext context(self.relevant_settings_object());// 1. If document’s visibility state is "hidden", then:- if (m_visibility_state == HTML::VisibilityState::Hidden) {+ if (self.m_visibility_state == HTML::VisibilityState::Hidden) {// 1. If document’s active view transition is not null, then skip document’s active view transition with an// "InvalidStateError" DOMException.- if (m_active_view_transition) {- m_active_view_transition->skip_the_view_transition(WebIDL::InvalidStateError::create("The document's visibility state is \"hidden\"."_utf16));+ if (self.m_active_view_transition) {+ self.m_active_view_transition->skip_the_view_transition(WebIDL::InvalidStateError::create("The document's visibility state is \"hidden\"."_utf16));}}// 2. Otherwise, assert: active view transition is null.else {- VERIFY(!m_active_view_transition);+ VERIFY(!self.m_active_view_transition);}}));}diff --git a/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.h b/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.hindex 4e1c692b6ee..afba3b57539 100644--- a/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.h+++ b/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.h@@ -7,6 +7,7 @@#pragma once#include <AK/Noncopyable.h>+#include <LibGC/Forward.h>#include <LibGC/Weak.h>#include <LibWeb/Forward.h>@@ -34,3 +35,6 @@ private:};}++// NB: A delayer holds its document weakly, so a function can capture it without an edge to trace.+GC_UNTRACED_CAPTURE(Web::DOM::DocumentLoadEventDelayer);diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cppindex 6141b4414a8..9878807fa63 100644--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp@@ -56,13 +56,13 @@ static void add_pdf_viewer_ready_listener(DOM::Document& document, GC::Ref<Fetchauto js_response = Fetch::Response::create(response, Fetch::Headers::Guard::Response);auto listener_function = JS::NativeFunction::create(- realm, [&document, js_response](JS::VM&) mutable -> JS::ThrowCompletionOr<JS::Value> {+ realm, GC::create_function(GC::Heap::the(), GC::captures(document, js_response), [](DOM::Document& document, GC::Ref<Fetch::Response>& js_response, JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {DOM::CustomEventInit init;auto& realm = document.relevant_settings_object().realm();init.detail = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { js_response });document.dispatch_event(*DOM::CustomEvent::create("ladybirdpdf"_fly_string, init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(document))));return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &realm);auto callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*listener_function, realm);document.add_event_listener_without_options("ladybirdviewerready"_utf16_fly_string, *DOM::IDLEventListener::create(*callback));@@ -151,7 +151,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_html_document(HTML::Naviauto mime_type = Fetch::Infrastructure::extract_mime_type(navigation_params.response->header_list());auto url = navigation_params.response->url().value();auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, source->bytes(), mime_type);- document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), [parser, url] {+ document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), GC::captures(parser, url), [](auto& parser, auto& url) {parser->run(url);}));}@@ -216,7 +216,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigif (auto maybe_encoding = type.parameters().get("charset"sv); maybe_encoding.has_value())content_encoding = *maybe_encoding;- auto process_body = GC::create_function(GC::Heap::the(), [document, url = navigation_params.response->url().value(), response_header_list = navigation_params.response->header_list(), content_encoding = move(content_encoding), mime = type](ByteBuffer data) {+ auto process_body = GC::create_function(GC::Heap::the(), GC::captures(document, navigation_params.response->url().value(), navigation_params.response->header_list(), move(content_encoding)), [](auto& document, auto& url, auto& response_header_list, auto& content_encoding, ByteBuffer data) {auto encoding = determine_xml_encoding(data, content_encoding.has_value() ? Optional<StringView> { content_encoding->bytes_as_string_view() } : OptionalNone {});// Once the character encoding is established, the document's character encoding must be set to that character encoding.@@ -230,7 +230,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigconvert_to_xml_error_document(document, Utf16String::formatted("Failed to decode XML document: {}", source.error()));return;}- auto run_xml_parser = [document, url, response_header_list, source_string = source.release_value()] {+ auto run_xml_parser = GC::create_function(GC::Heap::the(), GC::captures(document, url, response_header_list, source.release_value()), [](auto& document, auto& url, auto& response_header_list, auto& source_string) {XML::Parser parser(source_string, { .preserve_cdata = true, .preserve_comments = true, .resolve_named_html_entity = resolve_named_html_entity });XMLDocumentBuilder builder { *document };auto result = parser.parse_with_listener(builder);@@ -243,11 +243,11 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_xml_document(HTML::Navigconvert_to_xml_error_document(document, "Failed to parse XML document: not namespace-well-formed"_utf16);}HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);- };+ });if (document->ready_to_run_scripts()) {- run_xml_parser();+ run_xml_parser->function()();} else {- document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), move(run_xml_parser)));+ document->set_deferred_parser_start(run_xml_parser);}});@@ -290,7 +290,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_text_document(HTML::Navi// load event to be fired.// FIXME: Parse as we receive the document data, instead of waiting for the whole document to be fetched first.auto container_document = navigation_params.navigable ? navigation_params.navigable->container_document() : nullptr;- auto process_body = GC::create_function(GC::Heap::the(), [document, container_document, url = navigation_params.response->url().value(), response_header_list = navigation_params.response->header_list(), mime = type](ByteBuffer data) {+ auto process_body = GC::create_function(GC::Heap::the(), GC::captures(document, container_document, navigation_params.response->url().value(), navigation_params.response->header_list(), type), [](auto& document, auto& container_document, auto& url, auto& response_header_list, auto& mime, ByteBuffer data) {// The rules for how to convert the bytes of the plain text document into actual characters, and the rules for// actually rendering the text to the user, are defined by the specifications for the computed MIME type of the// resource (i.e., type).@@ -302,7 +302,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_text_document(HTML::Naviencoding = HTML::run_encoding_sniffing_algorithm(document, data, mime, container_document).encoding;dbgln_if(HTML_PARSER_DEBUG, "The encoding sniffing algorithm returned encoding '{}'", encoding);- auto run_text_parser = [document, data = move(data), url, response_header_list, encoding = move(encoding)] {+ auto run_text_parser = GC::create_function(GC::Heap::the(), GC::captures(document, move(data), url, response_header_list, move(encoding)), [](auto& document, auto& data, auto& url, auto& response_header_list, auto& encoding) {auto parser = HTML::HTMLParser::create_with_open_input_stream(document);parser->tokenizer().update_insertion_point();@@ -323,11 +323,11 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_text_document(HTML::Navi// 5. User agents may add content to the head element of document, e.g., linking to a style sheet, providing// script, or giving the document a title.// NB: Leave the head empty so the document text consists only of the response body.- };+ });if (document->ready_to_run_scripts()) {- run_text_parser();+ run_text_parser->function()();} else {- document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), move(run_text_parser)));+ document->set_deferred_parser_start(run_text_parser);}});@@ -424,7 +424,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::Nav// AD-HOC: document has no navigable until it is activated, so media queries would be evaluated against an empty// viewport. Process the link headers in a networking task instead, which runs once document is fully active// and before the task that step 8 queues when the body has been read.- HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), GC::create_function(GC::Heap::the(), [document, response_header_list = navigation_params.response->header_list(), url = navigation_params.response->url().value()] {+ HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(document, navigation_params.response->header_list(), navigation_params.response->url().value()), [](auto& document, auto& response_header_list, auto& url) {HTML::HTMLLinkElement::process_link_headers(document, response_header_list, url, HTML::HTMLLinkElement::LinkHeaderPhase::Media);}));@@ -432,7 +432,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::Nav// FIXME: We should not need to force the media file to load before saying that parsing has completed!// However, if we don't, then we get stuck in HTMLParser::the_end() waiting for the media file to load, which// never happens.- auto stop_parsing = GC::create_function(GC::Heap::the(), [document] { HTML::HTMLParser::the_end(document, nullptr); });+ auto stop_parsing = GC::create_function(GC::Heap::the(), GC::captures(document), [](auto& document) { HTML::HTMLParser::the_end(document, nullptr); });if (image_element) {// INTEROP: All major engines present the image from the response that was navigated to rather than fetching it// again. A second fetch would be subject to the Content-Security-Policy of that same response.@@ -440,7 +440,7 @@ static WebIDL::ExceptionOr<GC::Ref<DOM::Document>> load_media_document(HTML::Nav} else {navigation_params.response->body()->fully_read(realm,- GC::create_function(GC::Heap::the(), [stop_parsing](ByteBuffer) { stop_parsing->function()(); }),+ GC::create_function(GC::Heap::the(), GC::captures(stop_parsing), [](auto& stop_parsing, ByteBuffer) { stop_parsing->function()(); }),GC::create_function(GC::Heap::the(), [](JS::Value) { }),GC::Ref { realm.global_object() });}@@ -474,12 +474,12 @@ static GC::Ref<DOM::Document> load_pdf_document(HTML::NavigationParams const& naadd_pdf_viewer_ready_listener(document, GC::Ref(*navigation_params.response));- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [document, pdf_url] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(document, pdf_url), [](auto& document, auto& pdf_url) {auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, *viewer_bytes);if (document->ready_to_run_scripts()) {parser->run(pdf_url);} else {- document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), [parser, pdf_url] {+ document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), GC::captures(parser, pdf_url), [](auto& parser, auto& pdf_url) {parser->run(pdf_url);}));}diff --git a/Libraries/LibWeb/DOM/DocumentObserver.cpp b/Libraries/LibWeb/DOM/DocumentObserver.cppindex 1a19ddd8dfc..3ef650d6418 100644--- a/Libraries/LibWeb/DOM/DocumentObserver.cpp+++ b/Libraries/LibWeb/DOM/DocumentObserver.cpp@@ -69,44 +69,29 @@ void DocumentObserver::retarget_for_adoption(GC::Ref<Document> new_document)}}-void DocumentObserver::set_document_became_active(Function<void()> callback)+void DocumentObserver::set_document_became_active(GC::Ptr<GC::Function<void()>> callback){- if (callback)- m_document_became_active = GC::create_function(GC::Heap::the(), move(callback));- else- m_document_became_active = nullptr;+ m_document_became_active = callback;}-void DocumentObserver::set_document_became_inactive(Function<void()> callback)+void DocumentObserver::set_document_became_inactive(GC::Ptr<GC::Function<void()>> callback){- if (callback)- m_document_became_inactive = GC::create_function(GC::Heap::the(), move(callback));- else- m_document_became_inactive = nullptr;+ m_document_became_inactive = callback;}-void DocumentObserver::set_document_completely_loaded(Function<void()> callback)+void DocumentObserver::set_document_completely_loaded(GC::Ptr<GC::Function<void()>> callback){- if (callback)- m_document_completely_loaded = GC::create_function(GC::Heap::the(), move(callback));- else- m_document_completely_loaded = nullptr;+ m_document_completely_loaded = callback;}-void DocumentObserver::set_document_readiness_observer(Function<void(HTML::DocumentReadyState)> callback)+void DocumentObserver::set_document_readiness_observer(GC::Ptr<GC::Function<void(HTML::DocumentReadyState)>> callback){- if (callback)- m_document_readiness_observer = GC::create_function(GC::Heap::the(), move(callback));- else- m_document_readiness_observer = nullptr;+ m_document_readiness_observer = callback;}-void DocumentObserver::set_document_visibility_state_observer(Function<void(HTML::VisibilityState)> callback)+void DocumentObserver::set_document_visibility_state_observer(GC::Ptr<GC::Function<void(HTML::VisibilityState)>> callback){- if (callback)- m_document_visibility_state_observer = GC::create_function(GC::Heap::the(), move(callback));- else- m_document_visibility_state_observer = nullptr;+ m_document_visibility_state_observer = callback;}}diff --git a/Libraries/LibWeb/DOM/DocumentObserver.h b/Libraries/LibWeb/DOM/DocumentObserver.hindex a8ed4f5a0c0..8d630bb099d 100644--- a/Libraries/LibWeb/DOM/DocumentObserver.h+++ b/Libraries/LibWeb/DOM/DocumentObserver.h@@ -25,19 +25,19 @@ public:static GC::Ref<DocumentObserver> create(Document&);[[nodiscard]] GC::Ptr<GC::Function<void()>> document_became_active() const { return m_document_became_active; }- void set_document_became_active(Function<void()>);+ void set_document_became_active(GC::Ptr<GC::Function<void()>>);[[nodiscard]] GC::Ptr<GC::Function<void()>> document_became_inactive() const { return m_document_became_inactive; }- void set_document_became_inactive(Function<void()>);+ void set_document_became_inactive(GC::Ptr<GC::Function<void()>>);[[nodiscard]] GC::Ptr<GC::Function<void()>> document_completely_loaded() const { return m_document_completely_loaded; }- void set_document_completely_loaded(Function<void()>);+ void set_document_completely_loaded(GC::Ptr<GC::Function<void()>>);[[nodiscard]] GC::Ptr<GC::Function<void(HTML::DocumentReadyState)>> document_readiness_observer() const { return m_document_readiness_observer; }- void set_document_readiness_observer(Function<void(HTML::DocumentReadyState)>);+ void set_document_readiness_observer(GC::Ptr<GC::Function<void(HTML::DocumentReadyState)>>);[[nodiscard]] GC::Ptr<GC::Function<void(HTML::VisibilityState)>> document_visibility_state_observer() const { return m_document_visibility_state_observer; }- void set_document_visibility_state_observer(Function<void(HTML::VisibilityState)>);+ void set_document_visibility_state_observer(GC::Ptr<GC::Function<void(HTML::VisibilityState)>>);[[nodiscard]] GC::Ptr<GC::Function<void(bool)>> document_page_showing_observer() const { return m_document_page_showing_observer; }diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex a86fece8121..93f4ef0f92f 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -806,11 +806,11 @@ void Element::download_the_hyperlink(Optional<Utf16String> hyperlink_suffix, HTM// 4. Handle as a download response with subject's node navigable and null.auto controller_holder = Fetch::Infrastructure::FetchControllerHolder::create();Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = [navigable = GC::Ref { *navigable }, url, proposed_filename = move(proposed_filename), interface_origin = document().origin(), controller_holder](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *navigable }, url, move(proposed_filename), document().origin(), controller_holder), [](auto& navigable, auto& url, auto& proposed_filename, auto& interface_origin, auto& controller_holder, GC::Ref<Fetch::Infrastructure::ResponseView> response) {if (response->is_network_error())return;navigable->handle_as_a_download(response->unsafe_response(), url, controller_holder->controller(), proposed_filename, interface_origin);- };+ });auto& relevant_realm = document().relevant_settings_object().realm();controller_holder->set_controller(Fetch::Fetching::fetch(relevant_realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input))));}@@ -2830,13 +2830,13 @@ Utf16FlyString Element::make_html_uppercased_qualified_name() const}// https://html.spec.whatwg.org/multipage/webappapis.html#queue-an-element-task-HTML::TaskID Element::queue_an_element_task(HTML::Task::Source source, Function<void()> steps, GC::Ptr<GC::Function<void()>> discard_steps)+HTML::TaskID Element::queue_an_element_task(HTML::Task::Source source, GC::Ref<GC::Function<void()>> steps, GC::Ptr<GC::Function<void()>> discard_steps){// 1. Let global be element's relevant global object.auto& global = HTML::relevant_global_object(*this);// 2. Queue a global task given source, global, and steps.- return HTML::queue_global_task(source, global, GC::create_function(GC::Heap::the(), move(steps)), HTML::Task::Priority::Normal, discard_steps);+ return HTML::queue_global_task(source, global, steps, HTML::Task::Priority::Normal, discard_steps);}// https://html.spec.whatwg.org/multipage/syntax.html#void-elements@@ -4969,8 +4969,8 @@ void Element::enqueue_an_element_on_the_appropriate_element_queue()// 4. Queue a microtask to perform the following steps:// NOTE: `this` is protected by GC::Function- HTML::queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), [this]() {- auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*this).custom_element_reactions_stack;+ HTML::queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), GC::captures(*this), [](Element& self) {+ auto& reactions_stack = HTML::relevant_similar_origin_window_agent(self).custom_element_reactions_stack;// 1. Invoke custom element reactions in reactionsStack's backup element queue.HTML::invoke_custom_element_reactions(reactions_stack.backup_element_queue);diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.hindex 608c253a998..8abacfaaa14 100644--- a/Libraries/LibWeb/DOM/Element.h+++ b/Libraries/LibWeb/DOM/Element.h@@ -686,8 +686,7 @@ public:bool child_style_uses_tree_counting_function() const { return m_child_style_uses_tree_counting_function; }void set_child_style_uses_tree_counting_function() { m_child_style_uses_tree_counting_function = true; }- // NOTE: The function is wrapped in a GC::HeapFunction immediately.- HTML::TaskID queue_an_element_task(HTML::Task::Source, Function<void()>, GC::Ptr<GC::Function<void()>> discard_steps = {});+ HTML::TaskID queue_an_element_task(HTML::Task::Source, GC::Ref<GC::Function<void()>>, GC::Ptr<GC::Function<void()>> discard_steps = {});bool is_void_element() const;bool serializes_as_void() const;diff --git a/Libraries/LibWeb/DOM/EventTarget.cpp b/Libraries/LibWeb/DOM/EventTarget.cppindex 0d9229aa6c6..2a8e9fd1129 100644--- a/Libraries/LibWeb/DOM/EventTarget.cpp+++ b/Libraries/LibWeb/DOM/EventTarget.cpp@@ -502,10 +502,10 @@ void EventTarget::add_an_event_listener(DOMEventListener& listener)// 6. If listener’s signal is not null, then add the following abort steps to it:if (listener.signal) {// NOTE: `this` and `listener` are protected by AbortSignal using GC::HeapFunction.- (void)listener.signal->add_abort_algorithm([this, &listener] {+ (void)listener.signal->add_abort_algorithm(GC::create_function(GC::Heap::the(), GC::captures(*this, listener), [](EventTarget& self, DOMEventListener& listener) {// 1. Remove an event listener with eventTarget and listener.- remove_an_event_listener(listener);- });+ self.remove_an_event_listener(listener);+ }));}}@@ -885,8 +885,8 @@ void EventTarget::activate_event_handler(Utf16FlyString const& name, HTML::Event// 4. Let callback be the result of creating a Web IDL EventListener instance representing a reference to a function of one argument that executes the steps of the event handler processing algorithm, given eventTarget, name, and its argument.// The EventListener's callback context can be arbitrary; it does not impact the steps of the event handler processing algorithm. [DOM]- // NB: The listener below is eventTarget's and has type name, so the event it is called with gives both. This leaves- // the function no captures for the garbage collector to scan conservatively.+ // NB: The listener below is eventTarget's and has type name, so the event it is called with gives both, and the+ // function needs no captures.auto callback_function = JS::NativeFunction::create(realm, +[](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {// The event dispatcher should only call this with one argument.diff --git a/Libraries/LibWeb/DOM/MutationObserver.cpp b/Libraries/LibWeb/DOM/MutationObserver.cppindex d3c60a194fa..2ae3349b76b 100644--- a/Libraries/LibWeb/DOM/MutationObserver.cpp+++ b/Libraries/LibWeb/DOM/MutationObserver.cpp@@ -247,7 +247,12 @@ void queue_mutation_observer_microtask(HTML::SimilarOriginWindowAgent& surroundisurrounding_agent.mutation_observer_microtask_queued = true;// 3. Queue a microtask to notify mutation observers.- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [&surrounding_agent]() {+ // NB: The surrounding agent is the agent of the main thread, the only one that has a DOM, so the microtask finds it+ // there.+ VERIFY(&surrounding_agent == &Bindings::main_thread_similar_origin_window_agent());+ HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [] {+ auto& surrounding_agent = Bindings::main_thread_similar_origin_window_agent();+// https://dom.spec.whatwg.org/#notify-mutation-observers// 1. Set the surrounding agent’s mutation observer microtask queued to false.surrounding_agent.mutation_observer_microtask_queued = false;diff --git a/Libraries/LibWeb/DOM/SelectionchangeEventDispatching.h b/Libraries/LibWeb/DOM/SelectionchangeEventDispatching.hindex bea66b05d44..9e10793892f 100644--- a/Libraries/LibWeb/DOM/SelectionchangeEventDispatching.h+++ b/Libraries/LibWeb/DOM/SelectionchangeEventDispatching.h@@ -43,7 +43,7 @@ void schedule_a_selectionchange_event(T& target, Document& document)// 2. Queue a task on the user interaction task source to fire a selectionchange event on// target.- queue_global_task(HTML::Task::Source::UserInteraction, relevant_global_object(document), GC::create_function(GC::Heap::the(), [&] {+ queue_global_task(HTML::Task::Source::UserInteraction, relevant_global_object(document), GC::create_function(GC::Heap::the(), GC::captures(target, document), [](auto& target, auto& document) {fire_a_selectionchange_event(target, document);}));}diff --git a/Libraries/LibWeb/DOM/StyleElementBase.cpp b/Libraries/LibWeb/DOM/StyleElementBase.cppindex a480b33b46e..fce95c2e5e5 100644--- a/Libraries/LibWeb/DOM/StyleElementBase.cpp+++ b/Libraries/LibWeb/DOM/StyleElementBase.cpp@@ -248,7 +248,7 @@ void StyleElementBase::finished_loading_critical_subresources(AnyFailed any_failsuccess = false;// 4. Queue an element task on the networking task source given element and the following steps:- element.queue_an_element_task(HTML::Task::Source::Networking, [&element, success, style_sheet_update_generation] {+ element.queue_an_element_task(HTML::Task::Source::Networking, GC::create_function<void()>(GC::Heap::the(), GC::captures(element, success, style_sheet_update_generation), [](Element& element, auto& success, auto& style_sheet_update_generation) {// AD-HOC: If the associated stylesheet has been replaced or removed since this task was queued, ignore it.auto* style_element_base = as_if<StyleElementBase>(element);if (!style_element_base || style_element_base->m_style_sheet_update_generation != style_sheet_update_generation)@@ -281,7 +281,7 @@ void StyleElementBase::finished_loading_critical_subresources(AnyFailed any_fail// 4. Unblock rendering on element.element.unblock_rendering();style_element_base->m_associated_css_style_sheet_load_is_pending_for_script_blocking = false;- });+ }));m_document_load_event_delayer.clear();}diff --git a/Libraries/LibWeb/Editing/SpellCheckController.cpp b/Libraries/LibWeb/Editing/SpellCheckController.cppindex 53ea43daaa9..c7e25a5263e 100644--- a/Libraries/LibWeb/Editing/SpellCheckController.cpp+++ b/Libraries/LibWeb/Editing/SpellCheckController.cpp@@ -20,6 +20,9 @@#include <LibWeb/Page/Page.h>#include <LibWeb/Selection/Selection.h>+// NB: A request holds its nodes weakly, so a function can capture it without an edge to trace.+GC_UNTRACED_CAPTURE(Web::Editing::SpellCheckController::Request);+namespace Web::Editing {// https://html.spec.whatwg.org/multipage/interaction.html#spelling-and-grammar-checking@@ -179,7 +182,7 @@ void SpellCheckController::schedule_typing_check()if (m_typing_check_scheduled)return;m_typing_check_scheduled = true;- HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }), [](auto& document) {if (auto strong_document = document.ptr()) {strong_document->spell_check_controller().run_typing_check();strong_document->page().notify_spell_check_progress();@@ -217,7 +220,7 @@ void SpellCheckController::schedule_exempt_word_check()if (m_exempt_word_check_scheduled)return;m_exempt_word_check_scheduled = true;- HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }), [](auto& document) {if (auto strong_document = document.ptr()) {strong_document->spell_check_controller().run_exempt_word_check();strong_document->page().notify_spell_check_progress();@@ -362,7 +365,7 @@ void SpellCheckController::send(Request request)++m_requests_in_flight;if (request.kind == RequestKind::Typing)m_typing_check_in_flight = true;- m_document->page().request_spell_check(text, GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }, request = move(request)](Vector<SpellingError> errors) {+ m_document->page().request_spell_check(text, GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }, move(request)), [](auto& document, auto& request, Vector<SpellingError> errors) {auto strong_document = document.ptr();if (!strong_document)return;diff --git a/Libraries/LibWeb/Editing/WritingSuggestionController.cpp b/Libraries/LibWeb/Editing/WritingSuggestionController.cppindex e38daf8c584..0635ba05e4e 100644--- a/Libraries/LibWeb/Editing/WritingSuggestionController.cpp+++ b/Libraries/LibWeb/Editing/WritingSuggestionController.cpp@@ -17,6 +17,9 @@#include <LibWeb/Layout/LayoutRustBridge.h>#include <LibWeb/Page/Page.h>+// NB: A request holds its nodes weakly, so a function can capture it without an edge to trace.+GC_UNTRACED_CAPTURE(Web::Editing::WritingSuggestionController::Request);+namespace Web::Editing {WritingSuggestionController::WritingSuggestionController(DOM::Document& document)@@ -215,7 +218,7 @@ void WritingSuggestionController::schedule_selection_check()if (m_selection_check_scheduled)return;m_selection_check_scheduled = true;- HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }), [](auto& document) {if (auto strong_document = document.ptr()) {strong_document->writing_suggestion_controller().run_selection_check();strong_document->page().notify_writing_suggestion_progress();@@ -248,7 +251,7 @@ void WritingSuggestionController::schedule_request()if (m_request_scheduled)return;m_request_scheduled = true;- HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }), [](auto& document) {if (auto strong_document = document.ptr()) {strong_document->writing_suggestion_controller().run_request();strong_document->page().notify_writing_suggestion_progress();@@ -283,7 +286,7 @@ void WritingSuggestionController::run_request()++m_requests_in_flight;auto sent_text = request.sent_text;auto caret_offset = request.caret_offset;- page.request_writing_suggestion(sent_text, caret_offset, GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }, request = move(request)](Optional<WritingSuggestion> suggestion) {+ page.request_writing_suggestion(sent_text, caret_offset, GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }, move(request)), [](auto& document, auto& request, Optional<WritingSuggestion> suggestion) {auto strong_document = document.ptr();if (!strong_document)return;diff --git a/Libraries/LibWeb/Fetch/FetchMethod.cpp b/Libraries/LibWeb/Fetch/FetchMethod.cppindex 5c2deabca72..c02de62d32a 100644--- a/Libraries/LibWeb/Fetch/FetchMethod.cpp+++ b/Libraries/LibWeb/Fetch/FetchMethod.cpp@@ -123,7 +123,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi// 12. Set controller to the result of calling fetch given request and processResponse given response being these// steps:- auto process_response = [locally_aborted, promise_capability, request_object, response_object_holder, controller_holder, &relevant_realm](GC::Ref<Infrastructure::ResponseView> response) {+ auto process_response = GC::create_function(GC::Heap::the(), GC::captures(locally_aborted, promise_capability, request_object, response_object_holder, controller_holder, relevant_realm), [](auto& locally_aborted, auto& promise_capability, auto& request_object, auto& response_object_holder, auto& controller_holder, auto& relevant_realm, GC::Ref<Infrastructure::ResponseView> response) {// 1. If locallyAborted is true, then abort these steps.if (locally_aborted->value())return;@@ -161,9 +161,9 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindirelevant_realm,GC::Ref { *response_object_holder->response_object });WebIDL::resolve_promise(relevant_realm, promise_capability, response_value);- };+ });Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = move(process_response);+ fetch_algorithms_input.process_response = process_response;// AD-HOC: Request holds its body's source and length, and requestObject its stream, which fetching reads for a// body without a source. Its reader is acquired here, not when fetching reads the stream, so that script// cannot lock the stream first.@@ -172,7 +172,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindicontroller_holder->set_controller(Fetching::fetch(realm, request, Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input))));// 11. Add the following abort steps to requestObject’s signal:- (void)request_object->signal()->add_abort_algorithm([locally_aborted, controller_holder, promise_capability, request_object, response_object_holder, &relevant_realm] {+ (void)request_object->signal()->add_abort_algorithm(GC::create_function(GC::Heap::the(), GC::captures(locally_aborted, controller_holder, promise_capability, request_object, response_object_holder, relevant_realm), [](auto& locally_aborted, auto& controller_holder, auto& promise_capability, auto& request_object, auto& response_object_holder, auto& relevant_realm) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Request object signal's abort algorithm called");// 1. Set locallyAborted to true.@@ -189,7 +189,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi// 4. Abort the fetch() call with p, request, responseObject, and requestObject’s signal’s abort reason.abort_fetch(*promise_capability, request_object, response_object_holder->response_object, request_object->signal()->reason());- });+ }));// 13. Return p.return promise_capability;diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex cf860e959e2..b12d817bd69 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -735,7 +735,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// 2. Let corsWithPreflightResponse be the result of running HTTP fetch given fetchParams and true.auto cors_with_preflight_response = http_fetch(realm, *fetch_params, MakeCORSPreflight::Yes);- cors_with_preflight_response->when_loaded([request, returned_pending_response](NonnullRefPtr<Infrastructure::Response> cors_with_preflight_response) {+ cors_with_preflight_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(request, returned_pending_response), [](NonnullRefPtr<Infrastructure::Request>& request, GC::Ref<PendingResponse>& returned_pending_response, NonnullRefPtr<Infrastructure::Response> cors_with_preflight_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' cors_with_preflight_response load callback");// 3. If corsWithPreflightResponse is a network error, then clear cache entries using request.if (cors_with_preflight_response->is_network_error()) {@@ -744,7 +744,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// 4. Return corsWithPreflightResponse.returned_pending_response->resolve(cors_with_preflight_response);- });+ }));return returned_pending_response;}@@ -776,7 +776,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamif (!response) {pending_response = get_response->function()();}- pending_response->when_loaded([&realm, fetch_params, controller, request, response, response_was_null = !response](NonnullRefPtr<Infrastructure::Response> resolved_response) mutable {+ pending_response->when_loaded(GC::create_function<void(NonnullRefPtr<Infrastructure::Response>)>(GC::Heap::the(), GC::captures(realm, fetch_params, controller, request, response, !response), [](auto& realm, NonnullRefPtr<Infrastructure::FetchParams const>& fetch_params, GC::Ref<Infrastructure::FetchController>& controller, NonnullRefPtr<Infrastructure::Request>& request, RefPtr<Infrastructure::Response>& response, bool& response_was_null, NonnullRefPtr<Infrastructure::Response> resolved_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' pending_response load callback");// AD-HOC: From here on, response processing captures fetchParams's task destination as it schedules work@@ -930,7 +930,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParamelse {fetch_response_handover(realm, *fetch_params, controller, *response);}- });+ }));}));return GC::Ptr<PendingResponse> {};@@ -1034,7 +1034,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constauto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();// 2. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:- controller->set_report_timing_steps([response, fetch_params, timing_info, unsafe_end_time, timing_reported](JS::Object& global) mutable {+ controller->set_report_timing_steps(GC::create_function(GC::Heap::the(), GC::captures(response, fetch_params, timing_info, unsafe_end_time, timing_reported), [](auto& response, auto& fetch_params, auto& timing_info, auto& unsafe_end_time, auto& timing_reported, JS::Object& global) {// NB: Network completion and consuming the response body can both request a timing report.if (timing_reported->value())return;@@ -1089,7 +1089,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constauto initiator_type = Infrastructure::initiator_type_to_string(fetch_params->request()->initiator_type().value());ResourceTiming::PerformanceResourceTiming::mark_resource_timing(timing_info, utf16_string_from_url_ascii(fetch_params->request()->url().serialize()), initiator_type, global, cache_state, body_info, response_status);}- });+ }));});// NB: Share step 3 of processResponseEndOfBodyTask with the network-completion timing path.@@ -1760,7 +1760,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParamif (pending_preflight_response) {pending_actual_response = PendingResponse::create(fetch_params);- pending_preflight_response->when_loaded([returned_pending_response, pending_actual_response, fetch_main_content](NonnullRefPtr<Infrastructure::Response> preflight_response) {+ pending_preflight_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(returned_pending_response, pending_actual_response, fetch_main_content), [](auto& returned_pending_response, auto& pending_actual_response, auto& fetch_main_content, NonnullRefPtr<Infrastructure::Response> preflight_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_preflight_response load callback");// 2. If preflightResponse is a network error, then return preflightResponse.@@ -1770,11 +1770,11 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam}auto pending_main_content_response = fetch_main_content->function()();- pending_main_content_response->when_loaded([pending_actual_response](NonnullRefPtr<Infrastructure::Response> main_content_response) {+ pending_main_content_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(pending_actual_response), [](auto& pending_actual_response, NonnullRefPtr<Infrastructure::Response> main_content_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_main_content_response load callback");pending_actual_response->resolve(main_content_response);- });- });+ }));+ }));} else {pending_actual_response = fetch_main_content->function()();}@@ -1782,7 +1782,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParampending_actual_response = PendingResponse::create(fetch_params, Infrastructure::Response::create());}- pending_actual_response->when_loaded([&realm, fetch_params = NonnullRefPtr { fetch_params }, controller = fetch_params.controller(), request, response, internal_response, returned_pending_response, response_was_null = !response](NonnullRefPtr<Infrastructure::Response> resolved_actual_response) mutable {+ pending_actual_response->when_loaded(GC::create_function<void(NonnullRefPtr<Infrastructure::Response>)>(GC::Heap::the(), GC::captures(realm, NonnullRefPtr { fetch_params }, fetch_params.controller(), request, response, internal_response, returned_pending_response, !response), [](auto& realm, NonnullRefPtr<Infrastructure::FetchParams const>& fetch_params, GC::Ref<Infrastructure::FetchController>& controller, NonnullRefPtr<Infrastructure::Request>& request, RefPtr<Infrastructure::Response>& response, RefPtr<Infrastructure::Response>& internal_response, GC::Ref<PendingResponse>& returned_pending_response, bool& response_was_null, NonnullRefPtr<Infrastructure::Response> resolved_actual_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_actual_response load callback");if (response_was_null) {response = internal_response = resolved_actual_response;@@ -1844,9 +1844,9 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// 1. If request’s mode is "navigate", then set fetchParams’s controller’s next manual redirect steps// to run HTTP-redirect fetch given fetchParams and response.if (request->mode() == Infrastructure::Request::Mode::Navigate) {- controller->set_next_manual_redirect_steps([&realm, fetch_params, response] {+ controller->set_next_manual_redirect_steps(GC::create_function(GC::Heap::the(), GC::captures(realm, fetch_params, response), [](auto& realm, auto& fetch_params, auto& response) {(void)http_redirect_fetch(realm, *fetch_params, *response);- });+ }));}// 2. Otherwise, set response to an opaque-redirect filtered response whose internal response is// internalResponse.@@ -1865,14 +1865,14 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam}if (inner_pending_response) {- inner_pending_response->when_loaded([returned_pending_response](NonnullRefPtr<Infrastructure::Response> response) {+ inner_pending_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(returned_pending_response), [](auto& returned_pending_response, NonnullRefPtr<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' inner_pending_response load callback");returned_pending_response->resolve(response);- });+ }));} else {returned_pending_response->resolve(*response);}- });+ }));// 7. Return response.// NOTE: Typically internalResponse’s body’s stream is still being enqueued to after returning.@@ -2106,7 +2106,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, Inif (action == WebDriver::BiDi::NetworkContinuationAction::ProvideCredentials) {stop_discarded_response_body(*fetch_params->controller(), *continued_response);auto pending_response = http_network_or_cache_fetch(realm, *fetch_params, IsAuthenticationFetch::Yes);- pending_response->when_loaded([returned_pending_response](auto response) { returned_pending_response->resolve(response); });+ pending_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(returned_pending_response), [](GC::Ref<PendingResponse>& returned_pending_response, NonnullRefPtr<Infrastructure::Response> response) { returned_pending_response->resolve(response); }));} else if (first_is_one_of(action, WebDriver::BiDi::NetworkContinuationAction::CancelAuthentication, WebDriver::BiDi::NetworkContinuationAction::Fail, WebDriver::BiDi::NetworkContinuationAction::ProvideResponse)) {returned_pending_response->resolve(*continued_response);} else {@@ -2133,7 +2133,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, Ininner_pending_response = http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes);}- inner_pending_response->when_loaded([&realm, fetch_params = NonnullRefPtr { fetch_params }, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](NonnullRefPtr<Infrastructure::Response> response) {+ inner_pending_response->when_loaded(GC::create_function<void(NonnullRefPtr<Infrastructure::Response>)>(GC::Heap::the(), GC::captures(realm, NonnullRefPtr { fetch_params }, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch), [](auto& realm, NonnullRefPtr<Infrastructure::FetchParams const>& fetch_params, NonnullRefPtr<Infrastructure::Request>& request, GC::Ref<PendingResponse>& returned_pending_response, IsAuthenticationFetch& is_authentication_fetch, IsNewConnectionFetch& is_new_connection_fetch, NonnullRefPtr<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");// 15. If response’s status is 407, then:if (response->status() == 407) {@@ -2183,7 +2183,7 @@ static void process_http_network_or_cache_response(JS::Object& global_object, Ininner_pending_response = http_network_or_cache_fetch(realm, *fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes);}- inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](NonnullRefPtr<Infrastructure::Response> response) {+ inner_pending_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(returned_pending_response, is_authentication_fetch), [](auto& returned_pending_response, auto& is_authentication_fetch, NonnullRefPtr<Infrastructure::Response> response) {// 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given// realm.if (is_authentication_fetch == IsAuthenticationFetch::Yes) {@@ -2191,8 +2191,8 @@ static void process_http_network_or_cache_response(JS::Object& global_object, In}returned_pending_response->resolve(response);- });- });+ }));+ }));}// https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch@@ -2223,7 +2223,7 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&auto returned_pending_response = PendingResponse::create(fetch_params);- pending_forward_response->when_loaded([&realm, fetch_params = NonnullRefPtr { fetch_params }, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](NonnullRefPtr<Infrastructure::Response> resolved_forward_response) mutable {+ pending_forward_response->when_loaded(GC::create_function<void(NonnullRefPtr<Infrastructure::Response>)>(GC::Heap::the(), GC::captures(realm, NonnullRefPtr { fetch_params }, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, !response, http_cache), [](auto& realm, NonnullRefPtr<Infrastructure::FetchParams const>& fetch_params, RefPtr<Infrastructure::Response>& response, RefPtr<Infrastructure::Response>& stored_response, NonnullRefPtr<Infrastructure::Request>& http_request, NonnullRefPtr<Infrastructure::FetchParams const>& http_fetch_params, GC::Ref<PendingResponse>& returned_pending_response, IsAuthenticationFetch& is_authentication_fetch, IsNewConnectionFetch& is_new_connection_fetch, HTTP::Cookie::IncludeCredentials& include_credentials, bool& response_was_null, RefPtr<HTTP::MemoryCache>& http_cache, NonnullRefPtr<Infrastructure::Response> resolved_forward_response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");if (response_was_null) {auto forward_response = resolved_forward_response;@@ -2278,7 +2278,7 @@ static GC::Ref<PendingResponse> continue_http_network_or_cache_fetch(JS::Object&WebDriver::BiDi::network_response_started(*http_fetch_params, *response);}process_http_network_or_cache_response(realm.global_object(), *fetch_params, *http_request, *response, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials);- });+ }));// 18. Return response.// NOTE: Typically response’s body’s stream is still being enqueued to after returning.@@ -2607,7 +2607,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastrureturn;}auto pending_response = continue_http_network_or_cache_fetch(realm.global_object(), *fetch_params, *http_fetch_params, action == WebDriver::BiDi::NetworkContinuationAction::Continue ? response : continued_response, stored_response, http_cache, is_authentication_fetch, is_new_connection_fetch, include_credentials);- pending_response->when_loaded([returned_pending_response](auto response) { returned_pending_response->resolve(response); });+ pending_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(returned_pending_response), [](GC::Ref<PendingResponse>& returned_pending_response, NonnullRefPtr<Infrastructure::Response> response) { returned_pending_response->resolve(response); }));}),request);return returned_pending_response;@@ -2702,7 +2702,7 @@ NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::Fereturn transport;}-GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Infrastructure::Response& response, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey transfer_lease, RefPtr<Infrastructure::FetchTimingInfo> timing_info, Function<void(Optional<StringView> error)> on_network_settled)+GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Infrastructure::Response& response, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey transfer_lease, RefPtr<Infrastructure::FetchTimingInfo> timing_info, GC::Ref<GC::Function<void(Optional<StringView> error)>> on_network_settled){if (!ResourceLoader::is_initialized())return {};@@ -2727,7 +2727,7 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Iauto network_transport = Engine::NetworkTransportHandle::create(*request);delivery_gate->attach_transport(network_transport);// The observer hears the body's end at most once.- auto network_settled = GC::make_root(GC::create_function(GC::Heap::the(), move(on_network_settled)));+ auto network_settled = GC::make_root(on_network_settled);network_transport->set_on_teardown([delivery_gate, channel, network_settled](Requests::Request::TeardownReason reason) {tear_down_network_body(*delivery_gate, *channel, reason);// A body that moves to another owner is reported there.@@ -3140,7 +3140,7 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::auto preflight_response = http_network_or_cache_fetch(realm, preflight_fetch_params);- preflight_response->when_loaded([request = fetch_params.request(), returned_pending_response, preflight_controller = GC::Ref { *preflight_controller }, preflight_fetch_params](NonnullRefPtr<Infrastructure::Response> response) {+ preflight_response->when_loaded(GC::create_function(GC::Heap::the(), GC::captures(fetch_params.request(), returned_pending_response, GC::Ref { *preflight_controller }, preflight_fetch_params), [](NonnullRefPtr<Infrastructure::Request>& request, GC::Ref<PendingResponse>& returned_pending_response, GC::Ref<Infrastructure::FetchController>& preflight_controller, NonnullRefPtr<Infrastructure::FetchParams>& preflight_fetch_params, NonnullRefPtr<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");if (WebDriver::BiDi::network_events_enabled()) {@@ -3286,7 +3286,7 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::// 8. Otherwise, return a network error.returned_pending_response->resolve(Infrastructure::Response::network_error("CORS-preflight check failed"_string));- });+ }));return returned_pending_response;}diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.hindex e6a9b386f7b..e6110f7ae0d 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h@@ -10,6 +10,7 @@#include <AK/Forward.h>#include <AK/RefPtr.h>#include <LibCore/ImmutableBytes.h>+#include <LibGC/Forward.h>#include <LibGC/Ptr.h>#include <LibHTTP/Cookie/IncludeCredentials.h>#include <LibHTTP/Forward.h>@@ -59,7 +60,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm&, Infrastructure::FetchParams const&);// on_network_settled runs at most once: when the network completes the body, or with an error when the body fails// or is stopped.-GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm&, Infrastructure::Response&, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey, RefPtr<Infrastructure::FetchTimingInfo>, Function<void(Optional<StringView> error)> on_network_settled);+GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm&, Infrastructure::Response&, Optional<Utf16String> const& request_server_top_level_site, Requests::RequestTransferLeaseKey, RefPtr<Infrastructure::FetchTimingInfo>, GC::Ref<GC::Function<void(Optional<StringView> error)>> on_network_settled);// Stopping the transport also cancels the channel.WEB_API NonnullRefPtr<Engine::WholeBodyTransport> create_whole_body_transport(Engine::FetchBodyDeliveryGate&, Engine::FetchByteChannel&);void set_sec_fetch_dest_header(Infrastructure::Request&);diff --git a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cpp b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cppindex 8c23b3a04d7..32f06307217 100644--- a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.cpp@@ -52,7 +52,7 @@ void PendingResponse::visit_edges(JS::Cell::Visitor& visitor)void PendingResponse::when_loaded(Callback callback){VERIFY(!m_callback);- m_callback = GC::create_function(GC::Heap::the(), move(callback));+ m_callback = callback;if (m_response)run_callback();}diff --git a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.h b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.hindex 9b0dd80aa58..3f9de12b819 100644--- a/Libraries/LibWeb/Fetch/Fetching/PendingResponse.h+++ b/Libraries/LibWeb/Fetch/Fetching/PendingResponse.h@@ -22,7 +22,7 @@ class PendingResponse : public JS::Cell {GC_DECLARE_ALLOCATOR(PendingResponse);public:- using Callback = Function<void(NonnullRefPtr<Infrastructure::Response>)>;+ using Callback = GC::Ref<GC::Function<void(NonnullRefPtr<Infrastructure::Response>)>>;[[nodiscard]] static GC::Ref<PendingResponse> create(GC::Ref<Infrastructure::FetchController>);[[nodiscard]] static GC::Ref<PendingResponse> create(GC::Ref<Infrastructure::FetchController>, NonnullRefPtr<Infrastructure::Response>);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cppindex 014b5c56c3e..8caffa67504 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp@@ -16,26 +16,14 @@ GC_DEFINE_ALLOCATOR(FetchAlgorithms);GC::Ref<FetchAlgorithms> FetchAlgorithms::create(Input input){- // NB: An algorithm the caller left out has no function, which the fetch steps check for.- auto make_function = [](auto&& function) -> GC::Ptr<GC::Function<typename RemoveCVReference<decltype(function)>::FunctionType>> {- if (!function)- return nullptr;- return GC::create_function(GC::Heap::the(), move(function));- };- auto process_request_body_chunk_length = make_function(move(input.process_request_body_chunk_length));- auto process_request_end_of_body = make_function(move(input.process_request_end_of_body));- auto process_early_hints_response = make_function(move(input.process_early_hints_response));- auto process_response = make_function(move(input.process_response));- auto process_response_end_of_body = make_function(move(input.process_response_end_of_body));- auto process_response_consume_body = make_function(move(input.process_response_consume_body));return GC::Heap::the().allocate<FetchAlgorithms>(input.body_intent,- process_request_body_chunk_length,- process_request_end_of_body,- process_early_hints_response,- process_response,- process_response_end_of_body,- process_response_consume_body,+ input.process_request_body_chunk_length,+ input.process_request_end_of_body,+ input.process_early_hints_response,+ input.process_response,+ input.process_response_end_of_body,+ input.process_response_consume_body,move(input.request_body_reader));}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.hindex f7927cadbb1..0690998e83b 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h@@ -53,12 +53,12 @@ public:}Engine::BodyIntent body_intent;- ProcessRequestBodyChunkLengthFunction process_request_body_chunk_length;- ProcessRequestEndOfBodyFunction process_request_end_of_body;- ProcessEarlyHintsResponseFunction process_early_hints_response;- ProcessResponseFunction process_response;- ProcessResponseEndOfBodyFunction process_response_end_of_body;- ProcessResponseConsumeBodyFunction process_response_consume_body;+ ProcessRequestBodyChunkLengthHeapFunction process_request_body_chunk_length;+ ProcessRequestEndOfBodyHeapFunction process_request_end_of_body;+ ProcessEarlyHintsResponseHeapFunction process_early_hints_response;+ ProcessResponseHeapFunction process_response;+ ProcessResponseEndOfBodyHeapFunction process_response_end_of_body;+ ProcessResponseConsumeBodyHeapFunction process_response_consume_body;Optional<RequestBodyReader> request_body_reader;};diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex 80d52671597..04ee2d83602 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -113,14 +113,14 @@ void FetchController::set_body_transport(Engine::FetchBodyDeliveryGate::Transporm_body_transport = body_transport;}-void FetchController::set_report_timing_steps(Function<void(JS::Object&)> report_timing_steps)+void FetchController::set_report_timing_steps(GC::Ref<GC::Function<void(JS::Object&)>> report_timing_steps){- m_report_timing_steps = GC::create_function(GC::Heap::the(), move(report_timing_steps));+ m_report_timing_steps = report_timing_steps;}-void FetchController::set_next_manual_redirect_steps(Function<void()> next_manual_redirect_steps)+void FetchController::set_next_manual_redirect_steps(GC::Ref<GC::Function<void()>> next_manual_redirect_steps){- m_next_manual_redirect_steps = GC::create_function(GC::Heap::the(), move(next_manual_redirect_steps));+ m_next_manual_redirect_steps = next_manual_redirect_steps;}// https://fetch.spec.whatwg.org/#finalize-and-report-timingdiff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.hindex 8c23cd7e7c1..477633b8142 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h@@ -47,8 +47,8 @@ public:[[nodiscard]] WeakPtr<FetchControllerRegistry> const& registry() const { return m_registry; }[[nodiscard]] FetchControlBlock& control_block() const { return *m_control_block; }- void set_report_timing_steps(Function<void(JS::Object&)> report_timing_steps);- void set_next_manual_redirect_steps(Function<void()> next_manual_redirect_steps);+ void set_report_timing_steps(GC::Ref<GC::Function<void(JS::Object&)>> report_timing_steps);+ void set_next_manual_redirect_steps(GC::Ref<GC::Function<void()>> next_manual_redirect_steps);[[nodiscard]] State state() const { return m_control_block->state(); }[[nodiscard]] RefPtr<FetchTimingInfo> full_timing_info() const { return m_control_block->full_timing_info(); }diff --git a/Libraries/LibWeb/FileAPI/Blob.cpp b/Libraries/LibWeb/FileAPI/Blob.cppindex 8734eddb13b..d05c49aba65 100644--- a/Libraries/LibWeb/FileAPI/Blob.cpp+++ b/Libraries/LibWeb/FileAPI/Blob.cpp@@ -149,7 +149,7 @@ static GC::Ref<Streams::ReadableStream> get_stream(JS::Realm& realm, ReadonlyBytauto bytes = MUST(ByteBuffer::copy(blob_bytes));// 2. Queue a global task on the file reading task source given blob’s relevant global object to perform the following steps:- HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), GC::create_function(GC::Heap::the(), [&realm, stream, bytes = move(bytes)]() {+ HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(realm, stream, move(bytes)), [](auto& realm, auto& stream, auto& bytes) {HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If bytes is failure, then error stream with a failure reason and abort these steps.@@ -204,10 +204,10 @@ void* web_blob_get_stream(void* realm, ReadonlyBytes blob_bytes)WebIDL::Promise* web_blob_text(void* realm, ReadonlyBytes blob_bytes){auto& js_realm = *static_cast<JS::Realm*>(realm);- auto& vm = js_realm.vm();auto promise = read_all_blob_bytes(js_realm, blob_bytes);- promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&vm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {+ promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), GC::captures(js_realm), [](auto& js_realm, JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {+ JS::VM& vm = js_realm.vm();auto const& object = first_argument.as_object();VERIFY(is<JS::ArrayBuffer>(object));auto const& array_buffer = static_cast<JS::ArrayBuffer const&>(object);@@ -224,7 +224,7 @@ WebIDL::Promise* web_blob_array_buffer(void* realm, ReadonlyBytes blob_bytes)auto& js_realm = *static_cast<JS::Realm*>(realm);auto promise = read_all_blob_bytes(js_realm, blob_bytes);- promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&js_realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {+ promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), GC::captures(js_realm), [](auto& js_realm, JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {auto const& object = first_argument.as_object();VERIFY(is<JS::ArrayBuffer>(object));auto const& array_buffer = static_cast<JS::ArrayBuffer const&>(object);@@ -240,7 +240,7 @@ WebIDL::Promise* web_blob_bytes(void* realm, ReadonlyBytes blob_bytes)auto& js_realm = *static_cast<JS::Realm*>(realm);auto promise = read_all_blob_bytes(js_realm, blob_bytes);- promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), [&js_realm](JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {+ promise = WebIDL::upon_fulfillment(*promise, GC::create_function(GC::Heap::the(), GC::captures(js_realm), [](auto& js_realm, JS::Value first_argument) -> WebIDL::ExceptionOr<JS::Value> {auto& object = first_argument.as_object();VERIFY(is<JS::ArrayBuffer>(object));auto& array_buffer = static_cast<JS::ArrayBuffer&>(object);diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 987701849a3..6357d5e49f7 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -14,12 +14,16 @@#include <LibGfx/Forward.h>#include <LibIPC/Forward.h>#include <LibJS/Forward.h>+#include <LibURL/Forward.h>#include <LibWeb/Bindings/Forward.h>#include <LibWeb/CSS/StyleEngineIdentifiers.h>#include <LibWeb/CSS/StyleRecordID.h>#include <LibWeb/Export.h>#include <LibWebCommon/Forward.h>+GC_UNTRACED_CAPTURE(URL::URL);+GC_UNTRACED_CAPTURE(URL::Origin);+namespace Web {class AutoScrollHandler;diff --git a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cpp b/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cppindex e529acedbfc..421870e87d4 100644--- a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cpp+++ b/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cpp@@ -37,8 +37,8 @@ static void resolve_haptics_promise(WebIDL::Promise const& promise, GamepadHaptistatic GC::Ref<GamepadHapticsCompletionSteps> create_queued_haptics_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise){- return GC::Function<void(GamepadHapticsResult)>::create(GC::Heap::the(), [global = GC::Ref { global }, promise](GamepadHapticsResult result) {- HTML::queue_global_task(HTML::Task::Source::Gamepad, global, GC::create_function(GC::Heap::the(), [promise, result] {+ return GC::create_function(GC::Heap::the(), GC::captures(global, promise), [](auto& global, auto& promise, GamepadHapticsResult result) {+ HTML::queue_global_task(HTML::Task::Source::Gamepad, global, GC::create_function(GC::Heap::the(), GC::captures(promise, result), [](auto& promise, auto& result) {resolve_haptics_promise(promise, result);}));});@@ -46,7 +46,7 @@ static GC::Ref<GamepadHapticsCompletionSteps> create_queued_haptics_completion_sstatic GC::Ref<GamepadHapticsCompletionSteps> create_haptics_completion_steps(GC::Ref<WebIDL::Promise> promise){- return GC::Function<void(GamepadHapticsResult)>::create(GC::Heap::the(), [promise](GamepadHapticsResult result) {+ return GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, GamepadHapticsResult result) {resolve_haptics_promise(promise, result);});}@@ -92,10 +92,10 @@ GamepadHapticActuator::GamepadHapticActuator(HTML::Window& window, GC::Ref<Gamep, m_window(window), m_document_became_hidden_observer(document_became_hidden_observer){- m_document_became_hidden_observer->set_document_visibility_state_observer([this](HTML::VisibilityState visibility_state) {+ m_document_became_hidden_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self, HTML::VisibilityState visibility_state) {if (visibility_state == HTML::VisibilityState::Hidden)- document_became_hidden();- });+ self.document_became_hidden();+ }));}GamepadHapticActuator::~GamepadHapticActuator() = default;@@ -255,20 +255,20 @@ void GamepadHapticActuator::play_effect(GamepadHapticEffectType type, GamepadEff// NOTE: Unused.// 8. Do the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, type, params] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, type, params), [](auto& self, auto& type, auto& params) {// 1. Issue a haptic effect to the actuator with type, params, and the playEffectTimestamp.- issue_haptic_effect(type, params, GC::create_function(GC::Heap::the(), [this] {+ self.issue_haptic_effect(type, params, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {// 2. When the effect completes, if this.[[playingEffectPromise]] is not null, queue a global task on the// gamepad task source with the relevant global object of this to run the following steps:- if (m_playing_effect_completion_steps) {- auto completion_steps = GC::Ref { *m_playing_effect_completion_steps };+ if (self.m_playing_effect_completion_steps) {+ auto completion_steps = GC::Ref { *self.m_playing_effect_completion_steps };// 2. Resolve this.[[playingEffectPromise]] with "complete".completion_steps->function()(GamepadHapticsResult::Complete);// 3. Set this.[[playingEffectPromise]] to null.- m_playing_effect_completion_steps = nullptr;- clear_playing_effect_timers();+ self.m_playing_effect_completion_steps = nullptr;+ self.clear_playing_effect_timers();}}));}));@@ -280,20 +280,20 @@ void GamepadHapticActuator::reset(GC::Ref<GamepadHapticsCompletionSteps> reset_c{// 4. If this.[[playingEffectPromise]] is not null, do the following steps in parallel:if (m_playing_effect_completion_steps) {- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, reset_completion_steps] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, reset_completion_steps), [](auto& self, auto& reset_completion_steps) {// 1. Let effectPromise be this.[[playingEffectPromise]].- auto effect_completion_steps = m_playing_effect_completion_steps;+ auto effect_completion_steps = self.m_playing_effect_completion_steps;// 2. Stop haptic effects on this's gamepad's actuator.- stop_haptic_effects();+ self.stop_haptic_effects();// 3. If the effect has been successfully stopped, do:// AD-HOC: The stop command is sent to the UI process without waiting for a reply, so it is taken to have// succeeded, matching other engines.// 1. If effectPromise and this.[[playingEffectPromise]] are still the same,// set this.[[playingEffectPromise]] to null.- if (effect_completion_steps == m_playing_effect_completion_steps)- m_playing_effect_completion_steps = nullptr;+ if (effect_completion_steps == self.m_playing_effect_completion_steps)+ self.m_playing_effect_completion_steps = nullptr;// 2. Queue a global task on the gamepad task source with the relevant global object of this to resolve// effectPromise with "preempted".@@ -339,26 +339,27 @@ void GamepadHapticActuator::issue_haptic_effect(GamepadHapticEffectType type, Ga// for more precise playback timing when params.startDelay is not 0.0. The user agent MAY modify the effect to// increase compatibility. For example, an effect intended for a rumble motor may be transformed into a// waveform-based effect for a device that supports waveform haptics but lacks rumble motors.- m_playing_effect_timer = Platform::Timer::create_single_shot(heap, AK::Duration::from_milliseconds(static_cast<int>(params.start_delay)), GC::create_function(heap, [this, type, params, on_complete, &heap] {- auto& page = m_window->page();+ m_playing_effect_timer = Platform::Timer::create_single_shot(heap, AK::Duration::from_milliseconds(static_cast<int>(params.start_delay)), GC::create_function(heap, GC::captures(*this, type, params, on_complete), [](auto& self, auto& type, auto& params, auto& on_complete) {+ auto& heap = GC::Heap::the();+ auto& page = self.m_window->page();auto first_magnitude = type == GamepadHapticEffectType::DualRumble ? params.strong_magnitude : params.left_trigger;auto second_magnitude = type == GamepadHapticEffectType::DualRumble ? params.weak_magnitude : params.right_trigger;- page.client().page_did_play_gamepad_effect(m_gamepad->handle(),+ page.client().page_did_play_gamepad_effect(self.m_gamepad->handle(),gamepad_effect_for_type(type,static_cast<u16>(first_magnitude * NumericLimits<u16>::max()),static_cast<u16>(second_magnitude * NumericLimits<u16>::max()),static_cast<u32>(params.duration)));- m_playing_effect_timer = Platform::Timer::create_single_shot(heap, AK::Duration::from_milliseconds(params.duration), GC::create_function(heap, [this, type, on_complete] {+ self.m_playing_effect_timer = Platform::Timer::create_single_shot(heap, AK::Duration::from_milliseconds(params.duration), GC::create_function(heap, GC::captures(self, type, on_complete), [](auto& self, auto& type, auto& on_complete) {// Explicitly stop the rumble before completing, ensuring the stop signal is sent synchronously.- auto& page = m_window->page();+ auto& page = self.m_window->page();- page.client().page_did_play_gamepad_effect(m_gamepad->handle(), gamepad_effect_for_type(type, 0, 0, 0));+ page.client().page_did_play_gamepad_effect(self.m_gamepad->handle(), gamepad_effect_for_type(type, 0, 0, 0));on_complete->function()();}));- m_playing_effect_timer->start();+ self.m_playing_effect_timer->start();}));m_playing_effect_timer->start();diff --git a/Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp b/Libraries/LibWeb/Gamepad/NavigatorGamepad.cppindex f0190c04835..3ebd0505420 100644--- a/Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp+++ b/Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp@@ -116,7 +116,7 @@ void NavigatorGamepadPartial::handle_gamepad_connected(GamepadDescription const&m_available_gamepads.append(description.handle);// 3. Queue a global task on the gamepad task source with the current global object to perform the following steps:- HTML::queue_global_task(HTML::Task::Source::Gamepad, global, GC::create_function(GC::Heap::the(), [&window, &document, description = description] mutable {+ HTML::queue_global_task(HTML::Task::Source::Gamepad, global, GC::create_function(GC::Heap::the(), GC::captures(window, document, description), [](auto& window, auto& document, auto& description) {// 1. Let gamepad be a new Gamepad representing the gamepad.auto gamepad = Gamepad::create(window, description);@@ -154,7 +154,7 @@ void NavigatorGamepadPartial::handle_gamepad_updated(Badge<EventHandler>, Gamepa// AD-HOC: Step 1 runs in the task. A newly available gamepad is created by an earlier task on the same task// source, so input received before that task has run still reaches the gamepad.auto& window = as<HTML::Navigator>(*this).window();- HTML::queue_global_task(HTML::Task::Source::Gamepad, window.principal_realm().global_object(), GC::create_function(GC::Heap::the(), [&window, state] {+ HTML::queue_global_task(HTML::Task::Source::Gamepad, window.principal_realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(window, state), [](auto& window, auto& state) {// 1. Let gamepad be the Gamepad object representing the device that received new button or axis input values.auto navigator = window.navigator();auto gamepad = navigator->m_gamepads.find_if([&state](GC::Ptr<Gamepad> gamepad) {@@ -184,7 +184,7 @@ void NavigatorGamepadPartial::handle_gamepad_disconnected(Badge<EventHandler>, G// AD-HOC: Step 1 runs in the task. A newly available gamepad is created by an earlier task on the same task// source, so a gamepad that becomes unavailable before that task has run is still removed.auto& window = as<HTML::Navigator>(*this).window();- HTML::queue_global_task(HTML::Task::Source::Gamepad, window.principal_realm().global_object(), GC::create_function(GC::Heap::the(), [&window, handle] {+ HTML::queue_global_task(HTML::Task::Source::Gamepad, window.principal_realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(window, handle), [](auto& window, auto& handle) {// 1. Let gamepad be the Gamepad representing the unavailable device.auto matching_gamepad = window.navigator()->m_gamepads.first_matching([&handle](GC::Ptr<Gamepad> gamepad) {return gamepad && gamepad->handle() == handle;diff --git a/Libraries/LibWeb/Geolocation/Geolocation.cpp b/Libraries/LibWeb/Geolocation/Geolocation.cppindex 8805c65451e..fa0c3da4a29 100644--- a/Libraries/LibWeb/Geolocation/Geolocation.cpp+++ b/Libraries/LibWeb/Geolocation/Geolocation.cpp@@ -57,14 +57,14 @@ static void invoke_position_error_callback(GC::Ref<WebIDL::CallbackType> callbacstatic void queue_success_callback(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GeolocationPosition> position){- HTML::queue_a_task(HTML::Task::Source::Geolocation, nullptr, nullptr, GC::create_function(GC::Heap::the(), [callback, position] {+ HTML::queue_a_task(HTML::Task::Source::Geolocation, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(callback, position), [](auto& callback, auto& position) {invoke_position_callback(callback, position);}));}static void queue_error_callback(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GeolocationPositionError> error){- HTML::queue_a_task(HTML::Task::Source::Geolocation, nullptr, nullptr, GC::create_function(GC::Heap::the(), [callback, error] {+ HTML::queue_a_task(HTML::Task::Source::Geolocation, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(callback, error), [](auto& callback, auto& error) {invoke_position_error_callback(callback, error);}));}@@ -210,7 +210,7 @@ void Geolocation::request_a_position(GC::Ref<WebIDL::CallbackType> success_callb}// 5. If document's visibility state is "hidden", wait for the following page visibility change steps to run:- run_in_parallel_when_document_is_visible(document, GC::create_function(GC::Heap::the(), [this, watch_id, success_callback, error_callback, options] {+ run_in_parallel_when_document_is_visible(document, GC::create_function(GC::Heap::the(), GC::captures(*this, watch_id, success_callback, error_callback, options), [](auto& self, auto& watch_id, auto& success_callback, auto& error_callback, auto& options) {// 1. Assert: document's visibility state is "visible".// 2. Continue to the next steps below.// AD-HOC: This is implemented by run_in_parallel_when_document_is_visible().@@ -223,56 +223,56 @@ void Geolocation::request_a_position(GC::Ref<WebIDL::CallbackType> success_callb// request goes out as an async IPC, and the rest of the steps run on the main thread once it answers.{// 1. Set permission to request permission to use descriptor.- auto& settings = window().associated_document().relevant_settings_object();- PermissionsAPI::request_permission_with_user_prompt(descriptor, settings, GC::create_function(heap(), [this, watch_id, success_callback, error_callback, options](PermissionsAPI::PermissionState permission) {+ auto& settings = self.window().associated_document().relevant_settings_object();+ PermissionsAPI::request_permission_with_user_prompt(descriptor, settings, GC::create_function(self.heap(), GC::captures(self, watch_id, success_callback, error_callback, options), [](auto& self, auto& watch_id, auto& success_callback, auto& error_callback, auto& options, PermissionsAPI::PermissionState permission) {// 2. If permission is "denied", then:if (permission == PermissionsAPI::PermissionState::Denied) {// 1. If watchId was passed, remove watchId from watchIDs.if (watch_id.has_value())- remove_watch_id(watch_id.value());+ self.remove_watch_id(watch_id.value());// 2. Call back with error passing errorCallback and PERMISSION_DENIED.- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PermissionDenied);+ self.call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::PermissionDenied);// 3. Terminate this algorithm.return;}// FIXME: 3. Wait to acquire a position passing successCallback, errorCallback, options, and watchId.- acquire_a_position(success_callback, error_callback, options, watch_id);+ self.acquire_a_position(success_callback, error_callback, options, watch_id);// 4. If watchId was not passed, terminate this algorithm.if (!watch_id.has_value())return;- if (!m_watch_ids.contains(*watch_id))+ if (!self.m_watch_ids.contains(*watch_id))return;// 5. While watchIDs contains watchId:// AD-HOC: The spec expresses this as a loop; register callbacks for significant position changes and// re-enter request a position from those callbacks.- auto watch_position_data = m_watch_position_data.get(*watch_id);+ auto watch_position_data = self.m_watch_position_data.get(*watch_id);if (!watch_position_data.has_value() || watch_position_data->emulated_position_data_observer_id.has_value())return;- auto weak_document = GC::Weak<DOM::Document> { window().associated_document() };- auto observer_id = window().page().register_emulated_position_data_observer(GC::create_function(heap(), [this, watch_id = *watch_id, weak_document] {- if (!m_watch_ids.contains(watch_id))+ auto weak_document = GC::Weak<DOM::Document> { self.window().associated_document() };+ auto observer_id = self.window().page().register_emulated_position_data_observer(GC::create_function(self.heap(), GC::captures(self, *watch_id, weak_document), [](auto& self, auto& watch_id, auto& weak_document) {+ if (!self.m_watch_ids.contains(watch_id))return;auto document = weak_document.ptr();if (!document || !document->is_fully_active())return;- if (m_pending_watch_position_request_ids.contains(watch_id))+ if (self.m_pending_watch_position_request_ids.contains(watch_id))return;- auto watch_position_data = m_watch_position_data.get(watch_id);+ auto watch_position_data = self.m_watch_position_data.get(watch_id);if (!watch_position_data.has_value())return;// FIXME: If document is not fully active or visibility state is not "visible", wait for visibility.- request_a_position(watch_position_data->success_callback, watch_position_data->error_callback, watch_position_data->options, watch_id);+ self.request_a_position(watch_position_data->success_callback, watch_position_data->error_callback, watch_position_data->options, watch_id);}));watch_position_data->emulated_position_data_observer_id = observer_id;}));@@ -391,13 +391,13 @@ void Geolocation::call_back_with_timeout_error(GC::Ptr<WebIDL::CallbackType> errauto weak_document = GC::Weak<DOM::Document> { window().associated_document() };auto timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(min(timeout, NumericLimits<int>::max())), {});m_timeout_timers.append(timer);- timer->on_timeout = GC::create_function(heap(), [this, timer, error_callback, watch_id, weak_document] {- m_timeout_timers.remove_first_matching([&](auto candidate) { return candidate == timer; });- if (watch_id.has_value() && !m_watch_ids.contains(*watch_id))+ timer->on_timeout = GC::create_function(heap(), GC::captures(*this, timer, error_callback, watch_id, weak_document), [](auto& self, auto& timer, auto& error_callback, auto& watch_id, auto& weak_document) {+ self.m_timeout_timers.remove_first_matching([&](auto candidate) { return candidate == timer; });+ if (watch_id.has_value() && !self.m_watch_ids.contains(*watch_id))return;if (!weak_document || !weak_document->is_fully_active())return;- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::Timeout);+ self.call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::Timeout);});timer->start();}@@ -414,23 +414,24 @@ void Geolocation::acquire_position_from_page(GC::Ref<WebIDL::CallbackType> succeauto timeout_timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(min(options.timeout, NumericLimits<int>::max())), {});m_timeout_timers.append(timeout_timer);- auto stop_timeout_timer = [this, timeout_timer, request_state] {+ auto stop_timeout_timer = GC::create_function(heap(), GC::captures(*this, timeout_timer, request_state), [](auto& self, auto& timeout_timer, auto& request_state) {if (request_state->timeout_stopped)return;request_state->timeout_stopped = true;timeout_timer->stop();timeout_timer->on_timeout = nullptr;- m_timeout_timers.remove_first_matching([&](auto timer) { return timer == timeout_timer; });- };+ self.m_timeout_timers.remove_first_matching([&](auto timer) { return timer == timeout_timer; });+ });auto position_callback = GC::create_function(heap(),- [this, success_callback, error_callback, options, watch_id, acquisition_time, request_state, weak_document, stop_timeout_timer](Page::GeolocationPositionResult result) {+ GC::captures(*this, success_callback, error_callback, options, watch_id, acquisition_time, request_state, weak_document, stop_timeout_timer),+ [](auto& self, auto& success_callback, auto& error_callback, auto& options, auto& watch_id, auto& acquisition_time, auto& request_state, auto& weak_document, auto& stop_timeout_timer, Page::GeolocationPositionResult result) {if (request_state->completed)return;- if (watch_id.has_value() && !m_watch_ids.contains(*watch_id)) {+ if (watch_id.has_value() && !self.m_watch_ids.contains(*watch_id)) {// NB: The position response arrived after the watch was cleared; stop the timeout before ignoring it.- stop_timeout_timer();+ stop_timeout_timer->function()();return;}if (!watch_id.has_value())@@ -439,7 +440,7 @@ void Geolocation::acquire_position_from_page(GC::Ref<WebIDL::CallbackType> succeauto document = weak_document.ptr();if (!document || !document->is_fully_active()) {// NB: The position response is no longer observable; stop the timeout before ignoring it.- stop_timeout_timer();+ stop_timeout_timer->function()();return;}@@ -448,15 +449,15 @@ void Geolocation::acquire_position_from_page(GC::Ref<WebIDL::CallbackType> succeauto error_code = result.get<GeolocationPositionError::ErrorCode>();// 1. Stop the timeout.- stop_timeout_timer();+ stop_timeout_timer->function()();if (watch_id.has_value() && error_code == GeolocationPositionError::ErrorCode::PermissionDenied) {request_state->completed = true;- m_pending_watch_position_request_ids.remove(*watch_id);+ self.m_pending_watch_position_request_ids.remove(*watch_id);}// 2. Go to dealing with failures.- call_back_with_error(error_callback, error_code);+ self.call_back_with_error(error_callback, error_code);// 3. Terminate this algorithm.return;@@ -494,10 +495,10 @@ void Geolocation::acquire_position_from_page(GC::Ref<WebIDL::CallbackType> succeauto position = GC::Heap::the().allocate<GeolocationPosition>(position_data, acquisition_time, options.enable_high_accuracy);// 6.3. Set this's [[cachedPosition]] to position.- m_cached_position = *position;+ self.m_cached_position = *position;// 7. Stop the timeout.- stop_timeout_timer();+ stop_timeout_timer->function()();// 8. Queue a task on the geolocation task source with a step that invokes successCallback with « position »// and "report".@@ -508,19 +509,19 @@ void Geolocation::acquire_position_from_page(GC::Ref<WebIDL::CallbackType> succeif (watch_id.has_value())m_pending_watch_position_request_ids.set(*watch_id, request_state->request_id);- timeout_timer->on_timeout = GC::create_function(heap(), [this, error_callback, watch_id, request_state, weak_document, weak_page, stop_timeout_timer] {+ timeout_timer->on_timeout = GC::create_function(heap(), GC::captures(*this, error_callback, watch_id, request_state, weak_document, weak_page, stop_timeout_timer), [](auto& self, auto& error_callback, auto& watch_id, auto& request_state, auto& weak_document, auto& weak_page, auto& stop_timeout_timer) {if (request_state->completed)return;request_state->completed = true;- stop_timeout_timer();- if (watch_id.has_value() && !m_pending_watch_position_request_ids.remove(*watch_id))+ stop_timeout_timer->function()();+ if (watch_id.has_value() && !self.m_pending_watch_position_request_ids.remove(*watch_id))return;if (auto page = weak_page.ptr())page->cancel_geolocation_position_request(request_state->request_id);auto document = weak_document.ptr();if (!document || !document->is_fully_active())return;- call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::Timeout);+ self.call_back_with_error(error_callback, GeolocationPositionError::ErrorCode::Timeout);});timeout_timer->start();}@@ -543,8 +544,8 @@ void Geolocation::run_in_parallel_when_document_is_visible(DOM::Document& docume{// Run callback in parallel if the document is already visible.if (document.visibility_state() == HTML::VisibilityState::Visible) {- auto callback_with_context = GC::create_function(GC::Heap::the(), [this, callback] {- HTML::TemporaryExecutionContext execution_context { window().relevant_settings_object() };+ auto callback_with_context = GC::create_function(GC::Heap::the(), GC::captures(*this, callback), [](auto& self, auto& callback) {+ HTML::TemporaryExecutionContext execution_context { self.window().relevant_settings_object() };callback->function()();});Platform::EventLoopPlugin::the().deferred_invoke(callback_with_context);@@ -555,23 +556,23 @@ void Geolocation::run_in_parallel_when_document_is_visible(DOM::Document& documeauto document_observer = DOM::DocumentObserver::create(document);auto timeout_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(VISIBILITY_STATE_TIMEOUT_MS), {});m_timeout_timers.append(timeout_timer);- auto clear_observer_and_timer = [this, document_observer, timeout_timer] {+ auto clear_observer_and_timer = GC::create_function(GC::Heap::the(), GC::captures(*this, document_observer, timeout_timer), [](auto& self, auto& document_observer, auto& timeout_timer) {document_observer->set_document_visibility_state_observer({});timeout_timer->stop();- m_timeout_timers.remove_first_matching([&](auto timer) { return timer == timeout_timer; });- };- timeout_timer->on_timeout = GC::create_function(GC::Heap::the(), [clear_observer_and_timer] {+ self.m_timeout_timers.remove_first_matching([&](auto timer) { return timer == timeout_timer; });+ });+ timeout_timer->on_timeout = GC::create_function(GC::Heap::the(), GC::captures(clear_observer_and_timer), [](auto& clear_observer_and_timer) {dbgln("Geolocation: Waiting for visibility state update timed out");- clear_observer_and_timer();+ clear_observer_and_timer->function()();});- document_observer->set_document_visibility_state_observer([this, clear_observer_and_timer, callback](HTML::VisibilityState state) {+ document_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(*this, clear_observer_and_timer, callback), [](auto& self, auto& clear_observer_and_timer, auto& callback, HTML::VisibilityState state) {if (state == HTML::VisibilityState::Visible) {- clear_observer_and_timer();- HTML::TemporaryExecutionContext execution_context { window().relevant_settings_object() };+ clear_observer_and_timer->function()();+ HTML::TemporaryExecutionContext execution_context { self.window().relevant_settings_object() };callback->function()();}- });+ }));timeout_timer->start();}diff --git a/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cpp b/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cppindex c92bb08a969..8c044d03ff2 100644--- a/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cpp+++ b/Libraries/LibWeb/HTML/AnimatedDecodedImageData.cpp@@ -25,21 +25,21 @@ AnimatedDecodedImageData::AnimatedDecodedImageData(GC::Ref<DOM::DocumentObserver// hidden. Other browsers disagree on what should happen when the document becomes active again,// Blink continues the animation from where it would be if it had been running the whole time, and// Gecko restarts the animation. For now we restart the animation since that's simpler.- m_document_observer->set_document_became_inactive([weak_this] {+ m_document_observer->set_document_became_inactive(GC::create_function(GC::Heap::the(), GC::captures(weak_this), [](auto& weak_this) {if (auto self = weak_this.ptr())self->stop_animation();- });+ }));- m_document_observer->set_document_became_active([weak_this] {+ m_document_observer->set_document_became_active(GC::create_function(GC::Heap::the(), GC::captures(weak_this), [](auto& weak_this) {if (auto self = weak_this.ptr()) {if (!self->has_clients())self->m_should_start_animation_on_client_registration = true;self->restart_animation();}- });+ }));- m_document_observer->set_document_visibility_state_observer([weak_this](HTML::VisibilityState visibility_state) {+ m_document_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(weak_this), [](auto& weak_this, HTML::VisibilityState visibility_state) {if (auto self = weak_this.ptr()) {switch (visibility_state) {case HTML::VisibilityState::Hidden:@@ -52,7 +52,7 @@ AnimatedDecodedImageData::AnimatedDecodedImageData(GC::Ref<DOM::DocumentObserverbreak;}}- });+ }));}void AnimatedDecodedImageData::restart_animation()diff --git a/Libraries/LibWeb/HTML/AudioTrack.cpp b/Libraries/LibWeb/HTML/AudioTrack.cppindex 226ad0d539b..b87ffb32b2e 100644--- a/Libraries/LibWeb/HTML/AudioTrack.cpp+++ b/Libraries/LibWeb/HTML/AudioTrack.cpp@@ -70,9 +70,9 @@ void AudioTrack::set_enabled(bool enabled)// Whenever an audio track in an AudioTrackList that was disabled is enabled, and whenever one that was enabled// is disabled, the user agent must queue a media element task given the media element to fire an event named// change at the AudioTrackList object.- media_element().queue_a_media_element_task([this, audio_track_list](HTMLMediaElement&) {- audio_track_list->dispatch_event(create_event_for_element(media_element(), HTML::EventNames::change));- });+ media_element().queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this, audio_track_list), [](auto& track, auto& audio_track_list, HTMLMediaElement&) {+ audio_track_list->dispatch_event(create_event_for_element(track.media_element(), HTML::EventNames::change));+ }));}media_element().set_audio_track_enabled({}, this, enabled);diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex fbe7d8923c1..1cd457b4cf6 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -280,7 +280,7 @@ void Canvas2DContextBase::notify_backing_storage_lost()// When the user agent detects that the backing storage associated with a canvas context has been lost, then it// must queue a global task on the DOM manipulation task source given canvas's relevant global object to run// these steps:- queue_global_task(HTML::Task::Source::DOMManipulation, canvas_host().canvas_relevant_global_object(), GC::create_function(GC::Heap::the(), [context = GC::Ref { *this }] {+ queue_global_task(HTML::Task::Source::DOMManipulation, canvas_host().canvas_relevant_global_object(), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }), [](auto& context) {// 1. Let canvas be context's canvas element.auto& canvas = context->canvas_host();diff --git a/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.h b/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.hindex d8e19a18594..a401eb9646e 100644--- a/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.h+++ b/Libraries/LibWeb/HTML/Canvas/SerializeBitmap.h@@ -9,6 +9,7 @@#include <AK/ByteBuffer.h>#include <AK/StringView.h>#include <AK/Utf16View.h>+#include <LibGC/Forward.h>#include <LibGfx/Forward.h>namespace Web::HTML {@@ -36,3 +37,5 @@ bool serialization_of_the_bitmap_supports_color_profiles(Utf16View type);ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::DecodedImageFrame const&, Utf16View type, Optional<double> quality);}++GC_UNTRACED_CAPTURE(Web::HTML::SerializeBitmapResult);diff --git a/Libraries/LibWeb/HTML/CheckUnloadingCanceledState.cpp b/Libraries/LibWeb/HTML/CheckUnloadingCanceledState.cppindex 5ad9bcd8f33..133d539c133 100644--- a/Libraries/LibWeb/HTML/CheckUnloadingCanceledState.cpp+++ b/Libraries/LibWeb/HTML/CheckUnloadingCanceledState.cpp@@ -32,14 +32,14 @@ CheckUnloadingCanceledState::CheckUnloadingCanceledState(, m_traversable(traversable), m_user_involvement(user_involvement), m_callback(callback)- , m_timeout(Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(TIMEOUT_MS), GC::create_function(heap(), [this] {- if (!m_completed) {- if (has_pending_before_unload_dialog()) {- m_timeout->restart();+ , m_timeout(Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(TIMEOUT_MS), GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ if (!self.m_completed) {+ if (self.has_pending_before_unload_dialog()) {+ self.m_timeout->restart();return;}dbgln("FIXME: check_if_unloading_is_canceled timed out");- finish(Result::Continue);+ self.finish(Result::Continue);}}))){@@ -175,48 +175,48 @@ void CheckUnloadingCanceledState::start_phase1(){// 4. Queue a global task on the navigation and traversal task source given traversable's active window to perform the following steps:VERIFY(m_traversable->active_window());- queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*m_traversable->active_window()), GC::create_function(GC::Heap::the(), [this] {+ queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*m_traversable->active_window()), GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 1. if needsBeforeunload is true, then:- if (m_needs_beforeunload) {+ if (self.m_needs_beforeunload) {// 1. Let (unloadPromptShownForThisDocument, unloadPromptCanceledByThisDocument) be the result of running the steps to fire beforeunload given traversable's active document and false.bool unload_prompt_shown_for_this_document;bool unload_prompt_canceled_by_this_document;- fire_beforeunload(*m_traversable->active_document(), false, unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);- if (m_adopted_for_close && !m_running_adopted_close) {- continue_as_close_after_adoption(unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);+ self.fire_beforeunload(*self.m_traversable->active_document(), false, unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);+ if (self.m_adopted_for_close && !self.m_running_adopted_close) {+ self.continue_as_close_after_adoption(unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);return;}// 2. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true.if (unload_prompt_shown_for_this_document)- m_unload_prompt_shown = UnloadPromptShown::Yes;+ self.m_unload_prompt_shown = UnloadPromptShown::Yes;// 3. If unloadPromptCanceledByThisDocument is true, then set finalStatus to "canceled-by-beforeunload".if (unload_prompt_canceled_by_this_document)- m_final_status = Result::CanceledByBeforeUnload;+ self.m_final_status = Result::CanceledByBeforeUnload;}// 2. If finalStatus is "canceled-by-beforeunload", then abort these steps.- if (m_final_status == Result::CanceledByBeforeUnload) {- finish(m_final_status);+ if (self.m_final_status == Result::CanceledByBeforeUnload) {+ self.finish(self.m_final_status);return;}// 3. Let navigation be traversable's active window's navigation API.- VERIFY(m_traversable->active_window());- auto navigation = m_traversable->active_window()->navigation();+ VERIFY(self.m_traversable->active_window());+ auto navigation = self.m_traversable->active_window()->navigation();// 4. Let navigateEventResult be the result of firing a traverse navigate event at navigation given targetEntry and userInvolvementForNavigateEvent.- VERIFY(m_target_entry);- auto navigate_event_result = navigation->fire_a_traverse_navigate_event(*m_target_entry, *m_user_involvement);+ VERIFY(self.m_target_entry);+ auto navigate_event_result = navigation->fire_a_traverse_navigate_event(*self.m_target_entry, *self.m_user_involvement);// 5. If navigateEventResult is false, then set finalStatus to "canceled-by-navigate".if (!navigate_event_result)- m_final_status = Result::CanceledByNavigate;+ self.m_final_status = Result::CanceledByNavigate;// 6. Set eventsFired to true.- phase1_completed();+ self.phase1_completed();}));}@@ -251,35 +251,35 @@ void CheckUnloadingCanceledState::start_phase2()// are only runnable when fully active. In the async state machine, documents can become non// fully-active between queue and execution time, causing the task to be permanently stuck.// A null-document task is always runnable; we check validity inside.- queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr, GC::create_function(heap(), [this, document, generation] {- if (generation != m_phase2_generation)+ queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr, GC::create_function(heap(), GC::captures(*this, document, generation), [](auto& self, auto& document, auto& generation) {+ if (generation != self.m_phase2_generation)return;if (document->has_been_destroyed() || !document->is_fully_active()) {- did_complete_phase2_task();+ self.did_complete_phase2_task();return;}// 1. Let (unloadPromptShownForThisDocument, unloadPromptCanceledByThisDocument) be the result of running the steps to fire beforeunload given document and unloadPromptShown.bool unload_prompt_shown_for_this_document;bool unload_prompt_canceled_by_this_document;- fire_beforeunload(*document, m_unload_prompt_shown == UnloadPromptShown::Yes, unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);- if (m_adopted_for_close && !m_running_adopted_close) {- continue_as_close_after_adoption(unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);+ self.fire_beforeunload(*document, self.m_unload_prompt_shown == UnloadPromptShown::Yes, unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);+ if (self.m_adopted_for_close && !self.m_running_adopted_close) {+ self.continue_as_close_after_adoption(unload_prompt_shown_for_this_document, unload_prompt_canceled_by_this_document);return;}- if (generation != m_phase2_generation)+ if (generation != self.m_phase2_generation)return;// 2. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true.if (unload_prompt_shown_for_this_document)- m_unload_prompt_shown = UnloadPromptShown::Yes;+ self.m_unload_prompt_shown = UnloadPromptShown::Yes;// 3. If unloadPromptCanceledByThisDocument is true, then set finalStatus to "canceled-by-beforeunload".if (unload_prompt_canceled_by_this_document)- m_final_status = Result::CanceledByBeforeUnload;+ self.m_final_status = Result::CanceledByBeforeUnload;// 4. Increment completedTasks.- did_complete_phase2_task();+ self.did_complete_phase2_task();}));}}diff --git a/Libraries/LibWeb/HTML/CloseWatcher.cpp b/Libraries/LibWeb/HTML/CloseWatcher.cppindex 85d94e3a3df..dfe82602d61 100644--- a/Libraries/LibWeb/HTML/CloseWatcher.cpp+++ b/Libraries/LibWeb/HTML/CloseWatcher.cpp@@ -77,10 +77,10 @@ WebIDL::ExceptionOr<GC::Ref<CloseWatcher>> CloseWatcher::create(Window& window,}// 3.2 Add the following steps to options["signal"]:- (void)signal->add_abort_algorithm([close_watcher] {+ (void)signal->add_abort_algorithm(GC::create_function(GC::Heap::the(), GC::captures(close_watcher), [](auto& close_watcher) {// 3.2.1 Destroy closeWatcher.close_watcher->destroy();- });+ }));}return close_watcher;diff --git a/Libraries/LibWeb/HTML/DataTransferItem.cpp b/Libraries/LibWeb/HTML/DataTransferItem.cppindex f4090379495..0e0d64d7419 100644--- a/Libraries/LibWeb/HTML/DataTransferItem.cpp+++ b/Libraries/LibWeb/HTML/DataTransferItem.cpp@@ -113,7 +113,7 @@ void DataTransferItem::get_as_string(GC::Ptr<WebIDL::CallbackType> callback) con// 4. Otherwise, queue a task to invoke callback, passing the actual data of the item represented by the// DataTransferItem object as the argument.HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr,- GC::Function<void()>::create(GC::Heap::the(), [callback, data = data.release_value()]() mutable {+ GC::create_function(GC::Heap::the(), GC::captures(callback, data.release_value()), [](auto& callback, auto& data) {auto& vm = callback->callback->vm();auto wrapped_data = JS::PrimitiveString::create(vm, move(data));(void)WebIDL::invoke_callback(*callback, {}, { { wrapped_data } });diff --git a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cppindex cb36f69f6e9..4a7852229db 100644--- a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp@@ -77,11 +77,11 @@ WebIDL::ExceptionOr<WebIDL::UnsignedLong> DedicatedWorkerGlobalScope::request_an// 3. Increment target's animation frame callback identifier by one, and let handle be the result.// 4. Let callbacks be target's map of animation frame callbacks.// 5. Set callbacks[handle] to callback.- auto handle = animation_frame_callback_driver().add(GC::create_function(heap(), [this, callback](double now) {+ auto handle = animation_frame_callback_driver().add(GC::create_function(heap(), GC::captures(*this, callback), [](auto& self, auto& callback, double now) {// Invoke callback with « now » and "report".auto result = WebIDL::invoke_callback(*callback, {}, { { JS::Value(now) } });if (result.is_error())- report_exception(result, realm());+ report_exception(result, self.realm());}));schedule_rendering_update();@@ -127,12 +127,12 @@ bool DedicatedWorkerGlobalScope::has_animation_frame_callbacks() constvoid DedicatedWorkerGlobalScope::schedule_rendering_update(){if (!m_rendering_update_timer) {- m_rendering_update_timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(0), GC::create_function(heap(), [this] {- if (relevant_settings_object(*this).responsible_event_loop().execution_paused()) {- schedule_rendering_update();+ m_rendering_update_timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(0), GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ if (relevant_settings_object(self).responsible_event_loop().execution_paused()) {+ self.schedule_rendering_update();return;}- run_rendering_update();+ self.run_rendering_update();}));}if (m_rendering_update_timer->is_active())diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex 5464d8d0574..dddb433fa57 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -72,10 +72,10 @@ EventLoop::EventLoop(Type type)}m_task_queue = GC::Heap::the().allocate<TaskQueue>(*this);- m_rendering_task_function = GC::create_function(GC::Heap::the(), [this] {- VERIFY(m_rendering_task_queued);- m_rendering_task_queued = false;- update_the_rendering();+ m_rendering_task_function = GC::create_function(GC::Heap::the(), GC::captures(*this), [](EventLoop& self) {+ VERIFY(self.m_rendering_task_queued);+ self.m_rendering_task_queued = false;+ self.update_the_rendering();});}@@ -112,8 +112,8 @@ void EventLoop::schedule()void EventLoop::schedule_for_queued_task(){if (!m_system_event_loop_timer) {- m_system_event_loop_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(0), GC::create_function(GC::Heap::the(), [this] {- process();+ m_system_event_loop_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(0), GC::create_function(GC::Heap::the(), GC::captures(*this), [](EventLoop& self) {+ self.process();}));}@@ -181,11 +181,11 @@ void EventLoop::spin_until(GC::Ref<GC::Function<bool()>> goal_condition)if (m_destruction_requested)schedule();};- Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), [this, goal_condition] {+ Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), GC::captures(*this, goal_condition), [](auto& self, auto& goal_condition) {if (goal_condition->function()())return true;- if (m_task_queue->has_runnable_tasks()) {- schedule();+ if (self.m_task_queue->has_runnable_tasks()) {+ self.schedule();// FIXME: Remove the platform event loop plugin so that this doesn't look out of placeCore::EventLoop::current().wake();}@@ -380,8 +380,8 @@ bool EventLoop::run_one_turn_of_the_processing_model()// anything but an idle callback starts an idle period right away (see did_request_idle_callback()).m_idle_callback_requested_outside_idle_period = false;if (!m_idle_period_timer) {- m_idle_period_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(50), GC::create_function(GC::Heap::the(), [this] {- schedule();+ m_idle_period_timer = Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(50), GC::create_function(GC::Heap::the(), GC::captures(*this), [](EventLoop& self) {+ self.schedule();}));}m_idle_period_timer->restart();@@ -966,13 +966,13 @@ void EventLoop::queue_task_to_process_input_events()if (m_input_events_task_queued)return;m_input_events_task_queued = true;- queue_a_task(Task::Source::UserInteraction, this, nullptr, GC::create_function(GC::Heap::the(), [this] {- m_input_events_task_queued = false;- if (m_running_rendering_task || m_rendering_update_in_flight)+ queue_a_task(Task::Source::UserInteraction, this, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](EventLoop& self) {+ self.m_input_events_task_queued = false;+ if (self.m_running_rendering_task || self.m_rendering_update_in_flight)return;// NB: No rendering update comes with this task, and script may run for long before the next one: the lanes// tick on.- take_clock_lanes_and_input_events_in({});+ self.take_clock_lanes_and_input_events_in({});}));}diff --git a/Libraries/LibWeb/HTML/EventSource.cpp b/Libraries/LibWeb/HTML/EventSource.cppindex 9c2bc0f1f7e..d6f0efb4fef 100644--- a/Libraries/LibWeb/HTML/EventSource.cpp+++ b/Libraries/LibWeb/HTML/EventSource.cpp@@ -114,17 +114,17 @@ WebIDL::ExceptionOr<GC::Ref<EventSource>> EventSource::create(WindowOrWorkerGlob// 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then// reestablish the connection.- auto process_event_source_end_of_body = [event_source](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ auto process_event_source_end_of_body = GC::create_function(event_source->heap(), GC::captures(event_source), [](auto& event_source, GC::Ref<Fetch::Infrastructure::ResponseView> response) {if (!response->is_network_error())event_source->reestablish_the_connection();- };+ });// 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody and processResponse set to the// following steps given response res:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };fetch_algorithms_input.process_response_end_of_body = move(process_event_source_end_of_body);- fetch_algorithms_input.process_response = [event_source](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ fetch_algorithms_input.process_response = GC::create_function(event_source->heap(), GC::captures(event_source), [](auto& event_source, GC::Ref<Fetch::Infrastructure::ResponseView> response) {auto& realm = HTML::relevant_realm(event_source->relevant_global_object());// FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:@@ -157,7 +157,7 @@ WebIDL::ExceptionOr<GC::Ref<EventSource>> EventSource::create(WindowOrWorkerGlobelse {event_source->announce_the_connection();- auto process_body_chunk = GC::create_function(GC::Heap::the(), [event_source, pending_data = ByteBuffer(), is_start_of_stream = true](ByteBuffer body) mutable {+ auto process_body_chunk = GC::create_function(GC::Heap::the(), GC::captures(event_source, ByteBuffer(), true), [](auto& event_source, auto& pending_data, auto& is_start_of_stream, ByteBuffer body) {if (pending_data.is_empty())pending_data = move(body);else@@ -183,7 +183,7 @@ WebIDL::ExceptionOr<GC::Ref<EventSource>> EventSource::create(WindowOrWorkerGlobresponse->body()->incrementally_read(realm, process_body_chunk, process_end_of_body, process_body_error, { realm.global_object() });}- };+ });event_source->m_fetch_algorithms = Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input));event_source->m_fetch_controller = Fetch::Fetching::fetch(HTML::relevant_realm(global_scope), request, *event_source->m_fetch_algorithms);@@ -302,10 +302,10 @@ void EventSource::announce_the_connection()// When a user agent is to announce the connection, the user agent must queue a task which, if the readyState attribute// is set to a value other than CLOSED, sets the readyState attribute to OPEN and fires an event named open at the// EventSource object.- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this]() {- if (m_ready_state != ReadyState::Closed) {- m_ready_state = ReadyState::Open;- dispatch_event(create_associated_event(HTML::EventNames::open));+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ if (self.m_ready_state != ReadyState::Closed) {+ self.m_ready_state = ReadyState::Open;+ self.dispatch_event(self.create_associated_event(HTML::EventNames::open));}}));}@@ -320,27 +320,27 @@ void EventSource::reestablish_the_connection()auto end_of_delay = MonotonicTime::now() + m_reconnection_time;// 1. Queue a task to run the following steps:- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this, end_of_delay]() {+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this, end_of_delay), [](auto& self, auto& end_of_delay) {// NB: Step 4 waits for this task to finish, and an error event handler can spin a nested event loop. So the// timer for the rest of the delay of step 2 starts only once this task has finished.- ScopeGuard start_the_reconnection_timer { [this, end_of_delay] {- if (m_ready_state != ReadyState::Closed)- m_reconnection_timer->start(max(end_of_delay - MonotonicTime::now(), AK::Duration::zero()));+ ScopeGuard start_the_reconnection_timer { [&self, end_of_delay] {+ if (self.m_ready_state != ReadyState::Closed)+ self.m_reconnection_timer->start(max(end_of_delay - MonotonicTime::now(), AK::Duration::zero()));} };// 1. If the readyState attribute is set to CLOSED, abort the task.- if (m_ready_state == ReadyState::Closed)+ if (self.m_ready_state == ReadyState::Closed)return;// 2. Set the readyState attribute to CONNECTING.- m_ready_state = ReadyState::Connecting;+ self.m_ready_state = ReadyState::Connecting;// 3. Fire an event named error at the EventSource object.- dispatch_event(create_associated_event(HTML::EventNames::error));+ self.dispatch_event(self.create_associated_event(HTML::EventNames::error));}));// 2. Wait a delay equal to the reconnection time of the event source.- m_reconnection_timer = Platform::Timer::create_single_shot(GC::Heap::the(), m_reconnection_time, GC::create_function(GC::Heap::the(), [this]() {+ m_reconnection_timer = Platform::Timer::create_single_shot(GC::Heap::the(), m_reconnection_time, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 3. Optionally, wait some more. In particular, if the previous attempt failed, then user agents might introduce// an exponential backoff delay to avoid overloading a potentially already overloaded server. Alternatively, if// the operating system has reported that there is no network connectivity, user agents might wait for the@@ -350,26 +350,26 @@ void EventSource::reestablish_the_connection()// NB: The timer starts only once that task has run. See step 1.// 5. Queue a task to run the following steps:- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this]() {+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {// 1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.- if (m_ready_state != ReadyState::Connecting)+ if (self.m_ready_state != ReadyState::Connecting)return;// 2. Let request be the EventSource object's request.- NonnullRefPtr request { *m_request };+ NonnullRefPtr request { *self.m_request };// 3. If the EventSource object's last event ID string is not the empty string, then:- if (!m_last_event_id.is_empty()) {+ if (!self.m_last_event_id.is_empty()) {// 1. Let lastEventIDValue be the EventSource object's last event ID string, encoded as UTF-8.- auto last_event_id_value = m_last_event_id.to_utf8();+ auto last_event_id_value = self.m_last_event_id.to_utf8();// 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.request->header_list()->set({ "Last-Event-ID"sv, last_event_id_value.to_byte_string() });}// 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this// section.- auto& realm = HTML::relevant_realm(relevant_global_object());- m_fetch_controller = Fetch::Fetching::fetch(realm, request, *m_fetch_algorithms);+ auto& realm = HTML::relevant_realm(self.relevant_global_object());+ self.m_fetch_controller = Fetch::Fetching::fetch(realm, request, *self.m_fetch_algorithms);}));}));}@@ -380,10 +380,10 @@ void EventSource::fail_the_connection()// When a user agent is to fail the connection, the user agent must queue a task which, if the readyState attribute// is set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires an event named error at the// EventSource object. Once the user agent has failed the connection, it does not attempt to reconnect.- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this]() {- if (m_ready_state != ReadyState::Closed) {- m_ready_state = ReadyState::Closed;- dispatch_event(create_associated_event(HTML::EventNames::error));+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ if (self.m_ready_state != ReadyState::Closed) {+ self.m_ready_state = ReadyState::Closed;+ self.dispatch_event(self.create_associated_event(HTML::EventNames::error));}}));}@@ -503,9 +503,9 @@ void EventSource::dispatch_the_event()// 8. Queue a task which, if the readyState attribute is set to a value other than CLOSED, dispatches the newly created// event at the EventSource object.- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this, event]() {- if (m_ready_state != ReadyState::Closed)- dispatch_event(event);+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this, event), [](auto& self, auto& event) {+ if (self.m_ready_state != ReadyState::Closed)+ self.dispatch_event(event);}));}diff --git a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp b/Libraries/LibWeb/HTML/FormAssociatedElement.cppindex ee7a83d5450..e7d72ba83d3 100644--- a/Libraries/LibWeb/HTML/FormAssociatedElement.cpp+++ b/Libraries/LibWeb/HTML/FormAssociatedElement.cpp@@ -1290,13 +1290,13 @@ void FormAssociatedTextControlElement::set_the_selection_range(Optional<WebIDL::// moves because the value changed (an edit, or the value setter). This is not in the spec but matches// how other browsers behave.if (source == SelectionSource::DOM || (source == SelectionSource::UI && m_selection_start != m_selection_end)) {- html_element.queue_an_element_task(Task::Source::UserInteraction, [&html_element] {+ html_element.queue_an_element_task(Task::Source::UserInteraction, GC::create_function(GC::Heap::the(), GC::captures(html_element), [](auto& html_element) {auto select_event = DOM::Event::create(EventNames::select,{ .bubbles = true },HighResolutionTime::current_high_resolution_time(relevant_global_object(html_element)));static_cast<DOM::EventTarget*>(&html_element)->dispatch_event(select_event);- });+ }));}// NB: A selection change ends typing coalescence in the editing history, unless it wasdiff --git a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp b/Libraries/LibWeb/HTML/HTMLCanvasElement.cppindex 9a753a1056b..0a445f630f0 100644--- a/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLCanvasElement.cpp@@ -448,7 +448,7 @@ WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(GC::Ref<WebIDL::CallbackTyp// 4. Run these steps in parallel:auto type_string = Utf16String::from_utf16(type);Optional<double> quality = js_quality.has_value() && js_quality->is_number() ? js_quality->as_double() : Optional<double>();- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), [this, callback, bitmap_result, type = move(type_string), quality] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), GC::captures(*this, callback, bitmap_result, move(type_string), quality), [](auto& self, auto& callback, auto& bitmap_result, auto& type, auto& quality) {// 1. If result is non-null, then set result to a serialization of result as a file with type and quality if given.Optional<SerializeBitmapResult> file_result;if (bitmap_result.has_value()) {@@ -457,9 +457,9 @@ WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(GC::Ref<WebIDL::CallbackTyp}// 2. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps:- queue_an_element_task(Task::Source::CanvasBlobSerializationTask, [this, callback, file_result = move(file_result)] {- auto& realm = HTML::relevant_realm(*this);- auto maybe_error = WebIDL::throw_dom_exception_if_needed(vm(), realm, [&]() -> WebIDL::ExceptionOr<void> {+ self.queue_an_element_task(Task::Source::CanvasBlobSerializationTask, GC::create_function(self.heap(), GC::captures(self, callback, move(file_result)), [](auto& self, auto& callback, auto& file_result) {+ auto& realm = HTML::relevant_realm(self);+ auto maybe_error = WebIDL::throw_dom_exception_if_needed(self.vm(), realm, [&]() -> WebIDL::ExceptionOr<void> {// 1. If result is non-null, then set result to a new Blob object, created in the relevant realm of this canvas element, representing result. [FILEAPI]GC::Ptr<FileAPI::Blob> blob_result;if (file_result.has_value())@@ -471,8 +471,8 @@ WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(GC::Ref<WebIDL::CallbackTypreturn {};});if (maybe_error.is_throw_completion())- report_exception(maybe_error.throw_completion(), HTML::relevant_realm(*this));- });+ report_exception(maybe_error.throw_completion(), HTML::relevant_realm(self));+ }));}));return {};}@@ -602,12 +602,12 @@ void HTMLCanvasElement::did_commit_placeholder_frame(Gfx::IntSize size, bool ori{m_placeholder_frame_is_origin_clean = origin_clean;- queue_an_element_task(Task::Source::DOMManipulation, [this, size] {- if (width() != static_cast<WebIDL::UnsignedLong>(size.width()))- set_attribute_value(HTML::AttributeNames::width, Utf16String::number(size.width()));- if (height() != static_cast<WebIDL::UnsignedLong>(size.height()))- set_attribute_value(HTML::AttributeNames::height, Utf16String::number(size.height()));- });+ queue_an_element_task(Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this, size.width(), size.height()), [](auto& self, auto& width, auto& height) {+ if (self.width() != static_cast<WebIDL::UnsignedLong>(width))+ self.set_attribute_value(HTML::AttributeNames::width, Utf16String::number(width));+ if (self.height() != static_cast<WebIDL::UnsignedLong>(height))+ self.set_attribute_value(HTML::AttributeNames::height, Utf16String::number(height));+ }));}RefPtr<Gfx::Bitmap> HTMLCanvasElement::get_bitmap_from_surface()diff --git a/Libraries/LibWeb/HTML/HTMLDataListElement.cpp b/Libraries/LibWeb/HTML/HTMLDataListElement.cppindex f752571cd30..def05761c9f 100644--- a/Libraries/LibWeb/HTML/HTMLDataListElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLDataListElement.cpp@@ -65,13 +65,13 @@ void HTMLDataListElement::attribute_changed(Utf16FlyString const& name, Optional// left, shows the suggestions of whatever element its list attribute now names.void HTMLDataListElement::notify_inputs_with_suggestions_sources_in(DOM::Node& root){- queue_an_element_task(HTML::Task::Source::DOMManipulation, [root = GC::Ref { root }] {+ queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { root }), [](GC::Ref<DOM::Node>& root) {root->for_each_in_inclusive_subtree_of_type<HTMLInputElement>([](HTMLInputElement& input) {if (input.has_attribute(AttributeNames::list))input.suggestions_source_element_did_change();return TraversalDecision::Continue;});- });+ }));}// NB: An input that shows the suggestions of a datalist, such as the ticks of a slider, shows them again once the@@ -82,14 +82,14 @@ void HTMLDataListElement::notify_inputs_using_this_as_suggestions_source()if (m_input_notification_queued || !id().has_value())return;m_input_notification_queued = true;- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {- m_input_notification_queued = false;- root().for_each_in_inclusive_subtree_of_type<HTMLInputElement>([&](HTMLInputElement& input) {- if (auto list = input.get_attribute(AttributeNames::list); list.has_value() && id() == *list)+ queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this), [](HTMLDataListElement& self) {+ self.m_input_notification_queued = false;+ self.root().for_each_in_inclusive_subtree_of_type<HTMLInputElement>([&](HTMLInputElement& input) {+ if (auto list = input.get_attribute(AttributeNames::list); list.has_value() && self.id() == *list)input.suggestions_source_element_did_change();return TraversalDecision::Continue;});- });+ }));}}diff --git a/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp b/Libraries/LibWeb/HTML/HTMLDetailsElement.cppindex d4aa6b8abf3..68b7ed449e1 100644--- a/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLDetailsElement.cpp@@ -121,18 +121,18 @@ void HTMLDetailsElement::queue_a_details_toggle_event_task(Utf16FlyString old_st}// 2. Queue an element task given the DOM manipulation task source and element to run the following steps:- auto task_id = queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, old_state, new_state = move(new_state)]() mutable {+ auto task_id = queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this, old_state, move(new_state)), [](auto& self, auto& old_state, auto& new_state) {// 1. Fire an event named toggle at element, using ToggleEvent, with the oldState attribute initialized to// oldState and the newState attribute initialized to newState.ToggleEventInit event_init {};event_init.old_state = move(old_state);event_init.new_state = move(new_state);- dispatch_event(ToggleEvent::create(HTML::EventNames::toggle, move(event_init), HighResolutionTime::current_high_resolution_time(relevant_global_object(*this))));+ self.dispatch_event(ToggleEvent::create(HTML::EventNames::toggle, move(event_init), HighResolutionTime::current_high_resolution_time(relevant_global_object(self))));// 2. Set element's details toggle task tracker to null.- m_details_toggle_task_tracker = {};- });+ self.m_details_toggle_task_tracker = {};+ }));// 3. Set element's details toggle task tracker to a struct with task set to the just-queued task and old state set to oldState.m_details_toggle_task_tracker = ToggleTaskTracker {diff --git a/Libraries/LibWeb/HTML/HTMLDialogElement.cpp b/Libraries/LibWeb/HTML/HTMLDialogElement.cppindex 6fb84e67df7..dfc218e2f20 100644--- a/Libraries/LibWeb/HTML/HTMLDialogElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLDialogElement.cpp@@ -78,7 +78,7 @@ void HTMLDialogElement::queue_a_dialog_toggle_event_task(Utf16FlyString old_stat}// 2. Queue an element task given the DOM manipulation task source and element to run the following steps:- auto task_id = queue_an_element_task(Task::Source::DOMManipulation, [this, old_state, new_state = move(new_state), source]() {+ auto task_id = queue_an_element_task(Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this, old_state, move(new_state), source), [](auto& self, auto& old_state, auto& new_state, auto& source) {// 1. Fire an event named toggle at element, using ToggleEvent, with the oldState attribute initialized to// oldState, the newState attribute initialized to newState, and the source attribute initialized to source.ToggleEventInit event_init {};@@ -86,11 +86,11 @@ void HTMLDialogElement::queue_a_dialog_toggle_event_task(Utf16FlyString old_statevent_init.new_state = move(new_state);event_init.source = source;- dispatch_event(ToggleEvent::create(HTML::EventNames::toggle, move(event_init), HighResolutionTime::current_high_resolution_time(relevant_global_object(*this))));+ self.dispatch_event(ToggleEvent::create(HTML::EventNames::toggle, move(event_init), HighResolutionTime::current_high_resolution_time(relevant_global_object(self))));// 2. Set element's dialog toggle task tracker to null.- m_dialog_toggle_task_tracker = {};- });+ self.m_dialog_toggle_task_tracker = {};+ }));// 3. Set element's dialog toggle task tracker to a struct with task set to the just-queued task and old state set to oldState.m_dialog_toggle_task_tracker = ToggleTaskTracker {@@ -388,10 +388,10 @@ void HTMLDialogElement::close_the_dialog(Optional<Utf16String> result, GC::Ptr<D// 13. Queue an element task on the user interaction task source given the subject element to fire an event named// close at subject.- queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {- auto close_event = DOM::Event::create(HTML::EventNames::close, HighResolutionTime::current_high_resolution_time(relevant_global_object(*this)));- dispatch_event(close_event);- });+ queue_an_element_task(HTML::Task::Source::UserInteraction, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ auto close_event = DOM::Event::create(HTML::EventNames::close, HighResolutionTime::current_high_resolution_time(relevant_global_object(self)));+ self.dispatch_event(close_event);+ }));}enum class ClosedByState : u8 {@@ -443,33 +443,33 @@ void HTMLDialogElement::set_close_watcher()// - cancelAction given canPreventClose being to return the result of firing an event named cancel at dialog,// with the cancelable attribute initialized to canPreventClose.auto cancel_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM& vm) {+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM& vm) {auto* event = Bindings::event_from_callback_argument(vm);VERIFY(event);bool can_prevent_close = event->cancelable();- auto should_continue = dispatch_event(DOM::Event::create(HTML::EventNames::cancel, { .cancelable = can_prevent_close }, HighResolutionTime::current_high_resolution_time(relevant_global_object(*this))));+ auto should_continue = self.dispatch_event(DOM::Event::create(HTML::EventNames::cancel, { .cancelable = can_prevent_close }, HighResolutionTime::current_high_resolution_time(relevant_global_object(self))));if (!should_continue)event->prevent_default();return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto cancel_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*cancel_callback_function, HTML::relevant_realm(*this));// - closeAction being to close the dialog given dialog, dialog's request close return value, and dialog's// request close source element.auto close_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM&) {- close_the_dialog(m_request_close_return_value, m_request_close_source_element);+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ self.close_the_dialog(self.m_request_close_return_value, self.m_request_close_source_element);return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto close_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*close_callback_function, HTML::relevant_realm(*this));// - getEnabledState being to return true if dialog's enable close watcher for request close is true or dialog's// computed closed-by state is not None; otherwise false.- auto get_enabled_state = GC::create_function(GC::Heap::the(), [dialog = this] {- if (dialog->m_enable_close_watcher_for_request_close)+ auto get_enabled_state = GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& dialog) {+ if (dialog.m_enable_close_watcher_for_request_close)return true;- return computed_closed_by_state(*dialog) != ClosedByState::None;+ return computed_closed_by_state(dialog) != ClosedByState::None;});m_close_watcher = CloseWatcher::establish(*document().window(), move(get_enabled_state));diff --git a/Libraries/LibWeb/HTML/HTMLElement.cpp b/Libraries/LibWeb/HTML/HTMLElement.cppindex e9bb979bd3e..e831c7b7f70 100644--- a/Libraries/LibWeb/HTML/HTMLElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLElement.cpp@@ -1915,11 +1915,11 @@ WebIDL::ExceptionOr<void> HTMLElement::show_popover(ThrowExceptions throw_except// NB: We simply don't add an event listener for the cancel action.// - closeAction being to hide a popover given element, true, true, false, and null.auto close_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM&) {- MUST(hide_popover(FocusPreviousElement::Yes, FireEvents::Yes, ThrowExceptions::No, IgnoreDomState::No, nullptr));+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ MUST(self.hide_popover(FocusPreviousElement::Yes, FireEvents::Yes, ThrowExceptions::No, IgnoreDomState::No, nullptr));return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto close_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*close_callback_function, HTML::relevant_realm(*this));// - getEnabledState being to return true.@@ -2429,7 +2429,7 @@ void HTMLElement::queue_a_popover_toggle_event_task(Utf16FlyString old_state, Ut}// 2. Queue an element task given the DOM manipulation task source and element to run the following steps:- auto task_id = queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, old_state, new_state = move(new_state), source]() mutable {+ auto task_id = queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this, old_state, move(new_state), source), [](auto& self, auto& old_state, auto& new_state, auto& source) {// 1. Fire an event named toggle at element, using ToggleEvent, with the oldState attribute initialized to// oldState, the newState attribute initialized to newState, and the source attribute initialized to source.ToggleEventInit event_init {};@@ -2437,11 +2437,11 @@ void HTMLElement::queue_a_popover_toggle_event_task(Utf16FlyString old_state, Utevent_init.new_state = move(new_state);event_init.source = GC::make_root<DOM::Element>(source.ptr());- dispatch_event(ToggleEvent::create(HTML::EventNames::toggle, move(event_init), HighResolutionTime::current_high_resolution_time(relevant_global_object(*this))));+ self.dispatch_event(ToggleEvent::create(HTML::EventNames::toggle, move(event_init), HighResolutionTime::current_high_resolution_time(relevant_global_object(self))));// 2. Set element's popover toggle task tracker to null.- ensure_html_element_rare_data().popover_toggle_task_tracker = {};- });+ self.ensure_html_element_rare_data().popover_toggle_task_tracker = {};+ }));// 3. Set element's popover toggle task tracker to a struct with task set to the just-queued task and old state set to oldState.popover_toggle_task_tracker = ToggleTaskTracker {diff --git a/Libraries/LibWeb/HTML/HTMLFormElement.cpp b/Libraries/LibWeb/HTML/HTMLFormElement.cppindex e8747f2a18d..e0ed2c5dfaf 100644--- a/Libraries/LibWeb/HTML/HTMLFormElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLFormElement.cpp@@ -1083,16 +1083,15 @@ void HTMLFormElement::plan_to_navigate_to(URL::URL url, DocumentResource post_re}// 4. Queue an element task on the DOM manipulation task source given the form element and the following steps:- // NOTE: `this`, `actual_resource`, `target_navigable` and `submitter` are protected by GC::HeapFunction.- queue_an_element_task(Task::Source::DOMManipulation, [this, url, post_resource, entry_list = move(entry_list), target_navigable, history_handling, referrer_policy, user_involvement, submitter]() {+ queue_an_element_task(Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this, url, post_resource, move(static_cast<Vector<XHR::FormDataEntry>&>(entry_list)), target_navigable, history_handling, referrer_policy, user_involvement, submitter), [](auto& self, auto& url, auto& post_resource, auto& entry_list, auto& target_navigable, auto& history_handling, auto& referrer_policy, auto& user_involvement, auto& submitter) {// 1. Set the form's planned navigation to null.- m_planned_navigation = {};+ self.m_planned_navigation = {};// 2. Navigate targetNavigable to url using the form element's node document, with historyHandling set to historyHandling,// userInvolvement set to userInvolvement, sourceElement set to submitter, referrerPolicy set to referrerPolicy,// documentResource set to postResource, and formDataEntryList set to entry list.- MUST(target_navigable->navigate({ .url = url, .source_document = this->document(), .document_resource = post_resource, .response = nullptr, .exceptions_enabled = false, .history_handling = history_handling, .form_data_entry_list = move(entry_list), .referrer_policy = referrer_policy, .user_involvement = user_involvement, .source_element = submitter }));- });+ MUST(target_navigable->navigate({ .url = url, .source_document = self.document(), .document_resource = post_resource, .response = nullptr, .exceptions_enabled = false, .history_handling = history_handling, .form_data_entry_list = GC::ConservativeVector<XHR::FormDataEntry> { move(entry_list) }, .referrer_policy = referrer_policy, .user_involvement = user_involvement, .source_element = submitter }));+ }));// 5. Set the form's planned navigation to the just-queued task.m_planned_navigation = HTML::main_thread_event_loop().task_queue().last_added_task();diff --git a/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp b/Libraries/LibWeb/HTML/HTMLIFrameElement.cppindex 89337b0b270..3b0d2c1a652 100644--- a/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLIFrameElement.cpp@@ -161,12 +161,12 @@ void HTMLIFrameElement::process_the_iframe_attributes(InitialInsertion initial_i// 2. If the will lazy load element steps given element return true, then:if (will_lazy_load_element()) {// 1. Set element's lazy load resumption steps to the rest of this algorithm starting with the step labeled navigate to the srcdoc resource.- set_lazy_load_resumption_steps([this]() {+ set_lazy_load_resumption_steps(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 3. Navigate to the srcdoc resource: navigate an iframe or frame given element, about:srcdoc, the empty string, and the value of element's srcdoc attribute.- navigate_an_iframe_or_frame(URL::about_srcdoc(), ReferrerPolicy::ReferrerPolicy::EmptyString, get_attribute_ns({}, HTML::AttributeNames::srcdoc));+ self.navigate_an_iframe_or_frame(URL::about_srcdoc(), ReferrerPolicy::ReferrerPolicy::EmptyString, self.get_attribute_ns({}, HTML::AttributeNames::srcdoc));// FIXME: The resulting Document must be considered an iframe srcdoc document.- });+ }));// 2. Set element's current navigation was lazy loaded boolean to true.set_current_navigation_was_lazy_loaded(true);@@ -212,10 +212,10 @@ void HTMLIFrameElement::process_the_iframe_attributes(InitialInsertion initial_i// 6. If the will lazy load element steps given element return true, then:if (will_lazy_load_element()) {// 1. Set element's lazy load resumption steps to the rest of this algorithm starting with the step labeled navigate.- set_lazy_load_resumption_steps([this, url, referrer_policy, initial_insertion]() {+ set_lazy_load_resumption_steps(GC::create_function(GC::Heap::the(), GC::captures(*this, url, referrer_policy, initial_insertion), [](auto& self, auto& url, auto& referrer_policy, auto& initial_insertion) {// 7. Navigate: Navigate an iframe or frame given element, url, referrerPolicy, null, and initialInsertion.- navigate_an_iframe_or_frame(*url, referrer_policy, {}, initial_insertion);- });+ self.navigate_an_iframe_or_frame(*url, referrer_policy, {}, initial_insertion);+ }));// 2. Set element's current navigation was lazy loaded boolean to true.set_current_navigation_was_lazy_loaded(true);@@ -272,9 +272,9 @@ void run_iframe_load_event_steps(HTMLIFrameElement& element)if (auto* local_navigable = as_if<LocalNavigable>(*element.content_navigable())) {if (auto active_document = local_navigable->active_document(); active_document && active_document->anything_is_delaying_the_load_event()) {auto element_ref = GC::Ref(element);- element.queue_an_element_task(HTML::Task::Source::DOMManipulation, [element_ref] {+ element.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(element_ref), [](auto& element_ref) {run_iframe_load_event_steps(element_ref);- });+ }));return;}}diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Libraries/LibWeb/HTML/HTMLImageElement.cppindex 60bd6c89f57..82b2911c7f0 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLImageElement.cpp@@ -124,9 +124,9 @@ void HTMLImageElement::initialize_element()// A document_became_active callback is set lazily by update_the_image_data() when// needed to restart image loading after the document becomes active again.m_document_observer = DOM::DocumentObserver::create(document());- m_document_observer->set_document_became_inactive([this]() {- m_load_event_delayer.clear();- });+ m_document_observer->set_document_became_inactive(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_load_event_delayer.clear();+ }));}// https://html.spec.whatwg.org/multipage/images.html#update-the-source-set@@ -677,56 +677,56 @@ void HTMLImageElement::decode(GC::Ref<WebIDL::Promise> promise) const// 1. Let promise be a new promise.// 2. Queue a microtask to perform the following steps:- queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), [this, promise]() mutable {+ queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), GC::captures(*this, promise), [](auto& self, auto& promise) {// 1. Let global be this's relevant global object.- auto& global = relevant_global_object(*this);+ auto& global = relevant_global_object(self);- auto reject_promise = [this, promise](Utf16String const& message) {+ auto reject_promise = GC::create_function(GC::Heap::the(), GC::captures(self, promise), [](auto& self, auto& promise, Utf16String const& message) {auto exception = WebIDL::EncodingError::create(message);- HTML::TemporaryExecutionContext context(document().relevant_settings_object());+ HTML::TemporaryExecutionContext context(self.document().relevant_settings_object());WebIDL::reject_promise(promise, exception);- };+ });- auto queue_reject_task = [reject_promise, &global](Utf16String const& message) {- queue_global_task(Task::Source::DOMManipulation, global, GC::create_function(GC::Heap::the(), [reject_promise, message = message] {- reject_promise(message);+ auto queue_reject_task = GC::create_function(GC::Heap::the(), GC::captures(reject_promise, global), [](auto& reject_promise, auto& global, Utf16String const& message) {+ queue_global_task(Task::Source::DOMManipulation, global, GC::create_function(GC::Heap::the(), GC::captures(reject_promise, message), [](auto& reject_promise, auto& message) {+ reject_promise->function()(message);}));- };+ });- auto queue_resolve_task = [this, promise, &global] {- queue_global_task(Task::Source::DOMManipulation, global, GC::create_function(GC::Heap::the(), [this, promise] {- HTML::TemporaryExecutionContext context(document().relevant_settings_object());+ auto queue_resolve_task = GC::create_function(GC::Heap::the(), GC::captures(self, promise, global), [](auto& self, auto& promise, auto& global) {+ queue_global_task(Task::Source::DOMManipulation, global, GC::create_function(GC::Heap::the(), GC::captures(self, promise), [](auto& self, auto& promise) {+ HTML::TemporaryExecutionContext context(self.document().relevant_settings_object());WebIDL::resolve_promise(promise);}));- };+ });// 2. If any of the following are true:// - this's node document is not fully active;- if (!document().is_fully_active()) {+ if (!self.document().is_fully_active()) {// then reject promise with an "EncodingError" DOMException.- reject_promise("Node document not fully active"_utf16);+ reject_promise->function()("Node document not fully active"_utf16);return;}// - or this's current request's state is broken,- auto& current_request = *m_current_request;+ auto& current_request = *self.m_current_request;if (current_request.state() == ImageRequest::State::Broken) {// then reject promise with an "EncodingError" DOMException.- reject_promise("Current request state is broken"_utf16);+ reject_promise->function()("Current request state is broken"_utf16);return;}- auto expected_request = m_current_request;- auto weak_this = GC::Weak<HTMLImageElement> { *this };+ auto expected_request = self.m_current_request;+ auto weak_this = GC::Weak<HTMLImageElement> { self };// 3. Otherwise, in parallel wait for one of the following cases to occur, and perform the corresponding actions:if (current_request.state() == ImageRequest::State::CompletelyAvailable) {- queue_resolve_task();+ queue_resolve_task->function()();return;}if (!current_request.shared_resource_request()) {- queue_reject_task("Current request changed or was mutated"_utf16);+ queue_reject_task->function()("Current request changed or was mutated"_utf16);return;}@@ -734,47 +734,47 @@ void HTMLImageElement::decode(GC::Ref<WebIDL::Promise> promise) const// AD-HOC: Queue a task to preserve ordering relative to update_the_image_data's step 16, which is queued the// same way. Otherwise decode() can resolve before the current request transitions to// CompletelyAvailable, leaving the image dimensions at zero when callers inspect them.- [weak_this, expected_request, queue_resolve_task, queue_reject_task] {- queue_image_task(weak_this ? &weak_this->document() : nullptr, GC::create_function(GC::Heap::the(), [weak_this, expected_request, queue_resolve_task, queue_reject_task] {+ GC::create_function(GC::Heap::the(), GC::captures(weak_this, expected_request, queue_resolve_task, queue_reject_task), [](auto& weak_this, auto& expected_request, auto& queue_resolve_task, auto& queue_reject_task) {+ queue_image_task(weak_this ? &weak_this->document() : nullptr, GC::create_function(GC::Heap::the(), GC::captures(weak_this, expected_request, queue_resolve_task, queue_reject_task), [](auto& weak_this, auto& expected_request, auto& queue_resolve_task, auto& queue_reject_task) {if (!weak_this) {- queue_reject_task("Image element no longer available"_utf16);+ queue_reject_task->function()("Image element no longer available"_utf16);return;}auto& image = *weak_this;if (!image.document().is_fully_active()) {- queue_reject_task("Node document not fully active"_utf16);+ queue_reject_task->function()("Node document not fully active"_utf16);return;}if (image.m_current_request != expected_request) {- queue_reject_task("Current request changed or was mutated"_utf16);+ queue_reject_task->function()("Current request changed or was mutated"_utf16);return;}if (image.current_request().state() == ImageRequest::State::Broken) {- queue_reject_task("Current request state is broken"_utf16);+ queue_reject_task->function()("Current request state is broken"_utf16);return;}- queue_resolve_task();+ queue_resolve_task->function()();}));- },- [weak_this, expected_request, queue_reject_task] {+ }),+ GC::create_function(GC::Heap::the(), GC::captures(weak_this, expected_request, queue_reject_task), [](auto& weak_this, auto& expected_request, auto& queue_reject_task) {if (!weak_this) {- queue_reject_task("Image element no longer available"_utf16);+ queue_reject_task->function()("Image element no longer available"_utf16);return;}auto& image = *weak_this;if (!image.document().is_fully_active()) {- queue_reject_task("Node document not fully active"_utf16);+ queue_reject_task->function()("Node document not fully active"_utf16);return;}if (image.m_current_request != expected_request) {- queue_reject_task("Current request changed or was mutated"_utf16);+ queue_reject_task->function()("Current request changed or was mutated"_utf16);return;}- queue_reject_task("Current request state is broken"_utf16);- });+ queue_reject_task->function()("Current request state is broken"_utf16);+ }));}));// 3. Return promise.@@ -882,11 +882,11 @@ void HTMLImageElement::update_the_image_data(bool restart_animations, bool maybe// 3. If another instance of this algorithm for this img element was started after this instance// (even if it aborted and is no longer running), then return.// 4. Queue a microtask to continue this algorithm.- m_document_observer->set_document_became_active([this, restart_animations, maybe_omit_events, update_the_image_data_count]() {- queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), [this, restart_animations, maybe_omit_events, update_the_image_data_count]() {- update_the_image_data_impl(restart_animations, maybe_omit_events, update_the_image_data_count);+ m_document_observer->set_document_became_active(GC::create_function(GC::Heap::the(), GC::captures(*this, restart_animations, maybe_omit_events, update_the_image_data_count), [](auto& self, auto& restart_animations, auto& maybe_omit_events, auto& update_the_image_data_count) {+ queue_a_microtask(&self.document(), GC::create_function(GC::Heap::the(), GC::captures(self, restart_animations, maybe_omit_events, update_the_image_data_count), [](auto& self, auto& restart_animations, auto& maybe_omit_events, auto& update_the_image_data_count) {+ self.update_the_image_data_impl(restart_animations, maybe_omit_events, update_the_image_data_count);}));- });+ }));return;}@@ -986,7 +986,7 @@ void HTMLImageElement::update_the_image_data_impl(bool restart_animations, boolset_needs_layout_update_or_repaint_after_image_data_change();// 7. Queue an element task on the DOM manipulation task source given the img element and following steps:- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, restart_animations, maybe_omit_events, url_string, previous_url, update_the_image_data_count] {+ queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this, restart_animations, maybe_omit_events, url_string, previous_url, update_the_image_data_count), [](auto& self, auto& restart_animations, auto& maybe_omit_events, auto& url_string, auto& previous_url, auto& update_the_image_data_count) {// AD-HOC: If another instance of this algorithm was started after this one, let that newer instance// fire the load event instead of firing one per instance. The spec only has this guard in the// microtask continuation below (step 9: "Only the last instance takes effect, to avoid@@ -994,29 +994,29 @@ void HTMLImageElement::update_the_image_data_impl(bool restart_animations, bool// set in succession."), but relevant mutations (e.g. setting src and then inserting into a// picture) can also invoke this algorithm several times in the same script block, and the// major engines coalesce those updates into a single load event.- if (update_the_image_data_count != m_update_the_image_data_count)+ if (update_the_image_data_count != self.m_update_the_image_data_count)return;// AD-HOC: Bail out if the document became inactive (e.g. iframe removed or navigated)// between when this task was queued and when it runs.- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}// 1. If restart animation is set, then restart the animation.if (restart_animations)- restart_the_animation();+ self.restart_the_animation();// 2. Set the current request's current URL to urlString.- m_current_request->set_current_url(document(), *url_string, m_cors_setting);+ self.m_current_request->set_current_url(self.document(), *url_string, self.m_cors_setting);// 3. If maybe omit events is not set or previousURL is not equal to urlString, then fire an event named load at the img element.if (!maybe_omit_events || previous_url != *url_string) {- associated_image_request_became_completely_available(*m_current_request);- dispatch_event(DOM::Event::create(HTML::relevant_global_object(*this), HTML::EventNames::load));+ self.associated_image_request_became_completely_available(*self.m_current_request);+ self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::load));}- });+ }));// 8. Abort the update the image data algorithm.return;@@ -1024,16 +1024,16 @@ void HTMLImageElement::update_the_image_data_impl(bool restart_animations, bool}after_step_7:// 8. Queue a microtask to perform the rest of this algorithm, allowing the task that invoked this algorithm to continue.- queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), [this, update_the_image_data_count, restart_animations, maybe_omit_events, previous_url]() mutable {+ queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), GC::captures(*this, update_the_image_data_count, restart_animations, maybe_omit_events, previous_url), [](auto& self, auto& update_the_image_data_count, auto& restart_animations, auto& maybe_omit_events, auto& previous_url) {// 9. If another instance of this algorithm for this img element was started after this instance// (even if it aborted and is no longer running), then return.- if (update_the_image_data_count != m_update_the_image_data_count)+ if (update_the_image_data_count != self.m_update_the_image_data_count)return;// AD-HOC: Bail out if the document became inactive (e.g. iframe removed or navigated)// between when this microtask was queued and when it runs.- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}@@ -1041,7 +1041,7 @@ after_step_7:// the URL and pixel density that results from selecting an image source, respectively.Optional<ImageSource> selected_source;Optional<float> pixel_density;- if (auto result = select_an_image_source(); result.has_value()) {+ if (auto result = self.select_an_image_source(); result.has_value()) {selected_source = result.value().source;pixel_density = result.value().pixel_density;}@@ -1054,87 +1054,87 @@ after_step_7:// at selection time and deliberately skips same-candidate updates on environment changes to avoid// spurious downloads. Spec issue: https://github.com/whatwg/html/issues/4646if (selected_source.has_value())- m_last_selected_source = selected_source->url;+ self.m_last_selected_source = selected_source->url;// 11. If selected source is null, then:if (!selected_source.has_value()) {// 1. Set the current request's state to broken,// abort the image request for the current request and the pending request,// and set the pending request to null.- m_current_request->set_state(ImageRequest::State::Broken);- unregister_with_decoded_image_data_if_needed();- abort_the_image_request(m_current_request);- abort_the_image_request(m_pending_request);- stop_delaying_the_load_event_for_aborted_requests();- m_pending_request = nullptr;+ self.m_current_request->set_state(ImageRequest::State::Broken);+ self.unregister_with_decoded_image_data_if_needed();+ abort_the_image_request(self.m_current_request);+ abort_the_image_request(self.m_pending_request);+ self.stop_delaying_the_load_event_for_aborted_requests();+ self.m_pending_request = nullptr;// AD-HOC: The element may have been rendering as blank space while a load was pending;// now that the current request is broken it renders its alt text instead.- set_needs_layout_update_or_repaint_after_image_data_change();+ self.set_needs_layout_update_or_repaint_after_image_data_change();// 2. Queue an element task on the DOM manipulation task source given the img element and the following steps:- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, maybe_omit_events, previous_url] {+ self.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(self, maybe_omit_events), [](auto& self, auto& maybe_omit_events) {// AD-HOC: Bail out if the document became inactive (e.g. iframe removed or navigated)// between when this task was queued and when it runs.- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}// 1. Change the current request's current URL to the empty string.- m_current_request->set_current_url(document(), Utf16String {}, m_cors_setting);+ self.m_current_request->set_current_url(self.document(), Utf16String {}, self.m_cors_setting);// 2. If all of the following conditions are true:// - the element has a src attribute or it uses srcset or picture; and// - maybe omit events is not set or previousURL is not the empty stringif (- (has_attribute(HTML::AttributeNames::src) || uses_srcset_or_picture())- && (!maybe_omit_events || !m_current_request->current_url().is_empty())) {- dispatch_event(DOM::Event::create(HTML::relevant_global_object(*this), HTML::EventNames::error));+ (self.has_attribute(HTML::AttributeNames::src) || self.uses_srcset_or_picture())+ && (!maybe_omit_events || !self.m_current_request->current_url().is_empty())) {+ self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::error));}- });+ }));// 3. Return.return;}// 12. Let urlString be the result of encoding-parsing-and-serializing a URL given selected source, relative to the element's node document.- auto url_string = document().encoding_parse_and_serialize_url(selected_source.value().url);+ auto url_string = self.document().encoding_parse_and_serialize_url(selected_source.value().url);// 13. If urlString is failure, then:if (!url_string.has_value()) {// 1. Abort the image request for the current request and the pending request.- unregister_with_decoded_image_data_if_needed();- abort_the_image_request(m_current_request);- abort_the_image_request(m_pending_request);- stop_delaying_the_load_event_for_aborted_requests();+ self.unregister_with_decoded_image_data_if_needed();+ abort_the_image_request(self.m_current_request);+ abort_the_image_request(self.m_pending_request);+ self.stop_delaying_the_load_event_for_aborted_requests();// 2. Set the current request's state to broken.- m_current_request->set_state(ImageRequest::State::Broken);+ self.m_current_request->set_state(ImageRequest::State::Broken);// 3. Set the pending request to null.- m_pending_request = nullptr;+ self.m_pending_request = nullptr;// AD-HOC: The element may have been rendering as blank space while a load was pending;// now that the current request is broken it renders its alt text instead.- set_needs_layout_update_or_repaint_after_image_data_change();+ self.set_needs_layout_update_or_repaint_after_image_data_change();// 4. Queue an element task on the DOM manipulation task source given the img element and the following steps:- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, selected_source, maybe_omit_events, previous_url] {+ self.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(self, selected_source->url, maybe_omit_events, previous_url), [](auto& self, auto& selected_source_url, auto& maybe_omit_events, auto& previous_url) {// AD-HOC: Bail out if the document became inactive (e.g. iframe removed or navigated)// between when this task was queued and when it runs.- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}// 1. Change the current request's current URL to selected source.- m_current_request->set_current_url(document(), selected_source.value().url, m_cors_setting);+ self.m_current_request->set_current_url(self.document(), selected_source_url, self.m_cors_setting);// 2. If maybe omit events is not set or previousURL is not equal to selected source, then fire an event named error at the img element.- if (!maybe_omit_events || previous_url != selected_source.value().url)- dispatch_event(create_event_for_element(*this, HTML::EventNames::error));- });+ if (!maybe_omit_events || previous_url != selected_source_url)+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));+ }));// 5. Return.return;@@ -1145,48 +1145,48 @@ after_step_7:// not make the image disappear while the higher-layer cache processes the same resource again.ListOfAvailableImages::Key key;key.url = *url_string;- key.mode = m_cors_setting;- if (m_cors_setting != CORSSettingAttribute::NoCORS)- key.origin = document().origin();- if (auto* entry = document().list_of_available_images().get(key)) {+ key.mode = self.m_cors_setting;+ if (self.m_cors_setting != CORSSettingAttribute::NoCORS)+ key.origin = self.document().origin();+ if (auto* entry = self.document().list_of_available_images().get(key)) {entry->ignore_higher_layer_caching = true;- unregister_with_decoded_image_data_if_needed();- abort_the_image_request(m_current_request);- abort_the_image_request(m_pending_request);- m_pending_request = nullptr;- m_load_event_delayer.clear();+ self.unregister_with_decoded_image_data_if_needed();+ abort_the_image_request(self.m_current_request);+ abort_the_image_request(self.m_pending_request);+ self.m_pending_request = nullptr;+ self.m_load_event_delayer.clear();- m_current_request = ImageRequest::create();- m_current_request->set_image_data(entry->image_data);- m_current_request->set_state(ImageRequest::State::CompletelyAvailable);- m_current_request->set_current_pixel_density(pixel_density.value_or(1.0f));- register_with_decoded_image_data_if_needed();- m_current_request->prepare_for_presentation(*this);+ self.m_current_request = ImageRequest::create();+ self.m_current_request->set_image_data(entry->image_data);+ self.m_current_request->set_state(ImageRequest::State::CompletelyAvailable);+ self.m_current_request->set_current_pixel_density(pixel_density.value_or(1.0f));+ self.register_with_decoded_image_data_if_needed();+ self.m_current_request->prepare_for_presentation(self);- set_needs_layout_update_or_repaint_after_image_data_change();+ self.set_needs_layout_update_or_repaint_after_image_data_change();- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, restart_animations, maybe_omit_events, url_string, previous_url, update_the_image_data_count] {- if (update_the_image_data_count != m_update_the_image_data_count)+ self.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(self, restart_animations, maybe_omit_events, url_string, previous_url, update_the_image_data_count), [](auto& self, auto& restart_animations, auto& maybe_omit_events, auto& url_string, auto& previous_url, auto& update_the_image_data_count) {+ if (update_the_image_data_count != self.m_update_the_image_data_count)return;- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}if (restart_animations)- restart_the_animation();- m_current_request->set_current_url(document(), *url_string, m_cors_setting);+ self.restart_the_animation();+ self.m_current_request->set_current_url(self.document(), *url_string, self.m_cors_setting);if (!maybe_omit_events || previous_url != *url_string) {- associated_image_request_became_completely_available(*m_current_request);- dispatch_event(DOM::Event::create(HTML::relevant_global_object(*this), HTML::EventNames::load));+ self.associated_image_request_became_completely_available(*self.m_current_request);+ self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::load));}- });+ }));return;}// 14. If the pending request is not null and urlString is the same as the pending request's current URL, then return.- if (m_pending_request && *url_string == m_pending_request->current_url()) {- auto resumption_steps = take_lazy_load_resumption_steps_internal();+ if (self.m_pending_request && *url_string == self.m_pending_request->current_url()) {+ auto resumption_steps = self.take_lazy_load_resumption_steps_internal();if (!resumption_steps)return;// NB: Retire the superseded lazy continuation and recreate it below for this update.@@ -1195,16 +1195,16 @@ after_step_7:// 15. If urlString is the same as the current request's current URL and the current request's state is// partially available:- if (*url_string == m_current_request->current_url() && m_current_request->state() == ImageRequest::State::PartiallyAvailable) {+ if (*url_string == self.m_current_request->current_url() && self.m_current_request->state() == ImageRequest::State::PartiallyAvailable) {// 1. Abort the image request for the pending request.- abort_the_image_request(m_pending_request);+ abort_the_image_request(self.m_pending_request);// 2. If restart animation is set, then queue an element task on the DOM manipulation task source given the// img element to restart the animation.if (restart_animations) {- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {- restart_the_animation();- });+ self.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {+ self.restart_the_animation();+ }));}// 3. Return.@@ -1212,43 +1212,43 @@ after_step_7:}// 16. If the pending request is not null, then abort the image request for the pending request.- abort_the_image_request(m_pending_request);+ abort_the_image_request(self.m_pending_request);// AD-HOC: At this point we start deviating from the spec in order to allow sharing ImageRequest between// multiple image elements (as well as CSS background-images, etc.)// 17. Set image request to a new image request whose current URL is urlString.auto image_request = ImageRequest::create();- if (auto resource = exchange(m_resource_from_navigation_response, nullptr))+ if (auto resource = exchange(self.m_resource_from_navigation_response, nullptr))image_request->set_current_url(*url_string, *resource);else- image_request->set_current_url(document(), *url_string, m_cors_setting);+ image_request->set_current_url(self.document(), *url_string, self.m_cors_setting);image_request->set_current_pixel_density(pixel_density.value_or(1.0f));// 18. If the current request's state is unavailable or broken, then set the current request to image request.// Otherwise, set the pending request to image request.- if (m_current_request->state() == ImageRequest::State::Unavailable || m_current_request->state() == ImageRequest::State::Broken) {- unregister_with_decoded_image_data_if_needed();- m_current_request = image_request;- register_with_decoded_image_data_if_needed();- CSS::record_element_replaced_content_input(*this);+ if (self.m_current_request->state() == ImageRequest::State::Unavailable || self.m_current_request->state() == ImageRequest::State::Broken) {+ self.unregister_with_decoded_image_data_if_needed();+ self.m_current_request = image_request;+ self.register_with_decoded_image_data_if_needed();+ CSS::record_element_replaced_content_input(self);} else {- m_pending_request = image_request;+ self.m_pending_request = image_request;}// A valid selected source is expected to produce image data, so it renders as blank while// loading instead of continuing to expose fallback text from a previous broken request.- remove_alt_text_shadow_tree();+ self.remove_alt_text_shadow_tree();// 24. Let delay load event be true if the img's lazy loading attribute is in the Eager state, or if scripting is disabled for the img, and false otherwise.- auto delay_load_event = lazy_loading_attribute() == LazyLoading::Eager;+ auto delay_load_event = self.lazy_loading_attribute() == LazyLoading::Eager;// When delay load event is true, fetching the image must delay the load event of the element's node document// until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.if (delay_load_event)- m_load_event_delayer.emplace(document());+ self.m_load_event_delayer.emplace(self.document());- add_callbacks_to_image_request(*image_request, maybe_omit_events, url_string->utf16_view(), previous_url.utf16_view(),+ self.add_callbacks_to_image_request(*image_request, maybe_omit_events, url_string->utf16_view(), previous_url.utf16_view(),delay_load_event ? SharedResourceRequest::DelaysLoadEvent::Yes : SharedResourceRequest::DelaysLoadEvent::No);// AD-HOC: If the image request is already available or fetching, no need to start another fetch.@@ -1256,46 +1256,46 @@ after_step_7:return;// AD-HOC: create_potential_CORS_request expects a url, but the following step passes a URL string.- auto url_record = document().encoding_parse_url(selected_source.value().url);+ auto url_record = self.document().encoding_parse_url(selected_source.value().url);VERIFY(url_record.has_value());// 19. Let request be the result of creating a potential-CORS request given urlString, "image",// and the current state of the element's crossorigin content attribute.- auto request = create_potential_CORS_request(*url_record, Fetch::Infrastructure::Request::Destination::Image, m_cors_setting);+ auto request = create_potential_CORS_request(*url_record, Fetch::Infrastructure::Request::Destination::Image, self.m_cors_setting);// 20. Set request's client to the element's node document's relevant settings object.- request->set_client(document().relevant_settings_object().address());+ request->set_client(self.document().relevant_settings_object().address());// AD-HOC: The spec doesn't set an initiator type for img requests, so they would never report resource timing.// Spec PR: https://github.com/whatwg/html/pull/13101request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::IMG);// 21. If the element uses srcset or picture, set request's initiator to "imageset".- if (uses_srcset_or_picture())+ if (self.uses_srcset_or_picture())request->set_initiator(Fetch::Infrastructure::Request::Initiator::ImageSet);// 22. Set request's referrer policy to the current state of the element's referrerpolicy attribute.- request->set_referrer_policy(ReferrerPolicy::from_string(attribute(HTML::AttributeNames::referrerpolicy).value_or({})).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString));+ request->set_referrer_policy(ReferrerPolicy::from_string(self.attribute(HTML::AttributeNames::referrerpolicy).value_or({})).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString));// 23. Set request's priority to the current state of the element's fetchpriority attribute.- request->set_priority(Fetch::Infrastructure::request_priority_from_string(attribute(HTML::AttributeNames::fetchpriority).value_or({})).value_or(Fetch::Infrastructure::Request::Priority::Auto));+ request->set_priority(Fetch::Infrastructure::request_priority_from_string(self.attribute(HTML::AttributeNames::fetchpriority).value_or({})).value_or(Fetch::Infrastructure::Request::Priority::Auto));// 25. If the will lazy load element steps given the img return true, then:// INTEROP: Like Blink and WebKit, only defer until the image first resumes lazy loading.// Subsequent source changes must not wait for another intersection observation.- if (!m_has_resumed_lazy_loading && will_lazy_load_element()) {+ if (!self.m_has_resumed_lazy_loading && self.will_lazy_load_element()) {// 1. Set the img's lazy load resumption steps to the rest of this algorithm starting with the step labeled fetch the image.- set_lazy_load_resumption_steps([this, request, image_request, update_the_image_data_count, observing_document = GC::Ref { document() }]() {+ self.set_lazy_load_resumption_steps(GC::create_function(GC::Heap::the(), GC::captures(self, request, image_request, update_the_image_data_count, GC::Ref { self.document() }), [](auto& self, auto& request, auto& image_request, auto& update_the_image_data_count, auto& observing_document) {// NB: Unobserve in the document which registered the image, including after adoption.- observing_document->stop_intersection_observing_a_lazy_loading_element(*this);- if (update_the_image_data_count != m_update_the_image_data_count)+ observing_document->stop_intersection_observing_a_lazy_loading_element(self);+ if (update_the_image_data_count != self.m_update_the_image_data_count)return;- m_has_resumed_lazy_loading = true;+ self.m_has_resumed_lazy_loading = true;image_request->fetch_image(request);- });+ }));// 2. Start intersection-observing a lazy loading element for the img element.- document().start_intersection_observing_a_lazy_loading_element(*this);+ self.document().start_intersection_observing_a_lazy_loading_element(self);// 3. Return.return;@@ -1318,12 +1318,12 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imagcache_key.origin = originating_document->origin();image_request->add_callbacks(- [this, image_request, maybe_omit_events, url_string = captured_url_string, previous_url = captured_previous_url, originating_document, cache_key]() {- queue_image_task(document(), GC::create_function(GC::Heap::the(), [this, image_request, maybe_omit_events, url_string, previous_url, originating_document, cache_key] {+ GC::create_function(GC::Heap::the(), GC::captures(*this, image_request, maybe_omit_events, captured_url_string, captured_previous_url, originating_document, cache_key), [](auto& self, auto& image_request, auto& maybe_omit_events, auto& url_string, auto& previous_url, auto& originating_document, auto& cache_key) {+ queue_image_task(self.document(), GC::create_function(GC::Heap::the(), GC::captures(self, image_request, maybe_omit_events, url_string, previous_url, originating_document, cache_key), [](auto& self, auto& image_request, auto& maybe_omit_events, auto& url_string, auto& previous_url, auto& originating_document, auto& cache_key) {// AD-HOC: Bail out if the document became inactive (e.g. iframe removed or navigated)// between when the fetch completed and when this task runs.- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}@@ -1332,8 +1332,8 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imag// request. Note that a newer instance of update_the_image_data may have run and left// this request in place (e.g. when the src attribute is set to the same URL twice in a// row); the callback is then still responsible for finishing the load.- if (image_request->was_aborted() || (image_request != m_current_request && image_request != m_pending_request)) {- m_load_event_delayer.clear();+ if (image_request->was_aborted() || (image_request != self.m_current_request && image_request != self.m_pending_request)) {+ self.m_load_event_delayer.clear();return;}@@ -1344,14 +1344,14 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imag// 1. If image request is the pending request, abort the image request for the current request,// upgrade the pending request to the current request// and prepare image request for presentation given the img element.- if (image_request == m_pending_request) {- unregister_with_decoded_image_data_if_needed();- abort_the_image_request(m_current_request);- upgrade_pending_request_to_current_request();- image_request->prepare_for_presentation(*this);+ if (image_request == self.m_pending_request) {+ self.unregister_with_decoded_image_data_if_needed();+ abort_the_image_request(self.m_current_request);+ self.upgrade_pending_request_to_current_request();+ image_request->prepare_for_presentation(self);}- register_with_decoded_image_data_if_needed();+ self.register_with_decoded_image_data_if_needed();// 2. Set image request to the completely available state.image_request->set_state(ImageRequest::State::CompletelyAvailable);@@ -1363,22 +1363,22 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imagoriginating_document->list_of_available_images().add(cache_key, *image_data, true);originating_document->prune_image_resource_caches();- set_needs_layout_update_or_repaint_after_image_data_change();+ self.set_needs_layout_update_or_repaint_after_image_data_change();// 4. If maybe omit events is not set or previousURL is not equal to urlString, then fire an event named load at the img element.if (!maybe_omit_events || previous_url != url_string) {- associated_image_request_became_completely_available(*image_request);- dispatch_event(create_event_for_element(*this, HTML::EventNames::load));+ self.associated_image_request_became_completely_available(*image_request);+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::load));}- m_load_event_delayer.clear();+ self.m_load_event_delayer.clear();}));- },- [this, image_request, maybe_omit_events, url_string = captured_url_string, previous_url = captured_previous_url]() {+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this, image_request, maybe_omit_events, captured_url_string, captured_previous_url), [](auto& self, auto& image_request, auto& maybe_omit_events, auto& url_string, auto& previous_url) {// AD-HOC: Bail out if the document became inactive (e.g. iframe removed or navigated)// between when the fetch completed and when this failure callback runs.- if (!document().is_fully_active()) {- m_load_event_delayer.clear();+ if (!self.document().is_fully_active()) {+ self.m_load_event_delayer.clear();return;}@@ -1389,8 +1389,8 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imag// request. Note that a newer instance of update_the_image_data may have run and left// this request in place (e.g. when the src attribute is set to the same URL twice in a// row); the callback is then still responsible for finishing the load.- if (image_request->was_aborted() || (image_request != m_current_request && image_request != m_pending_request)) {- m_load_event_delayer.clear();+ if (image_request->was_aborted() || (image_request != self.m_current_request && image_request != self.m_pending_request)) {+ self.m_load_event_delayer.clear();return;}@@ -1398,29 +1398,29 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imagimage_request->set_state(ImageRequest::State::Broken);// abort the image request for the current request and the pending request,- unregister_with_decoded_image_data_if_needed();- abort_the_image_request(m_current_request);- abort_the_image_request(m_pending_request);+ self.unregister_with_decoded_image_data_if_needed();+ abort_the_image_request(self.m_current_request);+ abort_the_image_request(self.m_pending_request);// upgrade the pending request to the current request if image request is the pending request,- if (image_request == m_pending_request)- upgrade_pending_request_to_current_request();+ if (image_request == self.m_pending_request)+ self.upgrade_pending_request_to_current_request();// AD-HOC: The element may have been rendering as blank space while the load was pending;// now that the current request is broken it renders its alt text instead.- set_needs_layout_update_or_repaint_after_image_data_change();+ self.set_needs_layout_update_or_repaint_after_image_data_change();// and then, if maybe omit events is not set or previousURL is not equal to urlString,// queue an element task on the DOM manipulation task source given the img element// to fire an event named error at the img element.if (!maybe_omit_events || previous_url != url_string)- dispatch_event(create_event_for_element(*this, HTML::EventNames::error));+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));- m_load_event_delayer.clear();- },- [this] {- m_load_event_delayer.clear();- },+ self.m_load_event_delayer.clear();+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_load_event_delayer.clear();+ }),delays_load_event);}@@ -1440,8 +1440,8 @@ void HTMLImageElement::did_set_viewport_rect(CSSPixelRect const& viewport_rect)return;m_last_seen_viewport_size = viewport_rect.size();update_dimension_attribute_source(*this);- queue_image_task(document(), GC::create_function(GC::Heap::the(), [this] {- react_to_changes_in_the_environment();+ queue_image_task(document(), GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.react_to_changes_in_the_environment();}));}@@ -1512,44 +1512,44 @@ void HTMLImageElement::react_to_changes_in_the_environment()// FIXME: 14. End the synchronous section, continuing the remaining steps in parallel.- auto step_16 = [this](Utf16String const& selected_source, GC::Ref<ImageRequest> image_request, ListOfAvailableImages::Key const& key, GC::Ref<DecodedImageData> image_data) {+ auto step_16 = GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self, Utf16String const& selected_source, GC::Ref<ImageRequest> image_request, ListOfAvailableImages::Key const& key, GC::Ref<DecodedImageData> image_data) {// 16. Queue an element task on the DOM manipulation task source given the img element and the following steps:- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, selected_source, image_request, key, image_data] {+ self.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(self, selected_source, image_request, key, image_data), [](auto& self, auto& selected_source, auto& image_request, auto& key, auto& image_data) {// 1. FIXME: If the img element has experienced relevant mutations since this algorithm started, then set the pending request to null and abort these steps.// AD-HOC: Check if we have a pending request still, otherwise we will crash when upgrading the request. This will happen if the image has experienced mutations,// but since the pending request may be set by another task soon after it is cleared, this check is probably not sufficient.- if (!m_pending_request)+ if (!self.m_pending_request)return;// 2. Set the img element's last selected source to selected source and the img element's current pixel density to selected pixel density.- m_last_selected_source = selected_source;+ self.m_last_selected_source = selected_source;// 3. Set the image request's state to completely available.image_request->set_state(ImageRequest::State::CompletelyAvailable);// 4. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.- document().list_of_available_images().add(key, image_data, true);- document().prune_image_resource_caches();+ self.document().list_of_available_images().add(key, image_data, true);+ self.document().prune_image_resource_caches();// 5. Upgrade the pending request to the current request.- upgrade_pending_request_to_current_request();+ self.upgrade_pending_request_to_current_request();// 6. Prepare image request for presentation given the img element.- image_request->prepare_for_presentation(*this);+ image_request->prepare_for_presentation(self);// FIXME: This is ad-hoc, updating the layout here should probably be handled by prepare_for_presentation().- set_needs_layout_update_or_repaint_after_image_data_change();+ self.set_needs_layout_update_or_repaint_after_image_data_change();// 7. Fire an event named load at the img element.- associated_image_request_became_completely_available(*image_request);- dispatch_event(create_event_for_element(*this, HTML::EventNames::load));- });- };+ self.associated_image_request_became_completely_available(*image_request);+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::load));+ }));+ });// 15. If the list of available images contains an entry for key, then set image request's image data to that of the entry.// Continue to the next step.if (auto* entry = document().list_of_available_images().get(key)) {image_request->set_image_data(entry->image_data);- step_16(selected_source.value(), *image_request, key, entry->image_data);+ step_16->function()(selected_source.value(), *image_request, key, entry->image_data);}// Otherwise:else {@@ -1575,7 +1575,7 @@ void HTMLImageElement::react_to_changes_in_the_environment()// Set the callbacks to handle steps 6 and 7 before starting the fetch request.image_request->add_callbacks(- [this, step_16, selected_source = selected_source.value(), image_request, key]() mutable {+ GC::create_function(GC::Heap::the(), GC::captures(*this, step_16, selected_source.value(), image_request, key), [](auto& self, auto& step_16, auto& selected_source, auto& image_request, auto& key) {// 6. If response's unsafe response is a network error// NOTE: This is handled in the second callback below.@@ -1589,23 +1589,23 @@ void HTMLImageElement::react_to_changes_in_the_environment()// then set the pending request to null and abort these steps.- queue_image_task(document(), GC::create_function(GC::Heap::the(), [step_16, selected_source = move(selected_source), image_request, key] {+ queue_image_task(self.document(), GC::create_function(GC::Heap::the(), GC::captures(step_16, move(selected_source), image_request, key), [](auto& step_16, auto& selected_source, auto& image_request, auto& key) {// 7. Otherwise, response's unsafe response is image request's image data. It can be either CORS-same-origin// or CORS-cross-origin; this affects the image's interaction with other APIs (e.g., when used on a canvas).VERIFY(image_request->shared_resource_request());auto image_data = image_request->shared_resource_request()->image_data();image_request->set_image_data(image_data);- step_16(selected_source, image_request, key, *image_data);+ step_16->function()(selected_source, image_request, key, *image_data);}));- },- [this]() {+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 6. If response's unsafe response is a network error// or if the image format is unsupported (as determined by applying the image sniffing rules, again as mentioned earlier),// ...// or if the user agent is able to determine that image request's image is corrupted in some// fatal way such that the image dimensions cannot be obtained,- m_pending_request = nullptr;- });+ self.m_pending_request = nullptr;+ }));// 5. Let response be the result of fetching request.image_request->fetch_image(request);diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cppindex 61ee3bcaa45..ccec3dbf98a 100644--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp@@ -650,9 +650,9 @@ void HTMLInputElement::did_select_files(Span<SelectedFile> selected_files, Multi// interaction task source given element to fire an event named cancel at element, with the bubbles attribute// initialized to true.if (selected_files.is_empty()) {- queue_an_element_task(HTML::Task::Source::UserInteraction, [this]() {- dispatch_event(create_event_for_element(*this, HTML::EventNames::cancel, { .bubbles = true }));- });+ queue_an_element_task(HTML::Task::Source::UserInteraction, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::cancel, { .bubbles = true }));+ }));return;}@@ -1340,20 +1340,20 @@ void HTMLInputElement::create_text_input_shadow_tree()MUST(stepper_container->append_child(*m_up_button_element));auto mouseup_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM&) {- commit_pending_changes();+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ self.commit_pending_changes();return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto mouseup_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mouseup_callback_function, HTML::relevant_realm(*this));DOM::EventTarget::AddEventListenerOptions mouseup_listener_options;mouseup_listener_options.once = true;auto up_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM&) {- step_for_user_interaction(StepDirection::Up, CommitChange::No);+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ self.step_for_user_interaction(StepDirection::Up, CommitChange::No);return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto step_up_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*up_callback_function, HTML::relevant_realm(*this));m_up_button_element->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(step_up_callback));@@ -1377,10 +1377,10 @@ void HTMLInputElement::create_text_input_shadow_tree()MUST(stepper_container->append_child(*m_down_button_element));auto down_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM&) {- step_for_user_interaction(StepDirection::Down, CommitChange::No);+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ self.step_for_user_interaction(StepDirection::Down, CommitChange::No);return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto step_down_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*down_callback_function, HTML::relevant_realm(*this));m_down_button_element->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(step_down_callback));@@ -1408,10 +1408,10 @@ void HTMLInputElement::create_text_input_shadow_tree()MUST(icon->append_child(icon_path));auto open_picker_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM&) {- show_the_picker_if_applicable(*this);+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ show_the_picker_if_applicable(self);return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto open_picker_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*open_picker_function, HTML::relevant_realm(*this));picker_indicator->add_event_listener_without_options(UIEvents::EventNames::click, DOM::IDLEventListener::create(open_picker_callback));@@ -1470,13 +1470,13 @@ void HTMLInputElement::create_file_input_shadow_tree()m_file_label = DOM::create_element(document(), HTML::TagNames::label, Namespace::HTML).release_value_but_fixme_should_propagate_errors();m_file_label->set_attribute_value(HTML::AttributeNames::style, "padding-left: 4px;"_utf16);- auto on_button_click = [this](JS::VM&) {- show_the_picker_if_applicable(*this);+ auto on_button_click = GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM&) {+ show_the_picker_if_applicable(self);return JS::js_undefined();- };+ });auto& realm = HTML::relevant_realm(*this);- auto on_button_click_function = JS::NativeFunction::create(realm, move(on_button_click), 0, Utf16FlyString {}, &realm);+ auto on_button_click_function = JS::NativeFunction::create(realm, on_button_click, 0, Utf16FlyString {}, &realm);auto on_button_click_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(on_button_click_function, realm);m_file_button->add_event_listener_without_options(UIEvents::EventNames::click, DOM::IDLEventListener::create(on_button_click_callback));@@ -1535,10 +1535,10 @@ void HTMLInputElement::create_range_input_shadow_tree()update_slider_shadow_tree_elements();auto keydown_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM& vm) {- if (type_state() != TypeAttributeState::Range)+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](HTMLInputElement& self, JS::VM& vm) {+ if (self.type_state() != TypeAttributeState::Range)return JS::js_undefined();- if (!allowed_value_step().has_value())+ if (!self.allowed_value_step().has_value())return JS::js_undefined();auto key_value = MUST(vm.argument(0).get(vm, "key"_utf16_fly_string));if (!key_value.is_string())@@ -1546,45 +1546,45 @@ void HTMLInputElement::create_range_input_shadow_tree()auto key = key_value.as_string().utf16_string_view();if (key == u"ArrowLeft"sv || key == u"ArrowDown"sv)- MUST(step_down());+ MUST(self.step_down());if (key == u"PageDown"sv)- MUST(step_down(10));+ MUST(self.step_down(10));if (key == u"ArrowRight"sv || key == u"ArrowUp"sv)- MUST(step_up());+ MUST(self.step_up());if (key == u"PageUp"sv)- MUST(step_up(10));+ MUST(self.step_up(10));- user_interaction_did_change_input_value();+ self.user_interaction_did_change_input_value();return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto keydown_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*keydown_callback_function, HTML::relevant_realm(*this));add_event_listener_without_options(UIEvents::EventNames::keydown, DOM::IDLEventListener::create(keydown_callback));auto wheel_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM& vm) {- if (type_state() != TypeAttributeState::Range)+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](HTMLInputElement& self, JS::VM& vm) {+ if (self.type_state() != TypeAttributeState::Range)return JS::js_undefined();- if (!allowed_value_step().has_value())+ if (!self.allowed_value_step().has_value())return JS::js_undefined();auto delta_y_value = MUST(vm.argument(0).get(vm, "deltaY"_utf16_fly_string));if (!delta_y_value.is_finite_number())return JS::js_undefined();if (delta_y_value.as_double() > 0) {- MUST(step_down());+ MUST(self.step_down());} else {- MUST(step_up());+ MUST(self.step_up());}- user_interaction_did_change_input_value();+ self.user_interaction_did_change_input_value();return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto wheel_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*wheel_callback_function, HTML::relevant_realm(*this));add_event_listener_without_options(UIEvents::EventNames::wheel, DOM::IDLEventListener::create(wheel_callback));- auto update_slider_by_mouse = [this](JS::VM& vm) {- if (type_state() != TypeAttributeState::Range)+ auto update_slider_by_mouse = GC::create_function<void(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](HTMLInputElement& self, JS::VM& vm) {+ if (self.type_state() != TypeAttributeState::Range)return;auto event = vm.argument(0).is_object()? Bindings::impl_from<UIEvents::MouseEvent>(&vm.argument(0).as_object())@@ -1594,47 +1594,47 @@ void HTMLInputElement::create_range_input_shadow_tree()auto client_x = event->client_x();if (!isfinite(client_x))return;- auto rect = get_bounding_client_rect().to_type<double>();+ auto rect = self.get_bounding_client_rect().to_type<double>();if (rect.width() <= 0)return;- double minimum = *min();- double maximum = *max();+ double minimum = *self.min();+ double maximum = *self.max();if (minimum > maximum)return;auto relative_x = client_x - rect.left();- MUST(set_value_as_number(mix(minimum, maximum, relative_x / rect.width())));- user_interaction_did_change_input_value();- };+ MUST(self.set_value_as_number(mix(minimum, maximum, relative_x / rect.width())));+ self.user_interaction_did_change_input_value();+ });auto mousedown_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this, update_slider_by_mouse](JS::VM& vm) {- update_slider_by_mouse(vm);+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this, update_slider_by_mouse), [](HTMLInputElement& self, auto& update_slider_by_mouse, JS::VM& vm) {+ update_slider_by_mouse->function()(vm);auto mousemove_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [update_slider_by_mouse](JS::VM& vm) {- update_slider_by_mouse(vm);+ HTML::relevant_realm(self), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(update_slider_by_mouse), [](auto& update_slider_by_mouse, JS::VM& vm) {+ update_slider_by_mouse->function()(vm);return JS::js_undefined();- },- 0, Utf16FlyString {}, &HTML::relevant_realm(*this));- auto mousemove_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mousemove_callback_function, HTML::relevant_realm(*this));+ }),+ 0, Utf16FlyString {}, &HTML::relevant_realm(self));+ auto mousemove_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mousemove_callback_function, HTML::relevant_realm(self));auto mousemove_listener = DOM::IDLEventListener::create(mousemove_callback);- auto& window = relevant_window(*this);+ auto& window = relevant_window(self);window.add_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);auto mouseup_callback_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this, mousemove_listener](JS::VM&) {- auto& window = relevant_window(*this);+ HTML::relevant_realm(self), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(self, mousemove_listener), [](HTMLInputElement& self, auto& mousemove_listener, JS::VM&) {+ auto& window = relevant_window(self);window.remove_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);return JS::js_undefined();- },- 0, Utf16FlyString {}, &HTML::relevant_realm(*this));- auto mouseup_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mouseup_callback_function, HTML::relevant_realm(*this));+ }),+ 0, Utf16FlyString {}, &HTML::relevant_realm(self));+ auto mouseup_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mouseup_callback_function, HTML::relevant_realm(self));DOM::EventTarget::AddEventListenerOptions mouseup_listener_options;mouseup_listener_options.once = true;window.add_event_listener(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(mouseup_callback), mouseup_listener_options);return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &HTML::relevant_realm(*this));auto mousedown_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mousedown_callback_function, HTML::relevant_realm(*this));add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(mousedown_callback));@@ -2069,39 +2069,39 @@ WebIDL::ExceptionOr<void> HTMLInputElement::handle_src_attribute(Utf16View valuem_resource_request = SharedResourceRequest::get_or_create(document(), *request);CSS::record_element_replaced_content_input(*this);m_resource_request->add_callbacks(- [this]() {- CSS::record_element_replaced_content_input(*this);+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ CSS::record_element_replaced_content_input(self);// 1. If the download was successful and the image is available, queue an element task on the user interaction// task source given the input element to fire an event named load at the input element.- queue_an_element_task(HTML::Task::Source::UserInteraction, [this]() {- dispatch_event(DOM::Event::create(HTML::EventNames::load,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));- });-- m_load_event_delayer.clear();- update_image_button_alt_text_shadow_tree();- set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::HTMLInputElementSrcAttribute);- },- [this]() {+ self.queue_an_element_task(HTML::Task::Source::UserInteraction, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {+ self.dispatch_event(DOM::Event::create(HTML::EventNames::load,+ HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self))));+ }));++ self.m_load_event_delayer.clear();+ self.update_image_button_alt_text_shadow_tree();+ self.set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::HTMLInputElementSrcAttribute);+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 2. Otherwise, if the fetching process fails without a response from the remote server, or completes but the// image is not a valid or supported image, then queue an element task on the user interaction task source// given the input element to fire an event named error on the input element.- queue_an_element_task(HTML::Task::Source::UserInteraction, [this]() {- dispatch_event(DOM::Event::create(HTML::EventNames::error,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));- });+ self.queue_an_element_task(HTML::Task::Source::UserInteraction, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {+ self.dispatch_event(DOM::Event::create(HTML::EventNames::error,+ HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self))));+ }));- m_load_event_delayer.clear();- CSS::record_element_replaced_content_input(*this);+ self.m_load_event_delayer.clear();+ CSS::record_element_replaced_content_input(self);// NB: The element may have been rendering as blank space while the load was pending;// now that the load failed it renders its alt text instead.- update_image_button_alt_text_shadow_tree();- set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::HTMLInputElementSrcAttribute);- },- [this]() {- m_load_event_delayer.clear();- });+ self.update_image_button_alt_text_shadow_tree();+ self.set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::HTMLInputElementSrcAttribute);+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_load_event_delayer.clear();+ }));if (m_resource_request->needs_fetching()) {m_resource_request->fetch_resource(request);diff --git a/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cpp b/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cppindex ec70acf7c11..058d2e52b16 100644--- a/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cpp+++ b/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cpp@@ -238,11 +238,11 @@ void HTMLInputElement::create_date_time_fields()auto index = m_date_time_fields.size();auto mousedown_function = JS::NativeFunction::create(- realm, [this, index](JS::VM&) {- if (index < m_date_time_fields.size())- set_active_date_time_field(index);+ realm, GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this, index), [](auto& self, auto& index, JS::VM&) {+ if (index < self.m_date_time_fields.size())+ self.set_active_date_time_field(index);return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &realm);auto mousedown_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mousedown_function, realm);element->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(mousedown_callback));diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cppindex bc73b665017..9d03d5c8315 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp@@ -207,7 +207,7 @@ void HTMLLinkElement::finished_loading_critical_style_subresources(AnyFailed anyif (!fetch_generation.has_value())return;- queue_an_element_task(Task::Source::Networking, [link = GC::Ref { *this }, fetch_generation = *fetch_generation, any_failed] {+ queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }, *fetch_generation, any_failed), [](auto& link, auto& fetch_generation, auto& any_failed) {if (fetch_generation != link->m_current_fetch_generation || !link->m_stylesheet_processing_pending)return;@@ -216,7 +216,7 @@ void HTMLLinkElement::finished_loading_critical_style_subresources(AnyFailed anyauto event_name = any_failed == AnyFailed::Yes ? HTML::EventNames::error : HTML::EventNames::load;link->dispatch_event(create_event_for_element(*link, event_name));link->finish_processing_stylesheet_resource(fetch_generation);- });+ }));}bool HTMLLinkElement::has_loaded_icon() const@@ -588,11 +588,11 @@ void HTMLLinkElement::default_fetch_and_process_linked_resource(u64 fetch_genera// 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null, failure, or a byte sequence bodyBytes:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = [this, fetch_generation](auto response, auto body_bytes) {+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, fetch_generation), [](auto& self, auto& fetch_generation, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {// "if, since the resource in question was fetched, it has become appropriate to fetch it again"- if (fetch_generation != m_current_fetch_generation)+ if (fetch_generation != self.m_current_fetch_generation)return;- m_fetch_controller = nullptr;+ self.m_fetch_controller = nullptr;// NB: The unsafe response below is always CORS-same-origin, so determine the origin-clean flag beforehand.auto origin_clean = response->is_cors_same_origin() ? CSS::StyleScope::OriginClean::Yes : CSS::StyleScope::OriginClean::No;@@ -621,14 +621,14 @@ void HTMLLinkElement::default_fetch_and_process_linked_resource(u64 fetch_genera// FIXME: 3. Otherwise, wait for the link resource's critical subresources to finish loading.// 4. Process the linked resource given el, success, response, and bodyBytes.- process_linked_resource(success, response, origin_clean, successful_body_bytes);- };+ self.process_linked_resource(success, response, origin_clean, successful_body_bytes);+ });m_fetch_controller = Fetch::Fetching::fetch(HTML::relevant_realm(*this), *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));// AD-HOC: A stopped fetch, such as one of a document that was stopped, never processes its response. Stop blocking// scripts, rendering and the load event on it then, as if the user agent had given up on loading it.- m_fetch_controller->set_stop_steps(GC::create_function(GC::Heap::the(), [weak_this = GC::Weak { *this }, fetch_generation] {+ m_fetch_controller->set_stop_steps(GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { *this }, fetch_generation), [](auto& weak_this, auto& fetch_generation) {auto link_element = weak_this.ptr();if (!link_element || fetch_generation != link_element->m_current_fetch_generation)return;@@ -693,7 +693,7 @@ void HTMLLinkElement::fetch_and_process_linked_preload_resource()// consumer of the preloaded resource.GC::Weak weak_this { *this };auto fetch_generation = m_current_fetch_generation;- preload(options, [weak_this, fetch_generation](Fetch::Infrastructure::Response& response) {+ preload(options, GC::create_function(GC::Heap::the(), GC::captures(weak_this, fetch_generation), [](auto& weak_this, auto& fetch_generation, Fetch::Infrastructure::Response& response) {// 1. If response is a network error, fire an event named error at el. Otherwise, fire an event named load at el.if (auto link_element = weak_this.ptr()) {if (fetch_generation != link_element->m_current_fetch_generation)@@ -703,7 +703,7 @@ void HTMLLinkElement::fetch_and_process_linked_preload_resource()elselink_element->dispatch_event(create_event_for_element(*link_element, HTML::EventNames::load));}- });+ }));}static bool media_attribute_matches_environment(DOM::Document const& document, Utf16View media)@@ -766,12 +766,12 @@ void HTMLLinkElement::fetch_and_process_linked_modulepreload_resource()// 3. If destination is not a module preload destination, then queue an element task on the networking task source// given el to fire an event named error at el, and return.if (!destination.has_value()) {- queue_an_element_task(Task::Source::Networking, [this, fetch_generation = m_current_fetch_generation] {+ queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(*this, m_current_fetch_generation), [](auto& self, auto& fetch_generation) {// NB: The fetch can be superseded before this task runs.- if (fetch_generation != m_current_fetch_generation)+ if (fetch_generation != self.m_current_fetch_generation)return;- dispatch_event(create_event_for_element(*this, HTML::EventNames::error));- });+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));+ }));return;}@@ -820,7 +820,7 @@ void HTMLLinkElement::fetch_and_process_linked_modulepreload_resource()// 14. Fetch a modulepreload module script graph given url, destination, settings object, and options.GC::Weak weak_this { *this };auto fetch_generation = m_current_fetch_generation;- auto on_complete = create_on_fetch_script_complete(GC::Heap::the(), [weak_this, fetch_generation](auto result) {+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(weak_this, fetch_generation), [](auto& weak_this, auto& fetch_generation, GC::Ptr<Script> result) {auto link_element = weak_this.ptr();if (!link_element || fetch_generation != link_element->m_current_fetch_generation)return;@@ -860,20 +860,20 @@ void HTMLLinkElement::fetch_and_process_linked_prefetch_resource()// 6. Let processPrefetchResponse be the following steps given a response response and null, failure, or a byte// sequence bytesOrNull:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = [this, fetch_generation = m_current_fetch_generation](auto response, auto) {- if (fetch_generation != m_current_fetch_generation)+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, m_current_fetch_generation), [](auto& self, auto& fetch_generation, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes) {+ if (fetch_generation != self.m_current_fetch_generation)return;- m_fetch_controller = nullptr;+ self.m_fetch_controller = nullptr;// 1. If response is a network error, fire an event named error at el.if (response->is_network_error()) {- dispatch_event(create_event_for_element(*this, HTML::EventNames::error));+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));}// 2. Otherwise, fire an event named load at el.else {- dispatch_event(create_event_for_element(*this, HTML::EventNames::load));+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::load));}- };+ });// 7. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse. User// agents may delay the fetching of request to prioritize other requests that are necessary for the current@@ -1018,7 +1018,7 @@ static bool type_matches_destination(Utf16View type, Optional<Fetch::Infrastruct}// https://html.spec.whatwg.org/multipage/links.html#preload-void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetch::Infrastructure::Response&)> process_response)+void HTMLLinkElement::preload(LinkProcessingOptions& options, GC::Ptr<GC::Function<void(Fetch::Infrastructure::Response&)>> process_response){auto& realm = options.environment->realm();// 1. If options's type doesn't match options's destination, then return.@@ -1066,14 +1066,14 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetcauto controller_holder = Fetch::Infrastructure::FetchControllerHolder::create();// 10. Let reportTiming given a Document document be to report timing for controller given document's relevant global object.- auto report_timing = GC::Function<void(DOM::Document const&)>::create(GC::Heap::the(), [controller_holder](DOM::Document const& document) {+ auto report_timing = GC::create_function(GC::Heap::the(), GC::captures(controller_holder), [](auto& controller_holder, DOM::Document const& document) {controller_holder->controller()->report_timing(relevant_global_object(document));});// 11. Set controller to the result of fetching request, with processResponseConsumeBody set to the following steps// given a response response and null, failure, or a byte sequence bodyBytes:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = [options = GC::Ref { options }, process_response = move(process_response), entry, report_timing](GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { options }, process_response, entry, report_timing), [](auto& options, auto& process_response, auto& entry, auto& report_timing, GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {// FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:// https://github.com/whatwg/html/issues/9355// NB: Step 1 sets the body of a clone of response, so the response fetch delivered never changes. Nothing can@@ -1105,15 +1105,15 @@ void HTMLLinkElement::preload(LinkProcessingOptions& options, Function<void(Fetc// 6. If processResponse is given, then call processResponse with response.if (process_response)- process_response(response);- };+ process_response->function()(response);+ });auto controller = Fetch::Fetching::fetch(realm, *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));controller_holder->set_controller(controller);entry->controller = controller;// 12. Let commit be the following steps given a Document document:- auto commit = GC::Function<void(DOM::Document&)>::create(GC::Heap::the(), [entry, report_timing, key = move(key)](DOM::Document& document) {+ auto commit = GC::create_function(GC::Heap::the(), GC::captures(entry, report_timing, move(key)), [](auto& entry, auto& report_timing, auto& key, DOM::Document& document) {// 1. If entry's response is not null, then call reportTiming given document.if (entry->response)report_timing->function()(document);@@ -1154,7 +1154,7 @@ void HTMLLinkElement::modulepreload(LinkProcessingOptions const& options).fetch_priority = options.fetch_priority,};- auto on_complete = create_on_fetch_script_complete(GC::Heap::the(), [](auto) { });+ auto on_complete = GC::create_function(GC::Heap::the(), [](GC::Ptr<Script>) { });fetch_modulepreload_module_script_graph(settings_object.realm(), *url, *options.destination, settings_object, script_fetch_options, on_complete);}@@ -1557,7 +1557,7 @@ void HTMLLinkElement::process_stylesheet_resource(bool success, Fetch::Infrastru// roots: the roots of a function that died would keep them alive through the collection that// finds it dead.link->queue_an_element_task(Task::Source::Networking,- [link = GC::Ref { *link }, loaded_document = GC::Ref { *loaded_document }, fetch_generation, location = move(location), base_url = move(base_url), parsed = move(parsed), origin_clean, referrer_policy] {+ GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *link }, GC::Ref { *loaded_document }, fetch_generation, move(location), move(base_url), move(parsed), origin_clean, referrer_policy), [](auto& link, auto& loaded_document, auto& fetch_generation, auto& location, auto& base_url, auto& parsed, auto& origin_clean, auto& referrer_policy) {if (fetch_generation != link->m_current_fetch_generation || !link->m_stylesheet_processing_pending)return;if (&link->document() != loaded_document.ptr() || !loaded_document->is_fully_active()@@ -1586,7 +1586,7 @@ void HTMLLinkElement::process_stylesheet_resource(bool success, Fetch::Infrastruauto event_name = sheet->loading_state() == CSS::StyleSheetState::LoadingState::Error ? HTML::EventNames::error : HTML::EventNames::load;link->dispatch_event(create_event_for_element(*link, event_name));link->finish_processing_stylesheet_resource(fetch_generation);- });+ }));});return;}@@ -1725,13 +1725,13 @@ void HTMLLinkElement::load_fallback_favicon_if_needed(GC::Ref<DOM::Document> doc// 2. Let response be the result of fetching request.Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = [document, request](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(document, request), [](auto& document, auto& request, GC::Ref<Fetch::Infrastructure::ResponseView> response) {auto& realm = document->relevant_settings_object().realm();auto global = GC::Ref { realm.global_object() };auto mime_type = Fetch::Infrastructure::extract_mime_type(response->header_list());- auto process_body = GC::create_function(GC::Heap::the(), [document, request, mime_type](ByteBuffer body) {+ auto process_body = GC::create_function(GC::Heap::the(), GC::captures(document, request, mime_type), [](auto& document, auto& request, auto& mime_type, ByteBuffer body) {// FIXME: We should use the response URL to account for redirects when determining if this is an SVG icon.decode_favicon(body, request->url(), mime_type, document)->when_resolved(GC::weak_callback(*document, [](DOM::Document& document, NonnullRefPtr<Gfx::Bitmap const>& favicon) {@@ -1750,7 +1750,7 @@ void HTMLLinkElement::load_fallback_favicon_if_needed(GC::Ref<DOM::Document> doc// 3. Use response's unsafe response as an icon as if it had been declared using the icon keyword.if (auto body = response->unsafe_response()->body())body->fully_read(realm, process_body, process_body_error, global);- };+ });Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.h b/Libraries/LibWeb/HTML/HTMLLinkElement.hindex 3dd47126440..8a193b77874 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.h+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.h@@ -191,7 +191,7 @@ private:bool stylesheet_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request&);static void preconnect(LinkProcessingOptions const&);- static void preload(LinkProcessingOptions&, Function<void(Fetch::Infrastructure::Response&)> process_response = {});+ static void preload(LinkProcessingOptions&, GC::Ptr<GC::Function<void(Fetch::Infrastructure::Response&)>> process_response = {});static void modulepreload(LinkProcessingOptions const&);void process_linked_resource(bool success, Fetch::Infrastructure::ResponseView const&, CSS::StyleScope::OriginClean, Core::ImmutableBytes const*);diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex 27e6309ec51..5a2e5bd313e 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -195,7 +195,7 @@ struct HTMLMediaElement::RemoteFetchData {URL::URL url_record;RefPtr<MediaClient::RemoteMediaStream> stream;GC::Weak<Fetch::Infrastructure::FetchController> fetch_controller;- Function<void(Utf16String)> failure_callback;+ GC::Ptr<GC::Function<void(Utf16String)>> failure_callback;bool accepts_byte_ranges { false };u64 offset { 0 };bool resource_was_complete { false };@@ -246,35 +246,35 @@ void HTMLMediaElement::initialize_element()m_document_observer = DOM::DocumentObserver::create(document());// https://html.spec.whatwg.org/multipage/media.html#playing-the-media-resource:media-element-82- m_document_observer->set_document_became_inactive([this]() {+ m_document_observer->set_document_became_inactive(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// If the media element's node document stops being a fully active document, then the playback will stop until// the document is active again.- pause_element();+ self.pause_element();// AD-HOC: Let the fetch stop while the document is inactive.// FIXME: Add a heuristic to also go idle when enough data is buffered ahead.- if (m_remote_fetch_data)- m_remote_fetch_data->stream->set_may_idle(true);+ if (self.m_remote_fetch_data)+ self.m_remote_fetch_data->stream->set_may_idle(true);- detach_video_sink_edge();- update_pending_activity();- });+ self.detach_video_sink_edge();+ self.update_pending_activity();+ }));- m_document_observer->set_document_became_active([this]() {+ m_document_observer->set_document_became_active(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// AD-HOC: Now that the document is active again, let the stream notify us when to start fetching again, unless// the download is suspended.- if (m_remote_fetch_data)- m_remote_fetch_data->stream->set_may_idle(m_remote_fetch_data->download_is_suspended);+ if (self.m_remote_fetch_data)+ self.m_remote_fetch_data->stream->set_may_idle(self.m_remote_fetch_data->download_is_suspended);- add_current_video_sink();- update_pending_activity();- });+ self.add_current_video_sink();+ self.update_pending_activity();+ }));- m_document_observer->set_document_visibility_state_observer([this](VisibilityState visibility_state) {- auto sink_predicate_may_query_layout_node = visibility_state == VisibilityState::Hidden || document().layout_is_up_to_date();+ m_document_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self, VisibilityState visibility_state) {+ auto sink_predicate_may_query_layout_node = visibility_state == VisibilityState::Hidden || self.document().layout_is_up_to_date();if (sink_predicate_may_query_layout_node)- sync_video_sink_ticking();- });+ self.sync_video_sink_ticking();+ }));document().page().register_media_element({}, unique_id());}@@ -311,15 +311,15 @@ void HTMLMediaElement::finalize()}// https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-task-void HTMLMediaElement::queue_a_media_element_task(Function<void(HTMLMediaElement&)> steps)+void HTMLMediaElement::queue_a_media_element_task(GC::Ref<GC::Function<void(HTMLMediaElement&)>> steps){// To queue a media element task with a media element element and a series of steps steps, queue an element task on the media element's// media element event task source given element and steps.- queue_an_element_task(media_element_event_task_source(), [self = GC::Ref(*this), steps = move(steps)]() mutable {- if (!self->document().is_fully_active())+ queue_an_element_task(media_element_event_task_source(), GC::create_function(GC::Heap::the(), GC::captures(*this, steps), [](auto& self, auto& steps) {+ if (!self.document().is_fully_active())return;- steps(*self);- });+ steps->function()(self);+ }));}void HTMLMediaElement::visit_edges(Cell::Visitor& visitor)@@ -336,6 +336,9 @@ void HTMLMediaElement::visit_edges(Cell::Visitor& visitor)visitor.visit(m_selected_video_track);visitor.visit(m_attached_media_source);visitor.visit(m_assigned_media_provider_object);+ visitor.visit(m_playback_manager_failure_callback);+ if (m_remote_fetch_data)+ visitor.visit(m_remote_fetch_data->failure_callback);if (m_controls.has_value())m_controls->visit_edges(visitor);if (m_screen_wake_lock.has_value())@@ -416,13 +419,13 @@ void HTMLMediaElement::removed_from(IsSubtreeRoot is_subtree_root, DOM::Node* ol// 1. Await a stable state, allowing the task that removed the media element from the Document to continue. The// synchronous section consists of all the remaining steps of this algorithm. (Steps in the synchronous section// are marked with ⌛.)- queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), [this] {+ queue_a_microtask(&document(), GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 2. ⌛ If the media element is in a document, return.- if (in_a_document_tree())+ if (self.in_a_document_tree())return;// 3. ⌛ Run the internal pause steps for the media element.- pause_element();+ self.pause_element();}));}@@ -724,9 +727,9 @@ void HTMLMediaElement::set_duration(double duration)// is not fired when the duration is reset as part of loading a new media resource.) If the duration is changed such that the current playback position// ends up being greater than the time of the end of the media resource, then the user agent must also seek to the time of the end of the media resource.if (!isnan(duration)) {- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::durationchange));- });+ }));if (current_playback_position() > duration)seek_element(duration);@@ -825,9 +828,9 @@ void HTMLMediaElement::volume_or_muted_attribute_changed()// Whenever either of the values that would be returned by the volume and muted IDL attributes change, the user// agent must queue a media element task given the media element to fire an event named volumechange at the media// element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::volumechange));- });+ }));// Then, if the media element is not allowed to play, the user agent must run the internal pause steps for the// media element.@@ -892,13 +895,13 @@ GC::Ref<TextTrack> HTMLMediaElement::add_text_track(Bindings::TextTrackKind kind// 5. Queue a media element task given the media element to fire an event named addtrack at the media element's// textTracks attribute's TextTrackList object, using TrackEvent, with the track attribute initialized to the new// text track's TextTrack object.- queue_a_media_element_task([text_track](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(text_track), [](auto& text_track, HTMLMediaElement& self) {Bindings::TrackEventInit event_init {};event_init.track = text_track;auto event = TrackEvent::create(HTML::EventNames::addtrack, move(event_init), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self)));self.m_text_tracks->dispatch_event(event);- });+ }));// 6. Return the new TextTrack object.return text_track;@@ -933,17 +936,17 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::load_element()// 6. If the media element's networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue a media element task given the media element to// fire an event named abort at the media element.if (m_network_state == NetworkState::Loading || m_network_state == NetworkState::Idle) {- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::abort));- });+ }));}// 7. If the media element's networkState is not set to NETWORK_EMPTY:if (m_network_state != NetworkState::Empty) {// 1. Queue a media element task given the media element to fire an event named emptied at the media element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::emptied));- });+ }));// 2. If a fetching process is in progress for the media element, the user agent should stop it.cancel_the_fetching_process();@@ -989,9 +992,9 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::load_element()// If this changed the official playback position, then queue a media element task given the media element to fire an// event named timeupdate at the media element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_time_update_event();- });+ }));}// 9. Set the timeline offset to Not-a-Number (NaN).@@ -1085,7 +1088,10 @@ public:// and its whole document alive. The element itself holds the selector until on_metadata_parsed(), and that's as// long as the callback can run: Once readyState is past HAVE_NOTHING, every failure takes the media data// processing steps instead (MEDIA_ERR_NETWORK or MEDIA_ERR_DECODE). Gecko/WebKit/Blink do so too.- m_media_element->load_url_resource(*url_record, GC::weak_callback(*this, [](auto& self, auto const&) { self.failed_with_elements(); }));+ m_media_element->load_url_resource(*url_record, GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { *this }), [](auto& weak_selector, Utf16String) {+ if (weak_selector)+ weak_selector->failed_with_elements();+ }));}void process_next_candidate()@@ -1100,8 +1106,8 @@ private:void failed_with_elements(){// 9. Failed with elements: Queue a media element task given the media element to fire an event named error at candidate.- m_media_element->queue_a_media_element_task([this](HTMLMediaElement&) {- m_candidate->dispatch_event(DOM::Event::create(HTML::relevant_global_object(*m_candidate), HTML::EventNames::error));+ m_media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& selector, HTMLMediaElement&) {+ selector.m_candidate->dispatch_event(DOM::Event::create(HTML::relevant_global_object(*selector.m_candidate), HTML::EventNames::error));// 10. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until// the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)@@ -1110,10 +1116,10 @@ private:// Update this if the spec is clarified in regard to this step.// 11. ⌛ Forget the media element's media-resource-specific tracks.- m_media_element->forget_media_resource_specific_tracks();+ selector.m_media_element->forget_media_resource_specific_tracks();- find_next_candidate(m_candidate);- });+ selector.find_next_candidate(selector.m_candidate);+ }));}void find_next_candidate(GC::Ref<DOM::Node> previous_candidate)@@ -1155,9 +1161,9 @@ private:// 19. ⌛ Queue a media element task given the media element to set the element's delaying-the-load-event flag// to false. This stops delaying the load event.- m_media_element->queue_a_media_element_task([this](HTMLMediaElement&) {- m_media_element->set_delaying_the_load_event(false);- });+ m_media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& selector, HTMLMediaElement&) {+ selector.m_media_element->set_delaying_the_load_event(false);+ }));// 20. End the synchronous section, continuing the remaining steps in parallel.@@ -1226,7 +1232,7 @@ void HTMLMediaElement::select_resource_for_current_load()// 4. Await a stable state, allowing the task that invoked this algorithm to continue. The synchronous section consists of all the remaining// steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// FIXME: 5. ⌛ If the media element's blocked-on-parser flag is false, then populate the list of pending text tracks.Optional<SelectMode> mode;@@ -1262,21 +1268,25 @@ void HTMLMediaElement::select_resource_for_current_load()self.set_network_state(NetworkState::Loading);// 8. ⌛ Queue a media element task given the media element to fire an event named loadstart at the media element.- self.queue_a_media_element_task([](HTMLMediaElement& self) {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::loadstart));- });+ }));// 9. Run the appropriate steps from the following list:switch (*mode) {// -> If mode is objectcase SelectMode::Object: {- auto failed_with_media_provider = GC::weak_callback(self, [](HTMLMediaElement& self, auto error_message) {+ auto failed_with_media_provider = GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { self }), [](auto& weak_self, Utf16String error_message) {+ if (!weak_self)+ return;+ auto& self = *weak_self;+// 4. Failed with media provider: Reaching this step indicates that the media resource failed to load. Take pending play promises and queue// a media element task given the media element to run the dedicated media source failure steps with the result.- self.queue_a_media_element_task([error_message = move(error_message)](HTMLMediaElement& self) mutable {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(error_message)), [](auto& error_message, HTMLMediaElement& self) {auto promises = self.take_pending_play_promises();self.handle_media_source_failure(promises, move(error_message));- });+ }));// 5. Wait for the task queued by the previous step to have executed.// AD-HOC: All calls to the failure steps immediately return, so we do not actually need to wait here.@@ -1290,9 +1300,9 @@ void HTMLMediaElement::select_resource_for_current_load()// 3. Run the resource fetch algorithm with the assigned media provider object. If that algorithm returns without aborting this one,// then the load failed.VERIFY(!self.m_assigned_media_provider_object.has<Empty>());- self.queue_a_media_element_task([failed_with_media_provider = move(failed_with_media_provider)](HTMLMediaElement& self) mutable {- self.load_local_resource(self.m_assigned_media_provider_object, move(failed_with_media_provider));- });+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(failed_with_media_provider), [](auto& failed_with_media_provider, HTMLMediaElement& self) {+ self.load_local_resource(self.m_assigned_media_provider_object, failed_with_media_provider);+ }));// 6. Return. The element won't attempt to load another resource until this algorithm is triggered again.return;@@ -1300,13 +1310,17 @@ void HTMLMediaElement::select_resource_for_current_load()// -> If mode is attributecase SelectMode::Attribute: {- auto failed_with_attribute = GC::weak_callback(self, [](HTMLMediaElement& self, auto error_message) {+ auto failed_with_attribute = GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { self }), [](auto& weak_self, Utf16String error_message) {+ if (!weak_self)+ return;+ auto& self = *weak_self;+// 6. Failed with attribute: Reaching this step indicates that the media resource failed to load or that the given URL could not be parsed. Take// pending play promises and queue a media element task given the media element to run the dedicated media source failure steps with the result.- self.queue_a_media_element_task([error_message = move(error_message)](HTMLMediaElement& self) mutable {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(error_message)), [](auto& error_message, HTMLMediaElement& self) {auto promises = self.take_pending_play_promises();self.handle_media_source_failure(promises, move(error_message));- });+ }));// 7. Wait for the task queued by the previous step to have executed.// AD-HOC: All calls to the failure steps immediately return, so we do not actually need to wait here.@@ -1315,7 +1329,7 @@ void HTMLMediaElement::select_resource_for_current_load()// 1. ⌛ If the src attribute's value is the empty string, then end the synchronous section, and jump down to the failed with attribute step below.auto source = self.attribute(HTML::AttributeNames::src).value_or({});if (source.is_empty()) {- failed_with_attribute("The 'src' attribute is empty"_utf16);+ failed_with_attribute->function()("The 'src' attribute is empty"_utf16);return;}@@ -1331,12 +1345,12 @@ void HTMLMediaElement::select_resource_for_current_load()// 5. If urlRecord was obtained successfully, run the resource fetch algorithm with urlRecord. If that algorithm returns without aborting this one,// then the load failed.- self.queue_a_media_element_task([url_record = move(url_record), failed_with_attribute = move(failed_with_attribute)](HTMLMediaElement& self) mutable {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(url_record), failed_with_attribute), [](auto& url_record, auto& failed_with_attribute, HTMLMediaElement& self) {if (url_record.has_value()) {- self.load_url_resource(*url_record, move(failed_with_attribute));+ self.load_url_resource(*url_record, failed_with_attribute);return;}- });+ }));// 8. Return. The element won't attempt to load another resource until this algorithm is triggered again.return;@@ -1371,11 +1385,11 @@ void HTMLMediaElement::select_resource_for_current_load()break;}- });+ }));}// https://html.spec.whatwg.org/multipage/media.html#concept-media-load-resource-void HTMLMediaElement::load_url_resource(URL::URL const& url_record, Function<void(Utf16String)> failure_callback)+void HTMLMediaElement::load_url_resource(URL::URL const& url_record, GC::Ref<GC::Function<void(Utf16String)>> failure_callback){// 1. Let mode be remote.// 2. If the algorithm was invoked with media provider object, then set mode to local.@@ -1424,10 +1438,10 @@ void HTMLMediaElement::load_url_resource(URL::URL const& url_record, Function<vo// NB: A MediaSource is only usable from the process that created it.auto blob_entry = FileAPI::local_blob_url_entry(url_record);if (!blob_entry.has_value()) {- failure_callback(u"Media provider object was created by another process"_utf16);+ failure_callback->function()(u"Media provider object was created by another process"_utf16);return;}- load_local_resource(blob_entry->object.get<GC::Ref<MediaSourceExtensions::MediaSource>>(), move(failure_callback));+ load_local_resource(blob_entry->object.get<GC::Ref<MediaSourceExtensions::MediaSource>>(), failure_callback);return;}}@@ -1442,7 +1456,7 @@ void HTMLMediaElement::load_url_resource(URL::URL const& url_record, Function<vom_remote_fetch_data->stream->set_data_request_callback(GC::weak_callback(*this, [](auto& self, Optional<u64> offset) {self.handle_data_request(offset);}));- m_remote_fetch_data->failure_callback = move(failure_callback);+ m_remote_fetch_data->failure_callback = failure_callback;// AD-HOC: If the poster is cleared, that means we've started playing or seeked, so continue the download.m_remote_fetch_data->may_suspend_after_first_frame = m_show_poster;@@ -1513,12 +1527,12 @@ void HTMLMediaElement::update_download_suspension()// When a media element's download has been suspended, the user agent must queue a media element task given the// media element to set the networkState to NETWORK_IDLE and fire an event named suspend at the element.- queue_a_media_element_task([fetch_data_id = m_remote_fetch_data->id](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(m_remote_fetch_data->id), [](auto& fetch_data_id, HTMLMediaElement& self) {if (!self.m_remote_fetch_data || self.m_remote_fetch_data->id != fetch_data_id || !self.m_remote_fetch_data->download_is_suspended)return;self.set_network_state(NetworkState::Idle);self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::suspend));- });+ }));// NB: The spec also stops delaying the load event when a download is suspended, but we only suspend at// HAVE_CURRENT_DATA, and reaching that state already stopped delaying it.@@ -1572,23 +1586,23 @@ void HTMLMediaElement::wait_for_an_implementation_defined_event_before_fetching_set_network_state(NetworkState::Idle);// 2. Queue a media element task given the media element to fire an event named suspend at the element.- queue_a_media_element_task([fetch_generation](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(fetch_generation), [](auto& fetch_generation, HTMLMediaElement& self) {if (fetch_generation != self.m_current_fetch_generation|| !self.m_waiting_for_an_implementation_defined_event_to_fetch_the_resource) {return;}self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::suspend));- });+ }));// 3. Queue a media element task given the media element to set the element's delaying-the-load-event flag to false. This stops delaying// the load event.- queue_a_media_element_task([fetch_generation](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(fetch_generation), [](auto& fetch_generation, HTMLMediaElement& self) {if (fetch_generation != self.m_current_fetch_generation|| !self.m_waiting_for_an_implementation_defined_event_to_fetch_the_resource) {return;}self.set_delaying_the_load_event(false);- });+ }));// 4. Wait for the task to be run.// 5. Wait for an implementation-defined event (e.g., the user requesting that the media element begin playback).@@ -1695,7 +1709,7 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_range// 8. Fetch request, with processResponse set to the following steps given response response:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = [weak_self = GC::Weak(*this), byte_range = move(byte_range), fetch_generation](auto response) mutable {+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(GC::Weak(*this), move(byte_range), fetch_generation), [](auto& weak_self, auto& byte_range, auto& fetch_generation, GC::Ref<Fetch::Infrastructure::ResponseView> response) {if (!weak_self)return;GC::Ref self = *weak_self;@@ -1725,7 +1739,7 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_range// fetch the resourceif (self->m_ready_state == ReadyState::HaveNothing) {fetch_data->stream->close();- fetch_data->failure_callback(maybe_verify_response_failure.release_value());+ fetch_data->failure_callback->function()(maybe_verify_response_failure.release_value());return;}@@ -1740,7 +1754,7 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_range// 2. Let updateMedia be to queue a media element task given the media element to run the first appropriate steps from the media data processing// steps list below. (A new task is used for this so that the work described below occurs relative to the appropriate media element event task// source rather than using the networking task source.)- auto update_media = GC::create_function(self->heap(), [weak_self = GC::Weak(self), fetch_generation, response_is_cors_cross_origin](ByteBuffer media_data) mutable {+ auto update_media = GC::create_function(self->heap(), GC::captures(GC::Weak(self), fetch_generation, response_is_cors_cross_origin), [](auto& weak_self, auto& fetch_generation, auto& response_is_cors_cross_origin, ByteBuffer media_data) {if (!weak_self)return;if (fetch_generation != weak_self->m_current_fetch_generation)@@ -1755,16 +1769,16 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_rangefetch_data->stream->add_chunk_at(fetch_data->offset, media_data.bytes());fetch_data->offset += media_data.size();- weak_self->queue_a_media_element_task([](HTMLMediaElement& self) {+ weak_self->queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.process_media_data(FetchingStatus::Ongoing);- });+ }));});// 3. Let processEndOfMedia be the following step: If the fetching process has completes without errors, including decoding the media data,// and if all of the data is available to the user agent without network access, then, the user agent must move on to the final step below.// This might never happen, e.g. when streaming an infinite resource such as web radio, or if the resource is longer than the user agent's// ability to cache data.- auto process_end_of_media = GC::create_function(self->heap(), [weak_self = GC::Weak(self), fetch_generation] {+ auto process_end_of_media = GC::create_function(self->heap(), GC::captures(GC::Weak(self), fetch_generation), [](auto& weak_self, auto& fetch_generation) {if (!weak_self)return;if (fetch_generation != weak_self->m_current_fetch_generation)@@ -1777,7 +1791,7 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_range// 5. Otherwise, incrementally read response's body given updateMedia, processEndOfMedia, an empty algorithm, and global.// AD-HOC: We need to pass a non-empty error algorithm in order to invoke the requisite steps.- auto process_body_error = GC::create_function(self->heap(), [weak_self = GC::Weak(self), fetch_generation](JS::Value) {+ auto process_body_error = GC::create_function(self->heap(), GC::captures(GC::Weak(self), fetch_generation), [](auto& weak_self, auto& fetch_generation, JS::Value) {if (!weak_self)return;if (fetch_generation != weak_self->m_current_fetch_generation)@@ -1794,13 +1808,13 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_range}response->body()->incrementally_read(HTML::relevant_realm(*self), update_media, process_end_of_media, process_body_error, GC::Ref { global });- };+ });m_remote_fetch_data->fetch_controller = Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}// https://html.spec.whatwg.org/multipage/media.html#concept-media-load-resource-void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider, Function<void(Utf16String)> failure_callback)+void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider, GC::Ref<GC::Function<void(Utf16String)>> failure_callback){// 1. Let mode be remote.// 2. If the algorithm was invoked with media provider object, then set mode to local.@@ -1846,7 +1860,7 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,// Run the "If the media data cannot be fetched at all, due to network errors, causing the user agent to// give up trying to fetch the resource" steps of the resource fetch algorithm's media data processing// steps list.- failure_callback("MediaSource is not closed"_utf16);+ failure_callback->function()("MediaSource is not closed"_utf16);}// -> Otherwiseelse {@@ -1877,7 +1891,7 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,media_source->set_assigned_to_media_element({}, *this);m_attached_media_source = media_source;update_pending_activity();- set_up_playback_manager_for_local(move(failure_callback));+ set_up_playback_manager_for_local(failure_callback);// 4. Set the readyState attribute to "open".// 5. Queue a task to fire an event named sourceopen at the MediaSource.@@ -1915,7 +1929,7 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,},[&](GC::Ref<FileAPI::Blob>) {// FIXME: Support File objects.- failure_callback("File objects are not supported"_utf16);+ failure_callback->function()("File objects are not supported"_utf16);},[](Empty) { });@@ -2229,9 +2243,9 @@ void HTMLMediaElement::upon_current_playback_position_possibly_changed()// https://w3c.github.io/media-source/#buffer-monitoring// This is queued as a task to ensure that any tasks queued to fire events based on prior ready state// changes occur before it is changed again.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.update_ready_state();- });+ }));}void HTMLMediaElement::start_or_stop_playback_position_update_timer()@@ -2430,14 +2444,18 @@ void HTMLMediaElement::set_up_playback_manager_for_remote()// https://html.spec.whatwg.org/multipage/media.html#media-elements// Therefore, we enumerate all the available tracks into our VideoTrackList and AudioTrackList.- set_up_playback_manager_error_handler(GC::weak_callback(*this, [](auto& self, Utf16String error_message) {+ set_up_playback_manager_error_handler(GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { *this }), [](auto& weak_self, Utf16String error_message) {+ if (!weak_self)+ return;+ auto& self = *weak_self;+// 1. The user agent should cancel the fetching process.VERIFY(self.m_remote_fetch_data);- auto failure_callback = move(self.m_remote_fetch_data->failure_callback);+ auto failure_callback = exchange(self.m_remote_fetch_data->failure_callback, nullptr);self.cancel_the_fetching_process();// 2. Abort this subalgorithm, returning to the resource selection algorithm.- failure_callback(move(error_message));+ failure_callback->function()(move(error_message));}));m_playback_manager->add_media_source(*m_remote_fetch_data->stream)@@ -2460,9 +2478,9 @@ void HTMLMediaElement::set_up_playback_manager_for_remote()self.on_metadata_parsed(SourceType::Remote);// NB: The initial source state may already contain a complete scan, with no later change.- self.queue_a_media_element_task([](HTMLMediaElement& self) {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.maybe_complete_remote_fetch();- });+ }));})).when_rejected(GC::weak_callback(*this, [](auto& self, Media::DecoderError& error) {self.handle_playback_manager_error(move(error));@@ -2473,17 +2491,17 @@ void HTMLMediaElement::set_up_playback_manager_for_remote()});m_playback_manager->on_buffered_ranges_change = GC::weak_callback(*this, [](auto& self) {- self.queue_a_media_element_task([](HTMLMediaElement& self) {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.maybe_complete_remote_fetch();self.update_ready_state();- });+ }));});}// https://html.spec.whatwg.org/multipage/media.html#media-data-processing-steps-list-void HTMLMediaElement::set_up_playback_manager_error_handler(Function<void(Utf16String)> failure_callback)+void HTMLMediaElement::set_up_playback_manager_error_handler(GC::Ref<GC::Function<void(Utf16String)>> failure_callback){- m_playback_manager_failure_callback = move(failure_callback);+ m_playback_manager_failure_callback = failure_callback;m_playback_manager->on_error = GC::weak_callback(*this, [](auto& self, Media::DecoderError&& error) {self.handle_playback_manager_error(move(error));});@@ -2492,14 +2510,14 @@ void HTMLMediaElement::set_up_playback_manager_error_handler(Function<void(Utf16// https://html.spec.whatwg.org/multipage/media.html#media-data-processing-steps-listvoid HTMLMediaElement::handle_playback_manager_error(Media::DecoderError&& error){- auto const* playback_manager_ptr = m_playback_manager.ptr();+ auto weak_playback_manager = m_playback_manager ? m_playback_manager->make_weak_ptr() : WeakPtr<MediaClient::RemotePlaybackManager> {};// NB: Queue a task for this so that we don't destroy the PlaybackManager within one of its callbacks when we// call forget_media_resource_specific_tracks().- queue_a_media_element_task([error = move(error), playback_manager_ptr](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(Utf16String::from_utf8(error.description()), move(weak_playback_manager)), [](auto& error_description, auto& weak_playback_manager, HTMLMediaElement& self) {if (self.m_error)return;- if (playback_manager_ptr != self.m_playback_manager.ptr())+ if (!weak_playback_manager || weak_playback_manager.ptr() != self.m_playback_manager.ptr())return;// NB: Failures to add a media source and failures during playback are both handled here, so the ready state@@ -2508,19 +2526,19 @@ void HTMLMediaElement::handle_playback_manager_error(Media::DecoderError&& error// -> If the media data is corruptedif (self.m_ready_state != ReadyState::HaveNothing) {- self.set_decoder_error(Utf16String::from_utf8(error.description()));+ self.set_decoder_error(move(error_description));return;}// -> If the media data can be fetched but is found by inspection to be in an unsupported format, or can otherwise not be rendered at allVERIFY(self.m_playback_manager_failure_callback);- auto failure_callback = move(self.m_playback_manager_failure_callback);- failure_callback(Utf16String::from_utf8(error.description()));- });+ auto failure_callback = exchange(self.m_playback_manager_failure_callback, nullptr);+ failure_callback->function()(move(error_description));+ }));}// https://html.spec.whatwg.org/multipage/media.html#media-data-processing-steps-list-void HTMLMediaElement::set_up_playback_manager_for_local(Function<void(Utf16String)> failure_callback)+void HTMLMediaElement::set_up_playback_manager_for_local(GC::Ref<GC::Function<void(Utf16String)>> failure_callback){m_playback_manager = document().page().client().create_media_playback_manager();@@ -2532,12 +2550,16 @@ void HTMLMediaElement::set_up_playback_manager_for_local(Function<void(Utf16Stri// NB: The Media Source Extensions spec creates the tracks in its initialization segment received algorithm, and// SourceBuffer runs the steps once enough of the media data has been fetched to determine its metadata.- set_up_playback_manager_error_handler(GC::weak_callback(*this, [failure_callback = move(failure_callback)](auto& self, Utf16String error_message) {+ set_up_playback_manager_error_handler(GC::create_function(GC::Heap::the(), GC::captures(GC::Weak { *this }, failure_callback), [](auto& weak_self, auto& failure_callback, Utf16String error_message) {+ if (!weak_self)+ return;+ auto& self = *weak_self;+// 1. The user agent should cancel the fetching process.self.cancel_the_fetching_process();// 2. Abort this subalgorithm, returning to the resource selection algorithm.- failure_callback(move(error_message));+ failure_callback->function()(move(error_message));}));m_playback_manager->on_playback_state_change = GC::weak_callback(*this, [](auto& self) {@@ -2545,10 +2567,10 @@ void HTMLMediaElement::set_up_playback_manager_for_local(Function<void(Utf16Stri});m_playback_manager->on_buffered_ranges_change = GC::weak_callback(*this, [](auto& self) {- self.queue_a_media_element_task([](HTMLMediaElement& self) {+ self.queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.process_media_data(FetchingStatus::Ongoing);self.update_ready_state();- });+ }));});}@@ -2561,11 +2583,11 @@ void HTMLMediaElement::queue_interrupted_fetch_steps()}m_remote_fetch_data->fetching_was_interrupted = true;- queue_a_media_element_task([fetch_data_id = m_remote_fetch_data->id](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(m_remote_fetch_data->id), [](auto& fetch_data_id, HTMLMediaElement& self) {if (!self.m_remote_fetch_data || self.m_remote_fetch_data->id != fetch_data_id || self.m_error)return;self.process_media_data(FetchingStatus::Interrupted);- });+ }));}void HTMLMediaElement::maybe_complete_remote_fetch()@@ -2604,7 +2626,7 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)} else if (fetching_status == FetchingStatus::Ongoing) {// If the user agent ever discards any media data and then needs to resume the network activity to obtain it// again, then it must queue a media element task given the media element to set the networkState to NETWORK_LOADING.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// NB: Once an error has been set in the meantime, the network state stays where that error left it.if (self.m_error)return;@@ -2613,7 +2635,7 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)if (self.m_remote_fetch_data && self.m_remote_fetch_data->download_is_suspended)return;self.set_network_state(NetworkState::Loading);- });+ }));// While the load is not suspended (see below), every 350ms (±200ms) or for every byte received, whichever is// least frequent, queue a media element task given the media element to:@@ -2621,11 +2643,11 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)if (!m_last_progress_event_time.has_value() || now - m_last_progress_event_time.value() > AK::Duration::from_milliseconds(350)) {if (!m_remote_fetch_data || !m_remote_fetch_data->download_is_suspended) {m_last_progress_event_time = now;- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// FIXME: 1. Set the element's is currently stalled to false.// 2. Fire an event named progress at the element.self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::progress));- });+ }));}update_ready_state();@@ -2788,9 +2810,9 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)// -> If the previous ready state was HAVE_NOTHING, and the new ready state is HAVE_METADATAif (old_ready_state == ReadyState::HaveNothing && ready_state == ReadyState::HaveMetadata) {// Queue a media element task given the media element to fire an event named loadedmetadata at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::loadedmetadata));- });+ }));return;}@@ -2802,9 +2824,9 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)if (!m_has_fired_loadeddata) {m_has_fired_loadeddata = true;- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::loadeddata));- });+ }));}// https://html.spec.whatwg.org/multipage/media.html#loading-the-media-resource:dom-media-readystate-4@@ -2832,13 +2854,13 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)) {// the user agent must queue a media element task given the media element to fire an event named timeupdate// at the element, and- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_time_update_event();- });+ }));// queue a media element task given the media element to fire an event named waiting at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::waiting));- });+ }));}return;}@@ -2846,9 +2868,9 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)// -> If the previous ready state was HAVE_CURRENT_DATA or less, and the new ready state is HAVE_FUTURE_DATAif (old_ready_state <= ReadyState::HaveCurrentData && ready_state == ReadyState::HaveFutureData) {// The user agent must queue a media element task given the media element to fire an event named canplay at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::canplay));- });+ }));// If the element's paused attribute is false, the user agent must notify about playing for the element.if (!paused())@@ -2862,18 +2884,18 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)// If the previous ready state was HAVE_CURRENT_DATA or less, the user agent must queue a media element task given the media element to fire an event// named canplay at the element, and, if the element's paused attribute is false, notify about playing for the element.if (old_ready_state <= ReadyState::HaveCurrentData) {- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::canplay));- });+ }));if (!paused())notify_about_playing();}// The user agent must queue a media element task given the media element to fire an event named canplaythrough at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::canplaythrough));- });+ }));// If the element is not eligible for autoplay, then the user agent must abort these substeps.if (!is_eligible_for_autoplay())@@ -2894,9 +2916,9 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)}// Queue a media element task given the element to fire an event named play at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::play));- });+ }));// Notify about playing for the element.notify_about_playing();@@ -3052,10 +3074,10 @@ void HTMLMediaElement::on_playback_manager_state_change(){// NB: Queue the readyState update as a task so that it will never run before the durationchange and loadedmetadata// events are fired. This ensures that readyState has a deterministic value in those events.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {if (self.m_ready_state >= ReadyState::HaveMetadata)self.update_ready_state();- });+ }));VERIFY(m_playback_manager);auto state = m_playback_manager->state();@@ -3109,16 +3131,16 @@ void HTMLMediaElement::play_element()}// 3. Queue a media element task given the media element to fire an event named play at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::play));- });+ }));// 4. If the media element's readyState attribute has the value HAVE_NOTHING, HAVE_METADATA, or HAVE_CURRENT_DATA,// queue a media element task given the media element to fire an event named waiting at the element.if (m_ready_state == ReadyState::HaveNothing || m_ready_state == ReadyState::HaveMetadata || m_ready_state == ReadyState::HaveCurrentData) {- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::waiting));- });+ }));}// Otherwise, the media element's readyState attribute has the value HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA:// notify about playing for the element.@@ -3133,9 +3155,9 @@ void HTMLMediaElement::play_element()else if (m_ready_state == ReadyState::HaveFutureData || m_ready_state == ReadyState::HaveEnoughData) {auto promises = take_pending_play_promises();- queue_a_media_element_task([promises = move(promises)](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(promises)), [](auto& promises, HTMLMediaElement& self) {self.resolve_pending_play_promises(promises);- });+ }));}// 5. Set the media element's can autoplay flag to false.@@ -3157,7 +3179,7 @@ void HTMLMediaElement::pause_element()auto promises = take_pending_play_promises();// 3. Queue a media element task given the media element and the following steps:- queue_a_media_element_task([promises = move(promises)](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(promises)), [](auto& promises, HTMLMediaElement& self) {// 1. Fire an event named timeupdate at the element.self.dispatch_time_update_event();@@ -3166,7 +3188,7 @@ void HTMLMediaElement::pause_element()// 3. Reject pending play promises with promises and an "AbortError" DOMException.self.reject_pending_play_promises<WebIDL::AbortError>(promises, "Media playback was paused"_utf16);- });+ }));// 4. Set the official playback position to the current playback position.set_official_playback_position(current_playback_position());@@ -3267,9 +3289,9 @@ void HTMLMediaElement::seek_element(double playback_position, MediaSeekMode seek}// 10. Queue a media element task given the media element to fire an event named seeking at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::seeking));- });+ }));// 11. Set the current playback position to the new playback position.if (m_playback_manager) {@@ -3298,9 +3320,9 @@ void HTMLMediaElement::seek_element(double playback_position, MediaSeekMode seek// Awaiting a stable state seems to require a task to be queued anyway, and we use media element tasks to cancel// ongoing operations when load_element() is called.// See: https://github.com/whatwg/html/issues/2882#issuecomment-1108531815- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.finish_seeking_element();- });+ }));}}@@ -3318,14 +3340,14 @@ void HTMLMediaElement::finish_seeking_element()time_marches_on(TimeMarchesOnReason::Other);// 16. ⌛ Queue a media element task given the media element to fire an event named timeupdate at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_time_update_event();- });+ }));// 17. ⌛ Queue a media element task given the media element to fire an event named seeked at the element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::seeked));- });+ }));}// https://html.spec.whatwg.org/multipage/media.html#notify-about-playing@@ -3338,7 +3360,7 @@ void HTMLMediaElement::notify_about_playing()// AD-HOC: The playback clock starts running below, before this task runs, so scripts observing the start of// playback would read a position sampled at an arbitrary later time. Give them the position that// playback begins from instead.- queue_a_media_element_task([promises = move(promises), starting_position = current_playback_position()](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(promises), current_playback_position()), [](auto& promises, auto& starting_position, HTMLMediaElement& self) {self.set_official_playback_position(starting_position);// 1. Fire an event named playing at the element.@@ -3346,7 +3368,7 @@ void HTMLMediaElement::notify_about_playing()// 2. Resolve pending play promises with promises.self.resolve_pending_play_promises(promises);- });+ }));if (m_playback_manager)m_playback_manager->play();@@ -3426,9 +3448,9 @@ void HTMLMediaElement::set_default_playback_rate(double new_value)// When the defaultPlaybackRate or playbackRate attributes change value (either by being set by script or by being changed directly by the user agent, e.g. in response to user// control), the user agent must queue a media element task given the media element to fire an event named ratechange at the media element.if (m_default_playback_rate != new_value) {- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::ratechange));- });+ }));}// on setting the attribute must be set to the new value.@@ -3447,9 +3469,9 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::set_playback_rate(double new_value)// When the defaultPlaybackRate or playbackRate attributes change value (either by being set by script or by being changed directly by the user agent, e.g. in response to user// control), the user agent must queue a media element task given the media element to fire an event named ratechange at the media element.if (m_playback_rate != new_value) {- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::ratechange));- });+ }));}// 2. Set playbackRate to the new value, and if the element is potentially playing, change the playback speed.@@ -3654,10 +3676,10 @@ bool HTMLMediaElement::has_ended_playback(IgnoreLoopAttribute ignore_loop_attribvoid HTMLMediaElement::upon_has_ended_playback_possibly_changed(){- run_when_event_loop_reaches_step_1(GC::Function<void()>::create(GC::Heap::the(), [&] {+ run_when_event_loop_reaches_step_1(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// The ended attribute must return true if, the last time the event loop reached step 1, the media element had ended// playback and the direction of playback was forwards, and false otherwise.- update_ended_attribute();+ self.update_ended_attribute();}));}@@ -3697,12 +3719,12 @@ void HTMLMediaElement::reached_end_of_media_playback()// AD-HOC: Queue each step in its own task, so that loading a new resource in the timeupdate or pause handlers// removes the remaining tasks instead of firing ended at the new resource.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// 1. Fire an event named timeupdate at the media element.self.dispatch_time_update_event();- });+ }));- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// 2. If the media element has ended playback, the direction of playback is forwards, and paused is false, then:if (self.has_ended_playback(IgnoreLoopAttribute::No) && self.direction_of_playback() == PlaybackDirection::Forwards && !self.paused()) {// 1. Set the paused attribute to true.@@ -3718,12 +3740,12 @@ void HTMLMediaElement::reached_end_of_media_playback()// 3. Take pending play promises and reject pending play promises with the result and an "AbortError" DOMException.self.reject_pending_play_promises<WebIDL::AbortError>(promises, "Media playback has ended"_utf16);}- });+ }));- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// 3. Fire an event named ended at the media element.self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::ended));- });+ }));}void HTMLMediaElement::dispatch_time_update_event()@@ -3804,9 +3826,9 @@ void HTMLMediaElement::time_marches_on(TimeMarchesOnReason reason)if (dispatch_event) {m_last_time_update_event_time = now;- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_time_update_event();- });+ }));}}@@ -3916,9 +3938,9 @@ void HTMLMediaElement::time_marches_on(TimeMarchesOnReason reason)// 14. Queue a media element task given the media element for each task in events, in list order.for (auto& event : events) {- queue_a_media_element_task([name = move(event.name), target = event.target](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(move(event.name), event.target), [](auto& name, auto& target, HTMLMediaElement& self) {target->dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), name));- });+ }));}// 15. Sort affected tracks in the same order as the text tracks appear in the media element's list of text tracks, and@@ -3931,11 +3953,11 @@ void HTMLMediaElement::time_marches_on(TimeMarchesOnReason reason)// fire an event named cuechange at the TextTrack object, and, if the text track has a corresponding track element,// to then fire an event named cuechange at the track element as well.for (auto const& text_track : affected_tracks) {- queue_a_media_element_task([text_track](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(text_track), [](auto& text_track, HTMLMediaElement& self) {text_track->dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::cuechange));if (auto track_element = text_track->track_element())track_element->dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::cuechange));- });+ }));}// 17. Set the text track cue active flag of all the cues in the current cues, and unset the text track cue active flag@@ -3993,13 +4015,13 @@ void HTMLMediaElement::text_track_mode_changed()m_pending_text_track_change_notification_flag = true;// 3. Queue a media element task given the media element to run these steps:- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {// 1. Unset the media element's pending text track change notification flag.self.m_pending_text_track_change_notification_flag = false;// 2. Fire an event named change at the media element's textTracks attribute's TextTrackList object.self.m_text_tracks->dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::change));- });+ }));// 4. If the media element's show poster flag is not set, run the time marches on steps.if (!m_show_poster)diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.hindex b516901b22a..784609c7991 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h@@ -17,6 +17,7 @@#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibCompositing/Video/VideoFrameHold.h>#include <LibCore/Forward.h>+#include <LibGC/Function.h>#include <LibGC/RootVector.h>#include <LibGfx/Rect.h>#include <LibJS/Forward.h>@@ -73,8 +74,7 @@ public:return meets_focusable_area_rendering_requirements();}- // NOTE: The function is wrapped in a GC::HeapFunction immediately.- void queue_a_media_element_task(Function<void(HTMLMediaElement&)>);+ void queue_a_media_element_task(GC::Ref<GC::Function<void(HTMLMediaElement&)>>);Task::Source media_element_event_task_source() const { return m_media_element_event_task_source.source; }void cancel_the_fetching_process();@@ -260,9 +260,9 @@ private:void select_resource_for_current_load();void promote_current_resource_selection_to_explicit();- void load_url_resource(URL::URL const&, ESCAPING Function<void(Utf16String)> failure_callback);+ void load_url_resource(URL::URL const&, GC::Ref<GC::Function<void(Utf16String)>> failure_callback);void load_remote_resource(ByteRange const&);- void load_local_resource(MediaProvider const&, ESCAPING Function<void(Utf16String)> failure_callback);+ void load_local_resource(MediaProvider const&, GC::Ref<GC::Function<void(Utf16String)>> failure_callback);bool preload_attribute_is_in_none_state() const;bool preload_attribute_is_in_automatic_state() const;bool should_suspend_the_download() const;@@ -284,8 +284,8 @@ private:void handle_data_request(Optional<u64> offset);void set_up_playback_manager_for_remote();- void set_up_playback_manager_for_local(Function<void(Utf16String)> failure_callback);- void set_up_playback_manager_error_handler(Function<void(Utf16String)> failure_callback);+ void set_up_playback_manager_for_local(GC::Ref<GC::Function<void(Utf16String)>> failure_callback);+ void set_up_playback_manager_error_handler(GC::Ref<GC::Function<void(Utf16String)>> failure_callback);void handle_playback_manager_error(Media::DecoderError&&);enum class FetchingStatus : u8 {Ongoing,@@ -490,7 +490,7 @@ private:OwnPtr<MediaClient::RemotePlaybackManager> m_playback_manager;OwnPtr<MediaStreamPlayback> m_media_stream_playback;- Function<void(Utf16String)> m_playback_manager_failure_callback;+ GC::Ptr<GC::Function<void(Utf16String)>> m_playback_manager_failure_callback;RefPtr<Core::Timer> m_playback_position_update_timer;GC::Ptr<VideoTrack> m_selected_video_track;@@ -509,6 +509,10 @@ private:}+GC_UNTRACED_CAPTURE(Web::HTML::HTMLMediaElement::EntireResource);++GC_UNTRACED_CAPTURE(Web::HTML::HTMLMediaElement::UntilEnd);+namespace Web::DOM {template<>diff --git a/Libraries/LibWeb/HTML/HTMLObjectElement.cpp b/Libraries/LibWeb/HTML/HTMLObjectElement.cppindex c0654262fc3..3e6814a6665 100644--- a/Libraries/LibWeb/HTML/HTMLObjectElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLObjectElement.cpp@@ -75,12 +75,12 @@ void HTMLObjectElement::initialize_element()// - the element's node document changes whether it is fully active,// ...the user agent must queue an element task on the DOM manipulation task source given the object element to run// the following steps to (re)determine what the object element represents.- m_document_observer->set_document_became_active([this]() {- queue_element_task_to_run_object_representation_steps();- });- m_document_observer->set_document_became_inactive([this]() {- queue_element_task_to_run_object_representation_steps();- });+ m_document_observer->set_document_became_active(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.queue_element_task_to_run_object_representation_steps();+ }));+ m_document_observer->set_document_became_inactive(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.queue_element_task_to_run_object_representation_steps();+ }));}void HTMLObjectElement::visit_edges(Cell::Visitor& visitor)@@ -227,14 +227,14 @@ void HTMLObjectElement::queue_element_task_to_run_object_representation_steps()// This task being queued or actively running must delay the load event of the element's node document.m_document_load_event_delayer_for_object_representation_task.empend(document());- auto release_load_event_delay = GC::create_function(GC::Heap::the(), [this] {- m_document_load_event_delayer_for_object_representation_task.take_last();+ auto release_load_event_delay = GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_document_load_event_delayer_for_object_representation_task.take_last();});- auto steps = [this, release_load_event_delay]() {+ auto steps = GC::create_function(GC::Heap::the(), GC::captures(*this, release_load_event_delay), [](auto& self, auto& release_load_event_delay) {ScopeGuard guard { [&] { release_load_event_delay->function()(); } };- auto& realm = HTML::relevant_realm(*this);+ auto& realm = HTML::relevant_realm(self);// FIXME: 1. If the user has indicated a preference that this object element's fallback content be shown instead of the// element's usual behavior, then jump to the step below labeled fallback.@@ -245,27 +245,27 @@ void HTMLObjectElement::queue_element_task_to_run_object_representation_steps()// fallback.// FIXME: Handle the element being in the stack of open elements.// FIXME: Handle the element not being rendered.- if (!document().browsing_context() || !document().is_fully_active()) {- run_object_representation_fallback_steps();+ if (!self.document().browsing_context() || !self.document().is_fully_active()) {+ self.run_object_representation_fallback_steps();return;}- if (has_ancestor_media_element_or_object_element_not_showing_fallback_content()) {- run_object_representation_fallback_steps();+ if (self.has_ancestor_media_element_or_object_element_not_showing_fallback_content()) {+ self.run_object_representation_fallback_steps();return;}// 3. If the data attribute is present and its value is not the empty string, then:- if (auto data = get_attribute(HTML::AttributeNames::data); data.has_value() && !data->is_empty()) {+ if (auto data = self.get_attribute(HTML::AttributeNames::data); data.has_value() && !data->is_empty()) {// 1. If the type attribute is present and its value is not a type that the user agent supports, then the user// agent may jump to the step below labeled fallback without fetching the content to examine its real type.// 2. Let url be the result of encoding-parsing a URL given the data attribute's value, relative to the element's node document.- auto url = document().encoding_parse_url(*data);+ auto url = self.document().encoding_parse_url(*data);// 3. If url is failure, then fire an event named error at the element and jump to the step below labeled fallback.if (!url.has_value()) {- dispatch_event(create_event_for_element(*this, HTML::EventNames::error));- run_object_representation_fallback_steps();+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::error));+ self.run_object_representation_fallback_steps();return;}@@ -274,7 +274,7 @@ void HTMLObjectElement::queue_element_task_to_run_object_representation_steps()// "object", and whose use-URL-credentials flag is set.auto request = Fetch::Infrastructure::Request::create();request->set_url(url.release_value());- request->set_client(document().relevant_settings_object().address());+ request->set_client(self.document().relevant_settings_object().address());request->set_destination(Fetch::Infrastructure::Request::Destination::Object);request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);@@ -282,12 +282,12 @@ void HTMLObjectElement::queue_element_task_to_run_object_representation_steps()request->set_use_url_credentials(true);Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = [this](GC::Ref<Fetch::Infrastructure::ResponseView> response) {- auto& realm = HTML::relevant_realm(*this);- auto& global = document().relevant_settings_object().realm().global_object();+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self, GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ auto& realm = HTML::relevant_realm(self);+ auto& global = self.document().relevant_settings_object().realm().global_object();if (response->is_network_error()) {- resource_did_fail();+ self.resource_did_fail();return;}@@ -300,30 +300,30 @@ void HTMLObjectElement::queue_element_task_to_run_object_representation_steps()auto ignore_body_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });(void)body->incrementally_read(realm, ignore_chunk, ignore_end_of_body, ignore_body_error, GC::Ref { global });}- resource_did_fail();+ self.resource_did_fail();return;}if (response->type() == Fetch::Infrastructure::Response::Type::Opaque || response->type() == Fetch::Infrastructure::Response::Type::OpaqueRedirect)response = response->unsafe_response();- auto on_data_read = GC::create_function(GC::Heap::the(), [this, response](ByteBuffer data) {- resource_did_load(response, data);+ auto on_data_read = GC::create_function(GC::Heap::the(), GC::captures(self, response), [](auto& self, auto& response, ByteBuffer data) {+ self.resource_did_load(response, data);});- auto on_error = GC::create_function(GC::Heap::the(), [this](JS::Value) {- resource_did_fail();+ auto on_error = GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self, JS::Value) {+ self.resource_did_fail();});VERIFY(response->body());response->body()->fully_read(realm, on_data_read, on_error, GC::Ref { global });- };+ });// 5. Fetch request.(void)Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));// Fetching the resource must delay the load event of the element's node document until the task that is// queued by the networking task source once the resource has been fetched (defined next) has been run.- m_document_load_event_delayer_for_resource_load.empend(document());+ self.m_document_load_event_delayer_for_resource_load.empend(self.document());// 6. If the resource is not yet available (e.g. because the resource was not available in the cache, so that// loading the resource required making a request over the network), then jump to the step below labeled@@ -335,7 +335,7 @@ void HTMLObjectElement::queue_element_task_to_run_object_representation_steps()// response callback to invoke the fallback steps. This prevents the fallback layout from flashing very// briefly between here and the resource loading.}- };+ });queue_an_element_task(HTML::Task::Source::DOMManipulation, move(steps), release_load_event_delay);}@@ -516,9 +516,9 @@ void HTMLObjectElement::run_object_representation_completed_steps(Representation// queue an element task on the DOM manipulation task source given the object element to fire an event named// load at the element.if (representation != Representation::ContentNavigable) {- queue_an_element_task(HTML::Task::Source::DOMManipulation, [&]() {- dispatch_event(create_event_for_element(*this, HTML::EventNames::load));- });+ queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(create_event_for_element(self, HTML::EventNames::load));+ }));}update_layout_and_child_objects(representation);@@ -554,18 +554,18 @@ void HTMLObjectElement::load_image()CSS::record_element_box_kind(*this);CSS::record_element_replaced_content_input(*this);m_resource_request->add_callbacks(- [this] {- CSS::record_element_replaced_content_input(*this);- run_object_representation_completed_steps(Representation::Image);- m_document_load_event_delayer_for_resource_load.take_last();- },- [this] {- run_object_representation_fallback_steps();- m_document_load_event_delayer_for_resource_load.take_last();- },- [this] {- m_document_load_event_delayer_for_resource_load.take_last();- });+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ CSS::record_element_replaced_content_input(self);+ self.run_object_representation_completed_steps(Representation::Image);+ self.m_document_load_event_delayer_for_resource_load.take_last();+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.run_object_representation_fallback_steps();+ self.m_document_load_event_delayer_for_resource_load.take_last();+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_document_load_event_delayer_for_resource_load.take_last();+ }));if (m_resource_request->needs_fetching()) {auto request = HTML::create_potential_CORS_request(*url, Fetch::Infrastructure::Request::Destination::Image, HTML::CORSSettingAttribute::NoCORS);diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cppindex 2601981874c..89a51928ae9 100644--- a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp@@ -420,9 +420,9 @@ void HTMLOrSVGScriptElement::prepare_script()// FIXME: Add "speculationrules" support.if (m_script_type == ScriptType::ImportMap) {// then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.- element.queue_an_element_task(HTML::Task::Source::DOMManipulation, [&element] {+ element.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(element), [](auto& element) {element.dispatch_event(create_event_for_element(element, HTML::EventNames::error));- });+ }));return;}@@ -432,9 +432,9 @@ void HTMLOrSVGScriptElement::prepare_script()// 3. If src is the empty string, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.if (src.is_empty()) {dbgln("HTMLScriptElement: Refusing to run script because the src attribute is empty.");- element.queue_an_element_task(HTML::Task::Source::DOMManipulation, [&element] {+ element.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(element), [](auto& element) {element.dispatch_event(create_event_for_element(element, HTML::EventNames::error));- });+ }));return;}@@ -447,9 +447,9 @@ void HTMLOrSVGScriptElement::prepare_script()// 6. If url is failure, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.if (!url.has_value()) {dbgln("HTMLScriptElement: Refusing to run script because the src URL '{}' is invalid.", url);- element.queue_an_element_task(HTML::Task::Source::DOMManipulation, [&element] {+ element.queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(element), [](auto& element) {element.dispatch_event(create_event_for_element(element, HTML::EventNames::error));- });+ }));return;}@@ -466,12 +466,14 @@ void HTMLOrSVGScriptElement::prepare_script()options.render_blocking = true;// 10. Let onComplete given result be the following steps:- OnFetchScriptComplete on_complete = create_on_fetch_script_complete(element.heap(), [this](auto result) {+ OnFetchScriptComplete on_complete = create_on_fetch_script_complete(element.heap(), GC::captures(element), [](DOM::Element& element, GC::Ptr<Script> result) {+ auto& self = as<HTMLOrSVGScriptElement>(element);+// 1. Mark as ready el given result.if (result)- mark_as_ready(Result { *result });+ self.mark_as_ready(Result { *result });else- mark_as_ready(ResultState::Null {});+ self.mark_as_ready(ResultState::Null {});});// 11. Switch on el's type:@@ -490,13 +492,14 @@ void HTMLOrSVGScriptElement::prepare_script()// This resolves an edge case where mark_as_ready() can execute before we set// m_steps_to_run_when_the_result_is_ready// See https://github.com/whatwg/html/issues/12073- auto on_complete = create_on_fetch_script_complete(element.heap(), [this, &element](auto result) {- element.queue_an_element_task(Task::Source::Networking, [this, result = move(result)] {+ auto on_complete = create_on_fetch_script_complete(element.heap(), GC::captures(element), [](DOM::Element& element, GC::Ptr<Script> result) {+ element.queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(element, result), [](DOM::Element& element, GC::Ptr<Script>& result) {+ auto& self = as<HTMLOrSVGScriptElement>(element);if (!result)- mark_as_ready(ResultState::Null {});+ self.mark_as_ready(ResultState::Null {});else- mark_as_ready(Result(*result));- });+ self.mark_as_ready(Result(*result));+ }));});// Fetch an external module script graph given url, settings object, options, and onComplete.@@ -532,15 +535,17 @@ void HTMLOrSVGScriptElement::prepare_script()options.render_blocking = true;}- auto steps = create_on_fetch_script_complete(element.heap(), [this, &element](auto result) {+ auto steps = create_on_fetch_script_complete(element.heap(), GC::captures(element), [](DOM::Element& element, GC::Ptr<Script> result) {// 1. Queue an element task on the networking task source given el to perform the following steps:- element.queue_an_element_task(Task::Source::Networking, [this, result = move(result)] {+ element.queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(element, result), [](DOM::Element& element, GC::Ptr<Script>& result) {+ auto& self = as<HTMLOrSVGScriptElement>(element);+// 1. Mark as ready el given result.if (!result)- mark_as_ready(ResultState::Null {});+ self.mark_as_ready(ResultState::Null {});else- mark_as_ready(Result(*result));- });+ self.mark_as_ready(Result(*result));+ }));});// 3. Fetch an inline module script graph, given source text, base URL, settings object, options, and with the following steps given result:diff --git a/Libraries/LibWeb/HTML/HTMLSelectElement.cpp b/Libraries/LibWeb/HTML/HTMLSelectElement.cppindex 9a22655e358..8668b291ba8 100644--- a/Libraries/LibWeb/HTML/HTMLSelectElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLSelectElement.cpp@@ -1118,14 +1118,14 @@ void HTMLSelectElement::create_list_box_shadow_tree(DOM::ShadowRoot& shadow_rootMUST(shadow_root.append_child(*m_list_box_element));auto mousedown_function = JS::NativeFunction::create(- HTML::relevant_realm(*this), [this](JS::VM& vm) {+ HTML::relevant_realm(*this), GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(GC::Heap::the(), GC::captures(*this), [](auto& self, JS::VM& vm) {auto event = vm.argument(0).is_object()? Bindings::impl_from<UIEvents::MouseEvent>(&vm.argument(0).as_object()): nullptr;if (event)- handle_list_box_mousedown(*event);+ self.handle_list_box_mousedown(*event);return JS::js_undefined();- },+ }),1, Utf16FlyString {}, &HTML::relevant_realm(*this));auto mousedown_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mousedown_function, HTML::relevant_realm(*this));m_list_box_element->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(mousedown_callback));@@ -1140,11 +1140,11 @@ void HTMLSelectElement::list_box_options_did_change()if (!m_list_box_element || m_list_box_update_queued)return;m_list_box_update_queued = true;- queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {- m_list_box_update_queued = false;- if (m_list_box_element)- update_list_box();- });+ queue_an_element_task(HTML::Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_list_box_update_queued = false;+ if (self.m_list_box_element)+ self.update_list_box();+ }));}void HTMLSelectElement::update_list_box_row_styles()diff --git a/Libraries/LibWeb/HTML/HTMLTrackElement.cpp b/Libraries/LibWeb/HTML/HTMLTrackElement.cppindex 726462121ef..9b862d85988 100644--- a/Libraries/LibWeb/HTML/HTMLTrackElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLTrackElement.cpp@@ -142,11 +142,11 @@ void HTMLTrackElement::parent_changed(GC::Ptr<Node> old_parent)m_track->set_media_element(nullptr);m_track->unset_active_flag_of_cues();media_element->text_track_cue_or_text_track_removed();- media_element->queue_a_media_element_task([track = GC::Ref { *m_track }](HTMLMediaElement& media_element) {+ media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *m_track }), [](auto& track, HTMLMediaElement& media_element) {Bindings::TrackEventInit event_init {};event_init.track = track;media_element.text_tracks()->dispatch_event(TrackEvent::create(HTML::EventNames::removetrack, move(event_init), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(media_element))));- });+ }));}// When a track element's parent element changes and the new parent is a media element, then the user agent must@@ -157,11 +157,11 @@ void HTMLTrackElement::parent_changed(GC::Ptr<Node> old_parent)media_element->text_tracks()->add_track(*m_track);m_track->set_media_element(media_element);media_element->add_newly_introduced_cues(m_track->text_track_list_of_cues());- media_element->queue_a_media_element_task([track = GC::Ref { *m_track }](HTMLMediaElement& media_element) {+ media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *m_track }), [](auto& track, HTMLMediaElement& media_element) {Bindings::TrackEventInit event_init {};event_init.track = track;media_element.text_tracks()->dispatch_event(TrackEvent::create(HTML::EventNames::addtrack, move(event_init), HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(media_element))));- });+ }));}}@@ -234,8 +234,8 @@ void HTMLTrackElement::start_the_track_processing_model()m_loading = true;// 4. Run the remainder of these steps in parallel, allowing whatever caused these steps to run to continue.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this]() {- start_the_track_processing_model_parallel_steps();+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.start_the_track_processing_model_parallel_steps();}));}@@ -275,14 +275,14 @@ void HTMLTrackElement::start_the_track_processing_model_parallel_steps()request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Track);Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = [this, src_generation = m_src_generation](auto response, auto body_bytes) {- m_loading = false;+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, m_src_generation), [](auto& self, auto& src_generation, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {+ self.m_loading = false;// If fetching fails for any reason (network error, the server returns an error code, CORS fails, etc.),// or if URL is the empty string, then queue an element task on the DOM manipulation task source given the media element// to first change the text track readiness state to failed to load and then fire an event named error at the track element.if (!response->url().has_value() || body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status()) || response->is_network_error()) {- track_failed_to_load();+ self.track_failed_to_load();return;}@@ -293,26 +293,26 @@ void HTMLTrackElement::start_the_track_processing_model_parallel_steps()// FIXME: Support text track formats other than WebVTT, and parse the file incrementally as it is received.auto cues = WebVTT::parse_webvtt_file(body_bytes.template get<Core::ImmutableBytes>().bytes());if (!cues.has_value()) {- track_failed_to_load();+ self.track_failed_to_load();return;}// If fetching does not fail, and the file was successfully processed, then the final task that is queued by the networking task source,// after it has finished parsing the data, must change the text track readiness state to loaded, and fire an event named load at the track element.- queue_an_element_task(Task::Source::Networking, [this, cues = cues.release_value(), src_generation]() {- if (src_generation == m_src_generation) {+ self.queue_an_element_task(Task::Source::Networking, GC::create_function(GC::Heap::the(), GC::captures(self, cues.release_value(), src_generation), [](auto& self, auto& cues, auto& src_generation) {+ if (src_generation == self.m_src_generation) {for (auto const& parsed_cue : cues) {auto cue = MUST(WebVTT::VTTCue::create(parsed_cue.start_time, parsed_cue.end_time, parsed_cue.text));cue->set_id(parsed_cue.identifier);- m_track->add_cue(cue);+ self.m_track->add_cue(cue);}}- m_track->set_readiness_state(TextTrack::ReadinessState::Loaded);- dispatch_event(DOM::Event::create(HTML::EventNames::load,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));- });- };+ self.m_track->set_readiness_state(TextTrack::ReadinessState::Loaded);+ self.dispatch_event(DOM::Event::create(HTML::EventNames::load,+ HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self))));+ }));+ });// 4. Fetch request.m_fetch_algorithms = Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input));@@ -324,10 +324,10 @@ void HTMLTrackElement::start_the_track_processing_model_parallel_steps()// 11. Wait until the text track readiness state is no longer set to loading.if (m_track->readiness_state() == TextTrack::ReadinessState::Loading) {- m_track_observer->set_track_readiness_observer([this, url = move(url)](TextTrack::ReadinessState) mutable {- if (m_track->readiness_state() != TextTrack::ReadinessState::Loading)- track_became_ready();- });+ m_track_observer->set_track_readiness_observer(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self, TextTrack::ReadinessState) {+ if (self.m_track->readiness_state() != TextTrack::ReadinessState::Loading)+ self.track_became_ready();+ }));} else {track_became_ready();}@@ -343,11 +343,11 @@ void HTMLTrackElement::track_became_ready()void HTMLTrackElement::track_failed_to_load(){- queue_an_element_task(Task::Source::DOMManipulation, [this]() {- m_track->set_readiness_state(TextTrack::ReadinessState::FailedToLoad);- dispatch_event(DOM::Event::create(HTML::EventNames::error,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));- });+ queue_an_element_task(Task::Source::DOMManipulation, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.m_track->set_readiness_state(TextTrack::ReadinessState::FailedToLoad);+ self.dispatch_event(DOM::Event::create(HTML::EventNames::error,+ HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self))));+ }));}}diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Libraries/LibWeb/HTML/HTMLVideoElement.cppindex a55ae405009..741e91928d6 100644--- a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp@@ -169,9 +169,9 @@ void HTMLVideoElement::set_intrinsic_video_dimensions(Optional<Gfx::Size<u32>> d// dimensions are not available. This matches other browsers.if (dimensions.has_value()) {// the user agent must queue a media element task given the media element to fire an event named resize at the media element.- queue_a_media_element_task([](HTMLMediaElement& self) {+ queue_a_media_element_task(GC::create_function(GC::Heap::the(), [](HTMLMediaElement& self) {self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::resize));- });+ }));document().page().picture_in_picture_controller().video_size_did_change(*this, dimensions->to_type<int>());}@@ -311,7 +311,7 @@ WebIDL::ExceptionOr<void> HTMLVideoElement::determine_element_poster_frame(Optiom_load_event_delayer.emplace(document());// 7. If an image is thus obtained, the poster frame is that image. Otherwise, there is no poster frame.- fetch_algorithms_input.process_response = [weak_self = GC::Weak(*this), poster_url = request->url()](auto response) {+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(GC::Weak(*this), request->url()), [](auto& weak_self, auto& poster_url, GC::Ref<Fetch::Infrastructure::ResponseView> response) {if (!weak_self)return;auto& self = *weak_self;@@ -331,7 +331,7 @@ WebIDL::ExceptionOr<void> HTMLVideoElement::determine_element_poster_frame(Optioreturn;}- auto on_image_data_read = GC::create_function(GC::Heap::the(), [weak_self, poster_url](ByteBuffer image_data) {+ auto on_image_data_read = GC::create_function(GC::Heap::the(), GC::captures(weak_self, poster_url), [](auto& weak_self, auto& poster_url, ByteBuffer image_data) {if (!weak_self)return;// 6. If an image is thus obtained, the poster frame is that image. Otherwise, there is no poster frame.@@ -366,14 +366,14 @@ WebIDL::ExceptionOr<void> HTMLVideoElement::determine_element_poster_frame(Optio});});- auto on_body_read_error = GC::create_function(GC::Heap::the(), [weak_self](JS::Value) {+ auto on_body_read_error = GC::create_function(GC::Heap::the(), GC::captures(weak_self), [](auto& weak_self, JS::Value) {if (!weak_self)return;finalize(*weak_self, nullptr);});response->body()->fully_read(realm, on_image_data_read, on_body_read_error, GC::Ref { global });- };+ });m_fetch_controller = Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.cpp b/Libraries/LibWeb/HTML/HistoryExecutor.cppindex 94358fa7eb3..2b98df63706 100644--- a/Libraries/LibWeb/HTML/HistoryExecutor.cpp+++ b/Libraries/LibWeb/HTML/HistoryExecutor.cpp@@ -293,7 +293,7 @@ void HistoryExecutor::enqueue_changing_navigable_continuation(CrossProcessId ope// In both cases of step 12.8 of apply the history step, afterDocumentPopulated, for a changing navigable continuation.GC::Ref<HistoryExecutor::AfterDocumentPopulated> HistoryExecutor::after_document_populated_steps(CrossProcessId operation_id, GC::Ref<ChangingNavigableContinuationState> changing_navigable_continuation, GC::Ref<OnChangingNavigableHistoryStepJobComplete> on_complete){- return GC::create_function(heap(), [this, operation_id, changing_navigable_continuation, on_complete](GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {+ return GC::create_function(heap(), GC::captures(*this, operation_id, changing_navigable_continuation, on_complete), [](auto& self, auto& operation_id, auto& changing_navigable_continuation, auto& on_complete, GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {changing_navigable_continuation->population_output = output;// NB: Population that produces no document leaves targetEntry's document as it was.@@ -307,7 +307,7 @@ GC::Ref<HistoryExecutor::AfterDocumentPopulated> HistoryExecutor::after_document// NB: The UI process runs steps 2 and 3.// 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.- enqueue_changing_navigable_continuation(operation_id, *changing_navigable_continuation, on_complete);+ self.enqueue_changing_navigable_continuation(operation_id, *changing_navigable_continuation, on_complete);});}@@ -316,7 +316,7 @@ GC::Ref<HistoryExecutor::AfterDocumentPopulated> HistoryExecutor::after_document// afterDocumentPopulated.GC::Ref<GC::Function<void(HistoryNavigationPopulation)>> HistoryExecutor::population_steps(GC::Ref<LocalNavigable> navigable, GC::Ref<AfterDocumentPopulated> after_document_populated){- return GC::create_function(heap(), [this, navigable, after_document_populated](HistoryNavigationPopulation population) {+ return GC::create_function(heap(), GC::captures(navigable, after_document_populated), [](auto& navigable, auto& after_document_populated, HistoryNavigationPopulation population) {if (navigable->has_been_destroyed() || !navigable->active_window()) {after_document_populated->function()(nullptr);return;@@ -330,7 +330,7 @@ GC::Ref<GC::Function<void(HistoryNavigationPopulation)>> HistoryExecutor::populaafter_document_populated->function()(nullptr);return;}- auto output = heap().allocate<PopulateSessionHistoryEntryDocumentOutput>();+ auto output = GC::Heap::the().allocate<PopulateSessionHistoryEntryDocumentOutput>();output->redirected_url = move(result.redirected_url);output->redirect_replaced_fragment = result.redirect_replaced_fragment;output->classic_history_api_state = move(result.classic_history_api_state);@@ -348,8 +348,8 @@ GC::Ref<GC::Function<void(HistoryNavigationPopulation)>> HistoryExecutor::popularequest.history_entry.url, request.source_snapshot_params.allows_downloading, move(fetch_client_origin),request.user_involvement, request.navigation_id.is_empty() ? Optional<Utf16String> {} : Optional<Utf16String> { request.navigation_id }, params.release_value(), request.csp_navigation_type,request.history_entry.document_state.reload_pending ? Bindings::NavigationTimingType::Reload : Bindings::NavigationTimingType::BackForward,- output, GC::create_function(heap(), [navigable, after_document_populated](GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {- queue_apply_history_step_task(*navigable, GC::create_function(navigable->heap(), [after_document_populated, output] {+ output, GC::create_function(GC::Heap::the(), GC::captures(navigable, after_document_populated), [](auto& navigable, auto& after_document_populated, GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {+ queue_apply_history_step_task(*navigable, GC::create_function(navigable->heap(), GC::captures(after_document_populated, output), [](auto& after_document_populated, auto& output) {after_document_populated->function()(output);}));}));@@ -423,7 +423,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId operaoperation.changing_navigable_jobs.ensure(navigable_id);- queue_apply_history_step_task(*navigable, GC::create_function(heap(), [this, operation_id, navigation_type, user_involvement, needs_population, pending_document, claimed_target_entry = move(claimed_target_entry), navigable, on_complete]() mutable {+ queue_apply_history_step_task(*navigable, GC::create_function(heap(), GC::captures(*this, operation_id, navigation_type, user_involvement, needs_population, pending_document, move(claimed_target_entry), navigable, on_complete), [](auto& self, auto& operation_id, auto& navigation_type, auto& user_involvement, auto& needs_population, auto& pending_document, auto& claimed_target_entry, auto& navigable, auto& on_complete) {// 1. Let displayedEntry be navigable's active session history entry.auto displayed_entry = navigable->active_session_history_entry();@@ -434,7 +434,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId operaRefPtr<SessionHistoryEntry> target_entry = claimed_target_entry;// 3. Let changingNavigableContinuation be a changing navigable continuation state with:- auto changing_navigable_continuation = heap().allocate<ChangingNavigableContinuationState>();+ auto changing_navigable_continuation = GC::Heap::the().allocate<ChangingNavigableContinuationState>();changing_navigable_continuation->displayed_document = navigable->active_document();changing_navigable_continuation->target_entry = target_entry;changing_navigable_continuation->navigable = navigable;@@ -460,7 +460,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId operachanging_navigable_continuation->update_only = true;// 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.- enqueue_changing_navigable_continuation(operation_id, *changing_navigable_continuation, on_complete);+ self.enqueue_changing_navigable_continuation(operation_id, *changing_navigable_continuation, on_complete);// 3. Abort these steps.return;@@ -517,13 +517,13 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId operanavigation->fire_a_traverse_navigate_event(*target_entry, user_involvement);}- auto after_document_populated = after_document_populated_steps(operation_id, *changing_navigable_continuation, on_complete);+ auto after_document_populated = self.after_document_populated_steps(operation_id, *changing_navigable_continuation, on_complete);// 8. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:// NB: The UI process decides this, and runs the substeps but for step 4's snapshot of navigable's active document.if (needs_population) {- auto continue_population = population_steps(*navigable, after_document_populated);- auto* operation = find_history_operation(operation_id);+ auto continue_population = self.population_steps(*navigable, after_document_populated);+ auto* operation = self.find_history_operation(operation_id);if (!operation)return;operation->changing_navigable_jobs.ensure(navigable->id()).continue_population = continue_population;@@ -537,7 +537,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId operatarget_entry->document_state()->set_reload_pending(false);target_entry->document_state()->set_reload_bypasses_cache(false);- m_page->client().changing_navigable_history_job_reached_population(operation_id, navigable->id(), create_navigation_source_snapshot(*active_document_source_snapshot_params));+ self.m_page->client().changing_navigable_history_job_reached_population(operation_id, navigable->id(), create_navigation_source_snapshot(*active_document_source_snapshot_params));}// Otherwise, run afterDocumentPopulated immediately.else {@@ -581,8 +581,8 @@ bool HistoryExecutor::create_ui_history_navigation_params(CrossProcessId operatireturn false;auto source_snapshot_params = create_source_snapshot_params_from_navigation_source_snapshot(relevant_realm(*navigable->active_window()), request.source_snapshot_params);- navigable->populate_session_history_entry_document(request, source_snapshot_params, allow_POST, GC::create_function(heap(), [this, operation_id, navigable_id = request.navigable_id](NavigationPopulationResult result) {- m_page->client().history_navigation_params_creation_finished(operation_id, navigable_id, move(result));+ navigable->populate_session_history_entry_document(request, source_snapshot_params, allow_POST, GC::create_function(heap(), GC::captures(*this, operation_id, request.navigable_id), [](auto& self, auto& operation_id, auto& navigable_id, NavigationPopulationResult result) {+ self.m_page->client().history_navigation_params_creation_finished(operation_id, navigable_id, move(result));}));return true;}@@ -644,7 +644,7 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutor// 12. In both cases, let afterPotentialUnloads be the following steps:bool const update_only = continuation->update_only;- auto after_potential_unload = GC::create_function(heap(), [this, navigable, update_only, target_entry, continuation, population_output, clear_classic_history_api_state, clear_navigable_target_name, displayed_document = GC::Ref { *displayed_document }, script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), navigation_type = continuation->navigation_type, on_complete] {+ auto after_potential_unload = GC::create_function(heap(), GC::captures(navigable, update_only, target_entry, continuation, population_output, clear_classic_history_api_state, clear_navigable_target_name, GC::Ref { *displayed_document }, script_history_length, script_history_index, move(entries_for_navigation_api), continuation->navigation_type, on_complete), [](auto& navigable, auto& update_only, auto& target_entry, auto& continuation, auto& population_output, auto& clear_classic_history_api_state, auto& clear_navigable_target_name, auto& displayed_document, auto& script_history_length, auto& script_history_index, auto& entries_for_navigation_api, auto& navigation_type, auto& on_complete) {// AD-HOC: A provisional navigable stands in for a navigable another process hosts, which is destroyed as soon// as its container is removed, e.g. while displayedDocument unloads. The provisional navigable is only// discarded once that navigable's subtree has unloaded, and has no container to take over until then.@@ -704,7 +704,7 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutor// 3. Let updateDocument be an algorithm step which performs update document for history step application given// targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength,// scriptHistoryIndex, navigationType, entriesForNavigationAPI, and previousEntry.- auto update_document = [script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), target_entry, update_only, navigation_type, previous_entry, previous_entry_document_is_initial_about_blank, resolved_document, navigable, continuation] {+ auto update_document = GC::create_function(GC::Heap::the(), GC::captures(script_history_length, script_history_index, entries_for_navigation_api, target_entry, update_only, navigation_type, previous_entry, previous_entry_document_is_initial_about_blank, resolved_document, navigable, continuation), [](auto& script_history_length, auto& script_history_index, auto& entries_for_navigation_api, auto& target_entry, auto& update_only, auto& navigation_type, auto& previous_entry, auto& previous_entry_document_is_initial_about_blank, auto& resolved_document, auto& navigable, auto& continuation) {// NB: The specification initializes the navigation API entries for every newly activated document.// Gating this on a non-null navigationType left documents activated by a creation/destruction// update without an initialized navigation API entry list, which crashes the first same-document@@ -714,15 +714,15 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutorif (update_only)navigable->notify_navigation_observers_navigation_complete();- };+ });// 4. If targetEntry's document is equal to displayedDocument, then perform updateDocument.if (target_entry->document_state()->document_id() == displayed_document->unique_id()) {- update_document();+ update_document->function()();}// 5. Otherwise, queue a global task on the navigation and traversal task source given targetEntry's document's relevant global object to perform updateDocumentelse {- queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*resolved_document), GC::create_function(heap(), move(update_document)));+ queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*resolved_document), update_document);}// 6. Increment completedChangeJobs.@@ -767,7 +767,7 @@ void HistoryExecutor::unload_displayed_document_and_apply_ui_changing_navigable_// perform the following steps:// NB: Use a null document so this remains runnable after displayedDocument becomes non-fully-active.queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr,- GC::create_function(heap(), [displayed_document = GC::Ref { *dequeued->continuation->displayed_document }, new_document = dequeued->continuation->target_document, after_potential_unloads = dequeued->after_potential_unloads] {+ GC::create_function(heap(), GC::captures(GC::Ref { *dequeued->continuation->displayed_document }, dequeued->continuation->target_document, dequeued->after_potential_unloads), [](auto& displayed_document, auto& new_document, auto& after_potential_unloads) {// FIXME: 1. If firePageSwapSteps is given, then run firePageSwapSteps.// 2. Unload document, passing along newDocument if it is not null.diff --git a/Libraries/LibWeb/HTML/ImageRequest.cpp b/Libraries/LibWeb/HTML/ImageRequest.cppindex 827ac4893a9..298dc3f8271 100644--- a/Libraries/LibWeb/HTML/ImageRequest.cpp+++ b/Libraries/LibWeb/HTML/ImageRequest.cpp@@ -138,17 +138,17 @@ void ImageRequest::fetch_image(NonnullRefPtr<Fetch::Infrastructure::Request> reqm_shared_resource_request->fetch_resource(request);}-void ImageRequest::add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop, SharedResourceRequest::DelaysLoadEvent delays_load_event)+void ImageRequest::add_callbacks(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail, GC::Ptr<GC::Function<void()>> on_stop, SharedResourceRequest::DelaysLoadEvent delays_load_event){VERIFY(m_shared_resource_request);- if (auto id = m_shared_resource_request->add_removable_callbacks(move(on_finish), move(on_fail), move(on_stop), delays_load_event); id.has_value())+ if (auto id = m_shared_resource_request->add_removable_callbacks(on_finish, on_fail, on_stop, delays_load_event); id.has_value())m_shared_resource_request_callbacks_ids.append(*id);}-void ImageRequest::add_callbacks_without_delaying_the_load_event(Function<void()> on_finish, Function<void()> on_fail)+void ImageRequest::add_callbacks_without_delaying_the_load_event(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail){VERIFY(m_shared_resource_request);- (void)m_shared_resource_request->add_removable_callbacks(move(on_finish), move(on_fail), {}, SharedResourceRequest::DelaysLoadEvent::No);+ (void)m_shared_resource_request->add_removable_callbacks(on_finish, on_fail, {}, SharedResourceRequest::DelaysLoadEvent::No);}void ImageRequest::stop_waiting_for_fetch()diff --git a/Libraries/LibWeb/HTML/ImageRequest.h b/Libraries/LibWeb/HTML/ImageRequest.hindex 912585d62a9..a5aabd63d94 100644--- a/Libraries/LibWeb/HTML/ImageRequest.h+++ b/Libraries/LibWeb/HTML/ImageRequest.h@@ -60,10 +60,10 @@ public:void prepare_for_presentation(HTMLImageElement&);void fetch_image(NonnullRefPtr<Fetch::Infrastructure::Request>);- void add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop = {}, SharedResourceRequest::DelaysLoadEvent = SharedResourceRequest::DelaysLoadEvent::Yes);+ void add_callbacks(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail, GC::Ptr<GC::Function<void()>> on_stop = {}, SharedResourceRequest::DelaysLoadEvent = SharedResourceRequest::DelaysLoadEvent::Yes);// Adds callbacks that do not make the fetch delay the load event, and that stop_waiting_for_fetch() keeps.- void add_callbacks_without_delaying_the_load_event(Function<void()> on_finish, Function<void()> on_fail);+ void add_callbacks_without_delaying_the_load_event(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail);// Stops waiting for the fetch of the shared resource request, which then no longer delays the load event for// this image request.diff --git a/Libraries/LibWeb/HTML/LazyLoadingElement.h b/Libraries/LibWeb/HTML/LazyLoadingElement.hindex 4ed42be7b5d..b1b7b7efa61 100644--- a/Libraries/LibWeb/HTML/LazyLoadingElement.h+++ b/Libraries/LibWeb/HTML/LazyLoadingElement.h@@ -65,9 +65,9 @@ public:[[nodiscard]] bool has_lazy_load_resumption_steps() const { return !!m_lazy_load_resumption_steps; }- void set_lazy_load_resumption_steps(Function<void()> steps)+ void set_lazy_load_resumption_steps(GC::Ref<GC::Function<void()>> steps){- m_lazy_load_resumption_steps = GC::create_function(GC::Heap::the(), move(steps));+ m_lazy_load_resumption_steps = steps;}void visit_lazy_loading_element(JS::Cell::Visitor& visitor)diff --git a/Libraries/LibWeb/HTML/ListOfAvailableImages.h b/Libraries/LibWeb/HTML/ListOfAvailableImages.hindex bc3604a5681..c5c0f7e6719 100644--- a/Libraries/LibWeb/HTML/ListOfAvailableImages.h+++ b/Libraries/LibWeb/HTML/ListOfAvailableImages.h@@ -8,6 +8,7 @@#include <AK/HashMap.h>#include <AK/Utf16String.h>+#include <LibGC/Function.h>#include <LibJS/Heap/Cell.h>#include <LibURL/Origin.h>#include <LibURL/URL.h>@@ -68,6 +69,8 @@ private:}+GC_UNTRACED_CAPTURE(Web::HTML::ListOfAvailableImages::Key);+namespace AK {template<>diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex e19233f625e..1d10c0e565f 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -500,21 +500,21 @@ void LocalNavigable::start_download_for_response(GC::Ref<Fetch::Infrastructure::if (fetch_controller)page().client().page_did_register_download_controller(*download_id, *fetch_controller);- auto process_body_chunk = GC::create_function(realm.heap(), [navigable = GC::Ref { *this }, download_id = *download_id](ByteBuffer data) {+ auto process_body_chunk = GC::create_function(realm.heap(), GC::captures(GC::Ref { *this }, *download_id), [](auto& navigable, auto& download_id, ByteBuffer data) {if (navigable->page().client().page_is_download_canceled(download_id))return;navigable->page().client().page_did_receive_download_data(download_id, move(data));});- auto process_end_of_body = GC::create_function(realm.heap(), [navigable = GC::Ref { *this }, download_id = *download_id]() {+ auto process_end_of_body = GC::create_function(realm.heap(), GC::captures(GC::Ref { *this }, *download_id), [](auto& navigable, auto& download_id) {if (navigable->page().client().page_is_download_canceled(download_id))return;navigable->page().client().page_did_finish_download(download_id);});- auto process_body_error = GC::create_function(realm.heap(), [navigable = GC::Ref { *this }, download_id = *download_id](JS::Value) {+ auto process_body_error = GC::create_function(realm.heap(), GC::captures(GC::Ref { *this }, *download_id), [](auto& navigable, auto& download_id, JS::Value) {if (navigable->page().client().page_is_download_canceled(download_id))return;@@ -1025,7 +1025,7 @@ void LocalNavigable::continue_navigation_at_population(NavigationPopulationRequerequest.csp_navigation_type,Bindings::NavigationTimingType::Navigate,output,- GC::create_function(navigable->heap(), [navigable, history_entry, history_handling = request.history_handling, navigation_id = request.navigation_id, user_involvement = request.user_involvement](GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) mutable {+ GC::create_function(navigable->heap(), GC::captures(navigable, history_entry, request.history_handling, request.navigation_id, request.user_involvement), [](auto& navigable, auto& history_entry, auto& history_handling, auto& navigation_id, auto& user_involvement, GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {// AD-HOC: This check is not in the spec but we should not continue navigation if ongoing navigation id has changed.if (navigable->ongoing_navigation() != navigation_id) {if (output && output->document)@@ -1262,7 +1262,7 @@ void LocalNavigable::update_nonchanging_navigable_history_step_state(HistoryObje{// AD-HOC: Queue with null document instead of using queue_global_task. A document-associated task can become// unrunnable while the UI process waits for completion, so validate the document when the task runs.- queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr, GC::create_function(heap(), [navigable = GC::Ref { *this }, history_object_length_and_index, on_complete] {+ queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr, GC::create_function(heap(), GC::captures(GC::Ref { *this }, history_object_length_and_index.script_history_index, history_object_length_and_index.script_history_length, on_complete), [](auto& navigable, auto& script_history_index, auto& script_history_length, auto& on_complete) {// 1. Let document be navigable's active document.auto document = navigable->active_document();if (navigable->has_been_destroyed() || !document || !document->is_fully_active()) {@@ -1271,10 +1271,10 @@ void LocalNavigable::update_nonchanging_navigable_history_step_state(HistoryObje}// 2. Set document's history object's index to scriptHistoryIndex.- document->history()->m_index = history_object_length_and_index.script_history_index;+ document->history()->m_index = script_history_index;// 3. Set document's history object's length to scriptHistoryLength.- document->history()->m_length = history_object_length_and_index.script_history_length;+ document->history()->m_length = script_history_length;// 4. Increment completedNonchangingJobs.on_complete->function()();@@ -1289,7 +1289,7 @@ void LocalNavigable::queue_navigation_api_state_clear_task()if (!active_window())return;- queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*active_window()), GC::create_function(heap(), [navigable = GC::Ref { *this }] {+ queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*active_window()), GC::create_function(heap(), GC::captures(GC::Ref { *this }), [](auto& navigable) {if (navigable->has_been_destroyed() || !navigable->active_window())return;@@ -1321,7 +1321,7 @@ void LocalNavigable::run_ui_descendant_unload_task(ChildNavigableDestruction chi// The UI process has already unloaded this document's descendants.queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr,- GC::create_function(heap(), [navigable = GC::Ref { *this }, stop_hosting_after_unload, on_complete] {+ GC::create_function(heap(), GC::captures(GC::Ref { *this }, stop_hosting_after_unload, on_complete), [](auto& navigable, auto& stop_hosting_after_unload, auto& on_complete) {if (auto active_document = navigable->active_document()) {// The browsing context's WindowProxy outlives the document, since scripts hold it for the navigable.if (auto browsing_context = active_document->browsing_context())@@ -2344,15 +2344,15 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigation// FIXME: Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:// Let processResponse be the following algorithm given a response fetchedResponse:- auto process_response = [state_holder](GC::Ref<Fetch::Infrastructure::ResponseView> fetch_response) {+ auto process_response = GC::create_function(realm.heap(), GC::captures(state_holder), [](auto& state_holder, GC::Ref<Fetch::Infrastructure::ResponseView> fetch_response) {// 1. Set response to fetchedResponse.state_holder->response = fetch_response;VERIFY(state_holder->continuation_steps);state_holder->continuation_steps->function()(NavigationParamsFetchStateHolder::ContinuationReason::GotResponse);- };+ });Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = move(process_response);+ fetch_algorithms_input.process_response = process_response;state_holder->fetch_controller = Fetch::Fetching::fetch(realm,state_holder->request,@@ -2369,13 +2369,13 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<NavigationGC::Ptr<NavigationObserver> ongoing_navigation_changed_observer;if (state_holder->navigation_id.has_value()) {ongoing_navigation_changed_observer = NavigationObserver::create(*state_holder->navigable);- ongoing_navigation_changed_observer->set_ongoing_navigation_changed([state_holder] {+ ongoing_navigation_changed_observer->set_ongoing_navigation_changed(GC::create_function(realm.heap(), GC::captures(state_holder), [](auto& state_holder) {VERIFY(state_holder->continuation_steps);state_holder->continuation_steps->function()(NavigationParamsFetchStateHolder::ContinuationReason::OngoingNavigationChanged);- });+ }));}- state_holder->continuation_steps = GC::create_function(realm.heap(), [&realm, state_holder, ongoing_navigation_changed_observer, top_level_completion_steps, fetch_completion_steps](NavigationParamsFetchStateHolder::ContinuationReason continuation_reason) {+ state_holder->continuation_steps = GC::create_function(realm.heap(), GC::captures(realm, state_holder, ongoing_navigation_changed_observer, top_level_completion_steps, fetch_completion_steps), [](auto& realm, auto& state_holder, auto& ongoing_navigation_changed_observer, auto& top_level_completion_steps, auto& fetch_completion_steps, NavigationParamsFetchStateHolder::ContinuationReason continuation_reason) {// If the latter condition occurs, then abort fetchController, and return. Otherwise, proceed onward.if (state_holder->navigation_id.has_value()) {VERIFY(ongoing_navigation_changed_observer);@@ -2384,7 +2384,7 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigationif (continuation_reason == NavigationParamsFetchStateHolder::ContinuationReason::OngoingNavigationChanged) {if (state_holder->navigable->ongoing_navigation() != *state_holder->navigation_id) {state_holder->fetch_controller->abort(realm, {});- auto result = realm.heap().allocate<InternalNavigationResult>();+ auto result = GC::Heap::the().allocate<InternalNavigationResult>();result->navigation_params = LocalNavigable::NullOrError {};top_level_completion_steps->function()(*result);return;@@ -2396,7 +2396,7 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigation// was opened, with nothing to navigate left.if (state_holder->navigable->has_been_destroyed() || !state_holder->navigable->active_document()) {state_holder->fetch_controller->abort(realm, {});- auto result = realm.heap().allocate<InternalNavigationResult>();+ auto result = GC::Heap::the().allocate<InternalNavigationResult>();result->navigation_params = LocalNavigable::NullOrError {};top_level_completion_steps->function()(*result);return;@@ -2411,7 +2411,7 @@ static void perform_navigation_params_fetch(JS::Realm& realm, GC::Ref<Navigation}// 8. If request's body is null, then set entry's document state's resource to null.- if (state_holder->request->body().has<Empty>()) {+ if (state_holder->request->body().template has<Empty>()) {state_holder->resource_cleared = true;state_holder->resource = Empty {};}@@ -2796,8 +2796,8 @@ static void create_navigation_params_by_fetching(state_holder->target_snapshot_params = target_snapshot_params;state_holder->navigation_id = move(navigation_id);- perform_navigation_params_fetch(realm, state_holder, completion_steps, GC::create_function(realm.heap(), [&realm, state_holder, user_involvement, completion_steps] {- auto result = realm.heap().allocate<InternalNavigationResult>();+ perform_navigation_params_fetch(realm, state_holder, completion_steps, GC::create_function(realm.heap(), GC::captures(state_holder, user_involvement, completion_steps), [](auto& state_holder, auto& user_involvement, auto& completion_steps) {+ auto result = GC::Heap::the().allocate<InternalNavigationResult>();result->redirected_url = move(state_holder->redirected_url);result->redirect_replaced_fragment = state_holder->redirect_replaced_fragment;result->classic_history_api_state = move(state_holder->redirect_classic_history_api_state);@@ -2814,7 +2814,7 @@ static void create_navigation_params_by_fetching(// - initiator origin: responseOrigin// - navigation timing type: navTimingType// - user involvement: userInvolvement- result->navigation_params = realm.heap().allocate<NonFetchSchemeNavigationParams>(+ result->navigation_params = GC::Heap::the().allocate<NonFetchSchemeNavigationParams>(state_holder->navigation_id,state_holder->navigable,state_holder->location_url.value().value(),@@ -2883,7 +2883,7 @@ static void create_navigation_params_by_fetching(// user involvement: userInvolvement// FIXME: Value for iframe element referrer policy is missing in the spec. https://github.com/whatwg/html/issues/12567// So, we default to the empty string.- result->navigation_params = realm.heap().allocate<NavigationParams>(+ result->navigation_params = GC::Heap::the().allocate<NavigationParams>(state_holder->navigation_id,state_holder->navigable,state_holder->request,@@ -2989,7 +2989,7 @@ static void create_navigation_params_for_population(static void create_navigation_population_result(Window& window, GC::Ref<InternalNavigationResult> result, GC::Ref<GC::Function<void(NavigationPopulationResult)>> on_complete){auto& realm = window.principal_realm();- create_navigation_params_descriptor(realm, result->navigation_params, GC::create_function(realm.heap(), [result, on_complete](NavigationParamsVariantDescriptor navigation_params) {+ create_navigation_params_descriptor(realm, result->navigation_params, GC::create_function(realm.heap(), GC::captures(result, on_complete), [](auto& result, auto& on_complete, NavigationParamsVariantDescriptor navigation_params) {Optional<SessionHistoryDocumentStateDescriptor> replacement_document_state;if (result->replacement_document_state)replacement_document_state = create_session_history_document_state_descriptor(*result->replacement_document_state);@@ -3010,26 +3010,26 @@ static void create_navigation_population_result(Window& window, GC::Ref<Internalvoid LocalNavigable::populate_session_history_entry_document(NavigationPopulationRequest const& request, GC::Ref<SourceSnapshotParams> source_snapshot_params, bool allow_POST, GC::Ref<GC::Function<void(NavigationPopulationResult)>> response_steps){// AD-HOC: Not in the spec but subsequent steps will fail if the navigable doesn't have an active window.- auto respond_without_an_active_window = [response_steps] {+ auto respond_without_an_active_window = GC::create_function(heap(), GC::captures(response_steps), [](auto& response_steps) {response_steps->function()({.navigation_params = NavigationParamsNullOrError { "Navigable has no active window"_utf16 },.redirected_url = {},.classic_history_api_state = {},.replacement_document_state = {},});- };+ });if (!active_window()) {- respond_without_an_active_window();+ respond_without_an_active_window->function()();return;}- auto received_navigation_params = GC::create_function(heap(), [this, response_steps, respond_without_an_active_window](GC::Ref<InternalNavigationResult> result) {- if (!active_window()) {+ auto received_navigation_params = GC::create_function(heap(), GC::captures(*this, response_steps, respond_without_an_active_window), [](auto& self, auto& response_steps, auto& respond_without_an_active_window, GC::Ref<InternalNavigationResult> result) {+ if (!self.active_window()) {stop_response_body_delivery(result->navigation_params);- respond_without_an_active_window();+ respond_without_an_active_window->function()();return;}- create_navigation_population_result(*active_window(), result, response_steps);+ create_navigation_population_result(*self.active_window(), result, response_steps);});auto navigation_timing_type = request.history_entry.document_state.reload_pending ? Bindings::NavigationTimingType::Reload : Bindings::NavigationTimingType::BackForward;@@ -3074,7 +3074,7 @@ static GC::Ref<DOM::Document> create_navigation_error_document(LocalNavigable& n// FIXME: Directly calling parser->the_end results in a deadlock, because it waits for the warning image to load.// However the response is never processed when parser->the_end is called.// Queuing a global task is a workaround for now.- queue_a_task(Task::Source::Unspecified, HTML::main_thread_event_loop(), document, GC::create_function(document.heap(), [&document, parser] {+ queue_a_task(Task::Source::Unspecified, HTML::main_thread_event_loop(), document, GC::create_function(document.heap(), GC::captures(document, parser), [](auto& document, auto& parser) {HTMLParser::the_end(document, parser);}));});@@ -3138,11 +3138,11 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent(*params)->document_id = output->document_id;// 5. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:- queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function(heap(), [this, url, source_allows_downloading, source_interface_origin, user_involvement, navigation_id, navigation_params, csp_navigation_type, navigation_timing_type, output, completion_steps]() mutable {+ queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function<void()>(heap(), GC::captures(*this, url, source_allows_downloading, source_interface_origin, user_involvement, navigation_id, navigation_params, csp_navigation_type, navigation_timing_type, output, completion_steps), [](LocalNavigable& self, auto& url, auto& source_allows_downloading, auto& source_interface_origin, auto& user_involvement, auto& navigation_id, NavigationParamsVariant& navigation_params, auto& csp_navigation_type, auto& navigation_timing_type, auto& output, auto& completion_steps) {// 1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and abort these steps.// NB: A reload history job keeps the traversal marker while its document is populated.- auto is_reload_traversal = navigation_timing_type == Bindings::NavigationTimingType::Reload && ongoing_navigation().has<Traversal>();- if (navigation_id.has_value() && ongoing_navigation() != navigation_id && !is_reload_traversal) {+ auto is_reload_traversal = navigation_timing_type == Bindings::NavigationTimingType::Reload && self.ongoing_navigation().has<Traversal>();+ if (navigation_id.has_value() && self.ongoing_navigation() != navigation_id && !is_reload_traversal) {stop_response_body_delivery(navigation_params);if (completion_steps)completion_steps->function()(nullptr);@@ -3163,7 +3163,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent// INTEROP: A navigation that loads no document is reported as failed to WebDriver BiDi, which is what other// implementations do, so that the navigation's waiters learn it ended.if (!output->document && WebDriver::BiDi::is_active())- WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, url);+ WebDriver::BiDi::navigation_event(self, "browsingContext.navigationFailed"sv, navigation_id, url);// 2. Set saveExtraDocumentState to false.output->save_extra_document_state = false;@@ -3179,13 +3179,13 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent// document.else if (navigation_params.visit([](NullOrError) { return true; },- [this, csp_navigation_type](GC::Ref<NavigationParams> navigation_params) {- auto csp_result = ContentSecurityPolicy::should_navigation_response_to_navigation_request_of_type_in_target_be_blocked_by_content_security_policy(navigation_params->request, *navigation_params->response, navigation_params->policy_container->csp_list, csp_navigation_type, *this);+ [&self, csp_navigation_type](GC::Ref<NavigationParams> navigation_params) {+ auto csp_result = ContentSecurityPolicy::should_navigation_response_to_navigation_request_of_type_in_target_be_blocked_by_content_security_policy(navigation_params->request, *navigation_params->response, navigation_params->policy_container->csp_list, csp_navigation_type, self);if (csp_result == ContentSecurityPolicy::Directives::Directive::Result::Blocked)return true;// FIXME: Pass in navigationParams's policy container's CSP list- return !check_a_navigation_responses_adherence_to_x_frame_options(navigation_params->response, this, navigation_params->policy_container->csp_list, navigation_params->origin);+ return !check_a_navigation_responses_adherence_to_x_frame_options(navigation_params->response, &self, navigation_params->policy_container->csp_list, navigation_params->origin);},[](GC::Ref<NonFetchSchemeNavigationParams>) { return false; })) {// 1. Set entry's document state's document to the result of creating a document for inline content that doesn't have a DOM, given navigable, null, navTimingType, and userInvolvement. The inline content should indicate to the user the sort of error that occurred.@@ -3193,7 +3193,7 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent// AD-HOC: Name the URL that actually failed to load: The last URL the navigation was redirected to, if// any — rather than the URL it started at.auto error_url = output->redirected_url.value_or(url);- output->document = create_navigation_error_document(*this, navigation_id, navigation_timing_type, user_involvement, output->inline_content_origin.value(), output->document_id, error_url, error_message);+ output->document = create_navigation_error_document(self, navigation_id, navigation_timing_type, user_involvement, output->inline_content_origin.value(), output->document_id, error_url, error_message);// 2. Make document unsalvageable given entry's document state's document and "navigation-failure".if (output->document)@@ -3217,13 +3217,13 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_entauto response_url = navigation_params.visit([&](GC::Ref<NavigationParams> const& it) { return it->response->url().value_or(url); },[&](auto const&) { return url; });- WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, response_url);+ WebDriver::BiDi::navigation_event(self, "browsingContext.navigationFailed"sv, navigation_id, response_url);}}// INTEROP: A navigation whose fetch failed is reported as failed to WebDriver BiDi too, which is what other// implementations do.else if (WebDriver::BiDi::is_active()) {- WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, error_url);+ WebDriver::BiDi::navigation_event(self, "browsingContext.navigationFailed"sv, navigation_id, error_url);}}@@ -3247,28 +3247,27 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_entif (!sniff_bytes.has_value()) {// Async path: bytes not yet available, wait for themnav_params->response->resume_body_delivery_up_to(Fetch::Infrastructure::MAX_SNIFF_BYTES);- body->wait_for_sniff_bytes(GC::create_function(heap(),- [output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url, navigation_id, is_reload_traversal](Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {- // AD-HOC: The document may have been destroyed between when the fetch started and when the- // bytes arrived. A response that failed mid-sniff must not be loaded as a document- // off its partial bytes either.- // AD-HOC: A navigation that a newer one superseded during the wait makes no document either:- // the document would take over the Window of an initial about:blank, whose tasks then- // wait for a document that never becomes active, among them those of the newer- // navigation.- auto is_superseded = navigation_id.has_value() && nav_params->navigable->ongoing_navigation() != navigation_id && !is_reload_traversal;- if (!is_superseded && nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {- load_document_or_handle_download(nav_params, sniff_bytes.bytes, url, source_allows_downloading, source_interface_origin, *output);- } else {- stop_response_body_delivery(navigation_params);- if (sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Failed)- output->save_extra_document_state = false;- }- output->navigation_params = navigation_params;- report_a_document_with_an_origin_of_its_own(*nav_params->navigable, output);- if (completion_steps)- completion_steps->function()(output);- }));+ body->wait_for_sniff_bytes(GC::create_function(self.heap(), GC::captures(output, nav_params, navigation_params, completion_steps, source_allows_downloading, source_interface_origin, url, navigation_id, is_reload_traversal), [](auto& output, auto& nav_params, auto& navigation_params, auto& completion_steps, auto& source_allows_downloading, auto& source_interface_origin, auto& url, auto& navigation_id, auto& is_reload_traversal, Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {+ // AD-HOC: The document may have been destroyed between when the fetch started and when the+ // bytes arrived. A response that failed mid-sniff must not be loaded as a document+ // off its partial bytes either.+ // AD-HOC: A navigation that a newer one superseded during the wait makes no document either:+ // the document would take over the Window of an initial about:blank, whose tasks then+ // wait for a document that never becomes active, among them those of the newer+ // navigation.+ auto is_superseded = navigation_id.has_value() && nav_params->navigable->ongoing_navigation() != navigation_id && !is_reload_traversal;+ if (!is_superseded && nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {+ load_document_or_handle_download(nav_params, sniff_bytes.bytes, url, source_allows_downloading, source_interface_origin, *output);+ } else {+ stop_response_body_delivery(navigation_params);+ if (sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Failed)+ output->save_extra_document_state = false;+ }+ output->navigation_params = navigation_params;+ report_a_document_with_an_origin_of_its_own(*nav_params->navigable, output);+ if (completion_steps)+ completion_steps->function()(output);+ }));return;}@@ -3284,13 +3283,13 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent}output->navigation_params = navigation_params;- report_a_document_with_an_origin_of_its_own(*this, output);+ report_a_document_with_an_origin_of_its_own(self, output);if (completion_steps)completion_steps->function()(output);}),Task::Priority::Normal,// A task its document drops unrun stops the body it would have handed on.- GC::create_function(heap(), [navigation_params] {+ GC::create_function(heap(), GC::captures(navigation_params), [](auto& navigation_params) {stop_response_body_delivery(navigation_params);}));}@@ -3305,22 +3304,22 @@ void LocalNavigable::create_navigation_params_for_navigation(NavigationPopulatio}// 3. Queue a global task on the navigation and traversal task source given navigable's active window to abort a document and its descendants given navigable's active document.- queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function(heap(), [this] {- active_document()->abort_a_document_and_its_descendants();+ queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ self.active_document()->abort_a_document_and_its_descendants();}));- auto received_navigation_params = GC::create_function(heap(), [this, request, navigation_id](GC::Ref<InternalNavigationResult> result) mutable {- if (!active_window() || ongoing_navigation() != navigation_id) {+ auto received_navigation_params = GC::create_function(heap(), GC::captures(*this, request, navigation_id), [](auto& self, auto& request, auto& navigation_id, GC::Ref<InternalNavigationResult> result) {+ if (!self.active_window() || self.ongoing_navigation() != navigation_id) {stop_response_body_delivery(result->navigation_params);return;}- create_navigation_population_result(*active_window(), result, GC::create_function(heap(), [this, request = move(request), navigation_id, result](NavigationPopulationResult population_result) mutable {- if (!active_window() || ongoing_navigation() != navigation_id) {+ create_navigation_population_result(*self.active_window(), result, GC::create_function(self.heap(), GC::captures(self, move(request), navigation_id, result), [](auto& self, auto& request, auto& navigation_id, auto& result, NavigationPopulationResult population_result) {+ if (!self.active_window() || self.ongoing_navigation() != navigation_id) {stop_response_body_delivery(result->navigation_params);return;}- page().client().navigation_params_creation_finished(*this, move(request), move(population_result));+ self.page().client().navigation_params_creation_finished(self, move(request), move(population_result));}));});@@ -3544,8 +3543,8 @@ void LocalNavigable::navigate_to_a_javascript_url_from_ui_process(URL::URL const// NB: initialInsertion is false for a navigation the UI process runs: it never inserts a container.// NB: The task holds request's client until it runs.m_queued_javascript_url_navigations.append(navigation_id);- queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*window), GC::create_function(heap(), [this, request, client = source_snapshot_params->fetch_client, history_handling, initiator_origin, user_involvement, csp_navigation_type, navigation_id = move(navigation_id)] {- navigate_to_a_javascript_url(request, history_handling, initiator_origin, user_involvement, csp_navigation_type, InitialInsertion::No, navigation_id);+ queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*window), GC::create_function(heap(), GC::captures(*this, request, source_snapshot_params->fetch_client, history_handling, initiator_origin, user_involvement, csp_navigation_type, move(navigation_id)), [](auto& self, auto& request, auto&, auto& history_handling, auto& initiator_origin, auto& user_involvement, auto& csp_navigation_type, auto& navigation_id) {+ self.navigate_to_a_javascript_url(request, history_handling, initiator_origin, user_involvement, csp_navigation_type, InitialInsertion::No, navigation_id);}));}@@ -3724,8 +3723,8 @@ void LocalNavigable::begin_navigation(PreparedNavigation navigation)// NB: The task holds request's client until it runs.VERIFY(active_window());m_queued_javascript_url_navigations.append(navigation_id);- queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function(heap(), [this, request, client = source_snapshot_params->fetch_client, history_handling, initiator_origin_snapshot, user_involvement, csp_navigation_type, initial_insertion, navigation_id] {- navigate_to_a_javascript_url(request, to_history_handling_behavior(history_handling), initiator_origin_snapshot, user_involvement, csp_navigation_type, initial_insertion, navigation_id);+ queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function(heap(), GC::captures(*this, request, source_snapshot_params->fetch_client, history_handling, initiator_origin_snapshot, user_involvement, csp_navigation_type, initial_insertion, navigation_id), [](auto& self, auto& request, auto&, auto& history_handling, auto& initiator_origin_snapshot, auto& user_involvement, auto& csp_navigation_type, auto& initial_insertion, auto& navigation_id) {+ self.navigate_to_a_javascript_url(request, to_history_handling_behavior(history_handling), initiator_origin_snapshot, user_involvement, csp_navigation_type, initial_insertion, navigation_id);}));// 3. Return.@@ -3847,8 +3846,8 @@ void LocalNavigable::run_navigation_unload_check(Utf16String const& navigation_i// NB: This page checks the documents it hosts, last: the UI process, which requested the check, ran it in the// pages hosting the others first, and whether one of them showed the prompt comes with the request.check_if_unloading_is_canceled(page(), hosted_inclusive_descendant_navigables(), as_if<LocalTraversableNavigable>(this), {}, {}, {}, unload_prompt_shown,- GC::create_function(heap(), [this, navigation_id, completion_steps](CheckIfUnloadingIsCanceledResult unload_prompt_canceled, UnloadPromptShown) {- if (has_been_destroyed() || !active_window()) {+ GC::create_function(heap(), GC::captures(*this, navigation_id, completion_steps), [](auto& self, auto& navigation_id, auto& completion_steps, CheckIfUnloadingIsCanceledResult unload_prompt_canceled, UnloadPromptShown) {+ if (self.has_been_destroyed() || !self.active_window()) {completion_steps->function()(false);return;}@@ -3857,7 +3856,7 @@ void LocalNavigable::run_navigation_unload_check(Utf16String const& navigation_i// NB: The UI process learns of the canceled check from the population-failure report and ends the// recorded load itself.if (unload_prompt_canceled != CheckIfUnloadingIsCanceledResult::Continue) {- stop_delaying_load_events_for_navigation(navigation_id);+ self.stop_delaying_load_events_for_navigation(navigation_id);// AD-HOC: Step 2 ends with 'Abort these steps.', which leaves navigable's ongoing navigation as// navigationId: step 24 of navigate set it ('Set the ongoing navigation for navigable to// navigationId.'), and the canceled navigation runs nothing further that would reset it. 'Each@@ -3875,14 +3874,14 @@ void LocalNavigable::run_navigation_unload_check(Utf16String const& navigation_i// continueLoadAfterNavigationPolicy() stops on shouldClose(), and nsDocShell::InternalLoad()// returns on PermitUnload()), so no state of the canceled attempt outlives it there either, and// none does here once the ongoing navigation is reset.- if (ongoing_navigation() == navigation_id)- set_ongoing_navigation({});+ if (self.ongoing_navigation() == navigation_id)+ self.set_ongoing_navigation({});completion_steps->function()(false);return;}- if (ongoing_navigation() != navigation_id) {- stop_delaying_load_events_for_navigation(navigation_id);+ if (self.ongoing_navigation() != navigation_id) {+ self.stop_delaying_load_events_for_navigation(navigation_id);completion_steps->function()(false);return;}@@ -4359,7 +4358,7 @@ void LocalNavigable::reload(Optional<StorageSerializationRecord> navigation_api_.user_involvement = user_involvement,},{- .on_apply_history_step_complete = GC::create_function(heap(), [reloading_entry](HistoryStepResult result) {+ .on_apply_history_step_complete = GC::create_function(heap(), GC::captures(reloading_entry), [](auto& reloading_entry, HistoryStepResult result) {if (result == HistoryStepResult::Applied)return;@@ -4414,7 +4413,7 @@ void LocalTraversableNavigable::request_close_preflight(GC::Ref<GC::Function<voireturn;}- auto state_callback = GC::create_function(heap(), [callback](CheckIfUnloadingIsCanceledResult result, UnloadPromptShown) {+ auto state_callback = GC::create_function(heap(), GC::captures(callback), [](auto& callback, CheckIfUnloadingIsCanceledResult result, UnloadPromptShown) {callback->function()(result == CheckIfUnloadingIsCanceledResult::Continue);});auto state = heap().allocate<CheckUnloadingCanceledState>(page(), GC::Ptr<LocalTraversableNavigable> { this }, GC::Ptr<LocalTraversableNavigable> {}, Optional<UserNavigationInvolvement> {}, UnloadPromptShown::No, state_callback);@@ -4460,7 +4459,7 @@ void finalize_a_cross_document_navigation(GC::Ref<LocalNavigable> navigable, His.pending_document = pending_document,.local_target_navigable_id = navigable->id(),.local_target_entry = history_entry,- .on_complete = GC::create_function(navigable->heap(), [navigable, navigation_id, has_document = !!pending_document] {+ .on_complete = GC::create_function(navigable->heap(), GC::captures(navigable, navigation_id, !!pending_document), [](auto& navigable, auto& navigation_id, auto& has_document) {// AD-HOC: Step 2 runs as the navigation's document is activated. When the steps end without activating// it, the navigation is dropped, and stops delaying load events.if (has_document && !navigable->has_been_destroyed() && navigable->is_delaying_load_events())@@ -4895,7 +4894,7 @@ static GC::Ptr<DOM::Element> adopt_async_element_scroll_offset(DOM::Document& dostatic void queue_async_scroll_operation_promise_resolution(GC::Ref<WebIDL::Promise> promise){auto& realm = promise->promise()->shape().realm();- HTML::queue_a_microtask(nullptr, GC::create_function(realm.heap(), [promise] {+ HTML::queue_a_microtask(nullptr, GC::create_function(realm.heap(), GC::captures(promise), [](auto& promise) {auto& realm = promise->promise()->shape().realm();HTML::TemporaryExecutionContext execution_context {realm,@@ -8037,8 +8036,8 @@ GC::Ref<WebIDL::Promise> LocalNavigable::perform_a_scroll_of_the_viewport(CSSPixTemporaryExecutionContext execution_context_for_promise_reactions { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::wait_for_all(realm, { { layout_viewport_scroll.promise, visual_viewport_scroll.promise } },- [scroll_promise](auto const&) { WebIDL::resolve_promise(scroll_promise); },- [scroll_promise](JS::Value) { WebIDL::resolve_promise(scroll_promise); });+ GC::create_function(realm.heap(), GC::captures(scroll_promise), [](auto& scroll_promise, Vector<JS::Value> const&) { WebIDL::resolve_promise(scroll_promise); }),+ GC::create_function(realm.heap(), GC::captures(scroll_promise), [](auto& scroll_promise, JS::Value) { WebIDL::resolve_promise(scroll_promise); }));return scroll_promise;}diff --git a/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp b/Libraries/LibWeb/HTML/LocalTraversableNavigable.cppindex 789c0aa4726..f54bbffe6d0 100644--- a/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp@@ -147,9 +147,9 @@ GC::Ref<LocalTraversableNavigable> LocalTraversableNavigable::create_a_fresh_top// AD-HOC: Mark the about:blank document as finished parsing. This matches the behavior of the window open steps.auto document = GC::Ref(*traversable->active_document());auto completion_token = HTML::HTMLParser::parserless_completion_token(document);- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(traversable->heap(), [document, completion_token] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(traversable->heap(), GC::captures(document, completion_token.parser_generation), [](auto& document, auto& parser_generation) {// FIXME: We do this other places too when creating a new about:blank document. Perhaps it's worth a spec issue?- HTML::HTMLParser::the_end(document, completion_token);+ HTML::HTMLParser::the_end(document, { parser_generation });}));// 2. Navigate traversable to initialNavigationURL using traversable's active document, with documentResource set to initialNavigationPostResource.@@ -176,8 +176,8 @@ GC::Ref<LocalTraversableNavigable> LocalTraversableNavigable::create_stand_in(Ba// The stand-in displays the tab until the document it populates does: its document completes as a fresh// traversable's.auto completion_token = HTML::HTMLParser::parserless_completion_token(document);- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(traversable->heap(), [document = GC::Ref { document }, completion_token] {- HTML::HTMLParser::the_end(document, completion_token);+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(traversable->heap(), GC::captures(GC::Ref { document }, completion_token.parser_generation), [](auto& document, auto& parser_generation) {+ HTML::HTMLParser::the_end(document, { parser_generation });}));return traversable;}@@ -247,8 +247,8 @@ void LocalTraversableNavigable::close_top_level_traversable_from_script()this_traversable.set_closing(true);// 2. Queue a task on the DOM manipulation task source to definitely close thisTraversable.- queue_a_task(Task::Source::DOMManipulation, nullptr, nullptr, GC::create_function(heap(), [this] {- definitely_close_top_level_traversable();+ queue_a_task(Task::Source::DOMManipulation, nullptr, nullptr, GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ self.definitely_close_top_level_traversable();}));}@@ -271,19 +271,19 @@ void LocalTraversableNavigable::definitely_close_top_level_traversable(PromptToU{VERIFY(is_top_level_traversable());- auto append_close_steps = [this] {- if (m_close_steps_have_been_appended)+ auto append_close_steps = GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ if (self.m_close_steps_have_been_appended)return;- m_close_steps_have_been_appended = true;+ self.m_close_steps_have_been_appended = true;// 3. Append the following session history traversal steps to traversable:// NB: The UI process runs the traversal steps' unload recursion and delivers the final unload-and-destroy task// through run_ui_traversable_close_unload_task.- page().history_executor().request_history_operation(CloseTopLevelTraversableHistoryOperationParameters {});- };+ self.page().history_executor().request_history_operation(CloseTopLevelTraversableHistoryOperationParameters {});+ });if (prompt_to_unload == PromptToUnload::No) {- append_close_steps();+ append_close_steps->function()();return;}@@ -291,16 +291,16 @@ void LocalTraversableNavigable::definitely_close_top_level_traversable(PromptToU// 2. If the result of checking if unloading is canceled for toUnload is not "continue", then return.// NB: The documents of toUnload are hosted by this page and by others. The UI process runs the check in each// page hosting one, this one included, with the prompt shown at most once, and reports the result.- page().client().page_did_request_unload_check(id(), GC::create_function(heap(), [this, append_close_steps = move(append_close_steps)](CheckIfUnloadingIsCanceledResult result) {+ page().client().page_did_request_unload_check(id(), GC::create_function(heap(), GC::captures(*this, append_close_steps), [](auto& self, auto& append_close_steps, CheckIfUnloadingIsCanceledResult result) {if (result != CheckIfUnloadingIsCanceledResult::Continue) {// AD-HOC: Allow a later close attempt if this one was canceled.- if (!m_close_steps_have_been_appended)- set_closing(false);+ if (!self.m_close_steps_have_been_appended)+ self.set_closing(false);return;}// 3. Append the following session history traversal steps to traversable:- append_close_steps();+ append_close_steps->function()();}));}@@ -309,19 +309,19 @@ void LocalTraversableNavigable::run_ui_traversable_close_unload_task(){// The UI process has already unloaded every descendant subtree.queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr,- GC::create_function(heap(), [this] {+ GC::create_function(heap(), GC::captures(*this), [](auto& self) {// NB: The UI process discards the page of a tab it let go of without waiting for this task, and the page// goes without the unload then. A tab can also go while this task is queued.- if (page().has_been_discarded() || has_been_destroyed())+ if (self.page().has_been_discarded() || self.has_been_destroyed())return;// 2. Unload document, passing along newDocument if it is not null.- if (auto document = active_document())+ if (auto document = self.active_document())document->unload();// 3. If afterAllUnloads was given, then run it.// NB: afterAllUnloads is the close traversal steps' algorithm step which destroys traversable.- destroy_top_level_traversable();+ self.destroy_top_level_traversable();}));}diff --git a/Libraries/LibWeb/HTML/MediaControls.cpp b/Libraries/LibWeb/HTML/MediaControls.cppindex 800bb47c5d9..6ac70ed12fa 100644--- a/Libraries/LibWeb/HTML/MediaControls.cpp+++ b/Libraries/LibWeb/HTML/MediaControls.cpp@@ -6,6 +6,8 @@#include <AK/NumberFormat.h>#include <AK/Utf16StringBuilder.h>+#include <AK/WeakPtr.h>+#include <LibGC/Function.h>#include <LibGC/Heap.h>#include <LibJS/Runtime/NativeFunction.h>#include <LibWeb/CSS/CSSStyleProperties.h>@@ -107,16 +109,26 @@ void MediaControls::create_shadow_tree()template<typename T, CallableAs<bool, T&> Handler>GC::Ref<DOM::IDLEventListener> MediaControls::add_event_listener(JS::Realm& realm, DOM::EventTarget& target, Utf16FlyString const& event_name, ListenOnce listen_once, Handler handler){+ // NB: A handler uses these controls, which remove their listeners when they go away. It holds no strong pointer to+ // a cell, as nothing traces it.+ struct HandlerHolder : RefCounted<HandlerHolder> {+ explicit HandlerHolder(Handler handler)+ : handler(move(handler))+ {+ }++ Handler handler;+ };auto callback_function = JS::NativeFunction::create(- realm, [handler = move(handler)](JS::VM& vm) {+ realm, GC::create_function(GC::Heap::the(), GC::captures(make_ref_counted<HandlerHolder>(move(handler))), [](NonnullRefPtr<HandlerHolder>& holder, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {if (auto* event = Bindings::event_from_callback_argument(vm)) {if (auto* typed_event = as_if<T>(*event)) {- if (handler(*typed_event))+ if (holder->handler(*typed_event))typed_event->prevent_default();}}return JS::js_undefined();- },+ }),0, Utf16FlyString {}, &realm);auto callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*callback_function, realm);auto listener = DOM::IDLEventListener::create(callback);@@ -311,7 +323,7 @@ void MediaControls::set_up_event_listeners()return true;});- add_event_listener(realm, window, UIEvents::EventNames::mouseup, ListenOnce::Yes, [this, mousemove_listener](UIEvents::MouseEvent const& event) {+ add_event_listener(realm, window, UIEvents::EventNames::mouseup, ListenOnce::Yes, [this, mousemove_listener = GC::Weak<DOM::IDLEventListener> { mousemove_listener }](UIEvents::MouseEvent const& event) {VERIFY(m_media_element);VERIFY(m_dom->timeline_element);@@ -329,7 +341,8 @@ void MediaControls::set_up_event_listeners()update_play_pause_icon();auto& window_inner = relevant_window(*m_host);- window_inner.remove_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);+ if (mousemove_listener)+ window_inner.remove_event_listener_without_options(UIEvents::EventNames::mousemove, *mousemove_listener);return true;});@@ -378,7 +391,7 @@ void MediaControls::set_up_event_listeners()return true;});- add_event_listener(realm, window, UIEvents::EventNames::mouseup, ListenOnce::Yes, [this, mousemove_listener](UIEvents::MouseEvent const& event) {+ add_event_listener(realm, window, UIEvents::EventNames::mouseup, ListenOnce::Yes, [this, mousemove_listener = GC::Weak<DOM::IDLEventListener> { mousemove_listener }](UIEvents::MouseEvent const& event) {VERIFY(m_media_element);VERIFY(m_dom->volume_element);@@ -389,7 +402,8 @@ void MediaControls::set_up_event_listeners()set_volume(*volume);auto& window_inner = relevant_window(*m_host);- window_inner.remove_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);+ if (mousemove_listener)+ window_inner.remove_event_listener_without_options(UIEvents::EventNames::mousemove, *mousemove_listener);return true;});@@ -686,11 +700,14 @@ void MediaControls::request_timeline_update()auto& realm = HTML::relevant_realm(*m_host);auto& window = relevant_window(realm.global_object());m_animation_frame_window = window;- m_request_animation_frame_id = window.request_animation_frame([this](double) {- m_request_animation_frame_id = 0;- update_timeline();- request_timeline_update();- });+ m_request_animation_frame_id = window.request_animation_frame(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](WeakPtr<MediaControls>& weak_self, double) {+ auto* self = weak_self.ptr();+ if (!self)+ return;+ self->m_request_animation_frame_id = 0;+ self->update_timeline();+ self->request_timeline_update();+ }));}// A time as minutes and seconds, such as 4:10, with the hours before them when there are any.diff --git a/Libraries/LibWeb/HTML/MediaControls.h b/Libraries/LibWeb/HTML/MediaControls.hindex c87cb134a29..29e2da4a63e 100644--- a/Libraries/LibWeb/HTML/MediaControls.h+++ b/Libraries/LibWeb/HTML/MediaControls.h@@ -9,6 +9,7 @@#include <AK/Optional.h>#include <AK/Utf16FlyString.h>#include <AK/Vector.h>+#include <AK/Weakable.h>#include <LibCore/Timer.h>#include <LibGC/Cell.h>#include <LibGC/Weak.h>@@ -19,7 +20,7 @@ namespace Web::HTML {class HTMLMediaElement;-class MediaControls {+class MediaControls : public Weakable<MediaControls> {public:MediaControls(HTMLMediaElement& host, HTMLMediaElement& media_element);~MediaControls();diff --git a/Libraries/LibWeb/HTML/NavigableContainer.cpp b/Libraries/LibWeb/HTML/NavigableContainer.cppindex 5ec2b43d3fa..dd56dc513fd 100644--- a/Libraries/LibWeb/HTML/NavigableContainer.cpp+++ b/Libraries/LibWeb/HTML/NavigableContainer.cpp@@ -134,11 +134,11 @@ void NavigableContainer::create_new_child_navigable(){.local_target_navigable_id = navigable->id(),.local_target_entry = history_entry,- .on_complete = GC::create_function(heap(), [this, navigable] {- if (navigable->has_been_destroyed() || content_navigable() != navigable)+ .on_complete = GC::create_function(heap(), GC::captures(*this, navigable), [](auto& self, auto& navigable) {+ if (navigable->has_been_destroyed() || self.content_navigable() != navigable)return;navigable->set_has_session_history_entry_and_ready_for_navigation();- this->document().schedule_html_parser_end_check();+ self.document().schedule_html_parser_end_check();}),});}@@ -375,7 +375,7 @@ void NavigableContainer::continue_destroying_the_child_navigable(Navigable& navi{// 6. Queue a global task on the navigation and traversal task source given document's relevant global object to// perform the following steps:- queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr, GC::create_function(navigable.heap(), [navigable = GC::Ref { navigable }] {+ queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr, GC::create_function(navigable.heap(), GC::captures(GC::Ref { navigable }), [](auto& navigable) {// 1. If firePageSwapSteps is given, then run firePageSwapSteps.// 2. Unload document, passing along newDocument if it is not null.// NB: The document of a navigable hosted by another process was unloaded there by the UI process.@@ -470,15 +470,15 @@ void NavigableContainer::content_navigable_completely_finished_loading()// NB: container is this element.// 4. If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container.if (is<HTMLIFrameElement>(*this)) {- queue_an_element_task(Task::Source::DOMManipulation, [this] {- run_iframe_load_event_steps(static_cast<HTMLIFrameElement&>(*this));- });+ queue_an_element_task(Task::Source::DOMManipulation, GC::create_function(heap(), GC::captures(*this), [](NavigableContainer& self) {+ run_iframe_load_event_steps(static_cast<HTMLIFrameElement&>(self));+ }));}// 5. Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container.else {- queue_an_element_task(Task::Source::DOMManipulation, [this] {- dispatch_event(DOM::Event::create(EventNames::load, HighResolutionTime::current_high_resolution_time(relevant_global_object(*this))));- });+ queue_an_element_task(Task::Source::DOMManipulation, GC::create_function(heap(), GC::captures(*this), [](NavigableContainer& self) {+ self.dispatch_event(DOM::Event::create(EventNames::load, HighResolutionTime::current_high_resolution_time(relevant_global_object(self))));+ }));}// AD-HOC: Finishing a child document can unblock its parent's load-event-delay phase, so wake the parent parser enddiff --git a/Libraries/LibWeb/HTML/Navigation.cpp b/Libraries/LibWeb/HTML/Navigation.cppindex 832f8b79ceb..e08e5201ad0 100644--- a/Libraries/LibWeb/HTML/Navigation.cpp+++ b/Libraries/LibWeb/HTML/Navigation.cpp@@ -690,30 +690,30 @@ WebIDL::ExceptionOr<NavigationResult> Navigation::perform_a_navigation_api_trave// NOTE: The target-missing path is taken if navigation's entry list was outdated compared to navigableSHEs,// which can occur for brief periods while all the relevant threads and processes are being synchronized// in reaction to a history change.- auto on_rejected = GC::create_function(heap(), [this, api_method_tracker] {- queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(window()), GC::create_function(heap(), [this, api_method_tracker] {- auto& realm = relevant_realm(window());+ auto on_rejected = GC::create_function(heap(), GC::captures(*this, api_method_tracker), [](auto& self, auto& api_method_tracker) {+ queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(self.window()), GC::create_function(self.heap(), GC::captures(self, api_method_tracker), [](auto& self, auto& api_method_tracker) {+ auto& realm = relevant_realm(self.window());TemporaryExecutionContext execution_context { realm };- reject_the_finished_promise(api_method_tracker,+ self.reject_the_finished_promise(api_method_tracker,WebIDL::InvalidStateError::create(realm, "Cannot traverse with stale session history entry"_utf16));}));});- auto on_apply_history_step_complete = GC::create_function(heap(), [this, api_method_tracker](HistoryStepResult result) {+ auto on_apply_history_step_complete = GC::create_function<void(HistoryStepResult)>(heap(), GC::captures(*this, api_method_tracker), [](auto& self, auto& api_method_tracker, HistoryStepResult result) {// NOTE: When result is "canceled-by-beforeunload" or "initiator-disallowed", the navigate event was never fired,// aborting the ongoing navigation would not be correct; it would result in a navigateerror event without a// preceding navigate event. In the "canceled-by-navigate" case, navigate is fired, but the inner navigate event// firing algorithm will take care of aborting the ongoing navigation.- auto& realm = relevant_realm(window());- auto& global = relevant_global_object(window());+ auto& realm = relevant_realm(self.window());+ auto& global = relevant_global_object(self.window());// 5. If result is "canceled-by-beforeunload", then queue a global task on the navigation and traversal task source// given navigation's relevant global object to reject the finished promise for apiMethodTracker with a// new "AbortError" DOMException created in navigation's relevant realm.if (result == HistoryStepResult::CanceledByBeforeUnload) {- queue_global_task(Task::Source::NavigationAndTraversal, global, GC::create_function(heap(), [this, api_method_tracker, &realm] {+ queue_global_task(Task::Source::NavigationAndTraversal, global, GC::create_function(self.heap(), GC::captures(self, api_method_tracker, realm), [](auto& self, auto& api_method_tracker, auto& realm) {TemporaryExecutionContext execution_context { realm };- reject_the_finished_promise(api_method_tracker, WebIDL::AbortError::create(realm, "Navigation cancelled by beforeunload"_utf16));+ self.reject_the_finished_promise(api_method_tracker, WebIDL::AbortError::create(realm, "Navigation cancelled by beforeunload"_utf16));}));}@@ -721,9 +721,9 @@ WebIDL::ExceptionOr<NavigationResult> Navigation::perform_a_navigation_api_trave// given navigation's relevant global object to reject the finished promise for apiMethodTracker with a// new "SecurityError" DOMException created in navigation's relevant realm.if (result == HistoryStepResult::InitiatorDisallowed) {- queue_global_task(Task::Source::NavigationAndTraversal, global, GC::create_function(heap(), [this, api_method_tracker, &realm] {+ queue_global_task(Task::Source::NavigationAndTraversal, global, GC::create_function(self.heap(), GC::captures(self, api_method_tracker, realm), [](auto& self, auto& api_method_tracker, auto& realm) {TemporaryExecutionContext execution_context { realm };- reject_the_finished_promise(api_method_tracker, WebIDL::SecurityError::create(realm, "Navigation disallowed from this origin"_utf16));+ self.reject_the_finished_promise(api_method_tracker, WebIDL::SecurityError::create(realm, "Navigation disallowed from this origin"_utf16));}));}});@@ -953,7 +953,7 @@ void Navigation::run_the_navigate_event_intercept_commit_handler_steps(GC::Ref<N// 4. Wait for all of promisesList, with the following success steps:WebIDL::wait_for_all(- realm, promises_list, [event, this, api_method_tracker](auto const&) -> void {+ realm, promises_list, GC::create_function(GC::Heap::the(), GC::captures(event, *this, api_method_tracker), [](auto& event, auto& self, auto& api_method_tracker, Vector<JS::Value> const&) {// 1. If event's relevant global object is not fully active, then abort these steps.auto& window = event->relevant_window();if (!window.associated_document().is_fully_active())@@ -964,37 +964,37 @@ void Navigation::run_the_navigate_event_intercept_commit_handler_steps(GC::Ref<Nreturn;// 3. Assert: event equals navigation's ongoing navigate event.- VERIFY(event == m_ongoing_navigate_event);+ VERIFY(event == self.m_ongoing_navigate_event);// 4. Set navigation's ongoing navigate event to null.- m_ongoing_navigate_event = nullptr;+ self.m_ongoing_navigate_event = nullptr;// 6. If apiMethodTracker is non-null, then resolve the finished promise for apiMethodTracker.// AD-HOC: This runs before finishing the event, since resetting the focus can start a new navigation// from a blur handler, and its inner navigate event firing algorithm asserts that no API method// tracker is ongoing.if (api_method_tracker != nullptr)- resolve_the_finished_promise(*api_method_tracker);+ self.resolve_the_finished_promise(*api_method_tracker);// 5. Finish event given true.event->finish(true);// FIXME: Implement https://dom.spec.whatwg.org/#concept-event-fire somewhere// 7. Fire an event named navigatesuccess at navigation.- dispatch_event(DOM::Event::create(+ self.dispatch_event(DOM::Event::create(EventNames::navigatesuccess,HighResolutionTime::current_high_resolution_time(relevant_global_object(window))));// 8. If navigation's transition is not null, then resolve navigation's transition's finished promise with undefined.- if (m_transition != nullptr)- WebIDL::resolve_promise(m_transition->finished());+ if (self.m_transition != nullptr)+ WebIDL::resolve_promise(self.m_transition->finished());// 9. Set navigation's transition to null.- m_transition = nullptr; },+ self.m_transition = nullptr; }),// and the following failure step given reason: process navigate event handler failure given event and reason.- [event, this](JS::Value reason) -> void {- process_navigate_event_handler_failure(event, reason);- });+ GC::create_function(GC::Heap::the(), GC::captures(event, *this), [](auto& event, auto& self, JS::Value reason) {+ self.process_navigate_event_handler_failure(event, reason);+ }));}// https://html.spec.whatwg.org/multipage/nav-history-apis.html#process-navigate-event-handler-failure@@ -1294,12 +1294,12 @@ bool Navigation::inner_navigate_event_firing_algorithm(// reason.WebIDL::wait_for_all(realm, precommit_promises_list,- [this, event, api_method_tracker](auto const&) {- commit_a_navigate_event(event, api_method_tracker);- },- [this, event](JS::Value reason) {- process_navigate_event_handler_failure(event, reason);- });+ GC::create_function(GC::Heap::the(), GC::captures(*this, event, api_method_tracker), [](auto& self, auto& event, auto& api_method_tracker, Vector<JS::Value> const&) {+ self.commit_a_navigate_event(event, api_method_tracker);+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this, event), [](auto& self, auto& event, JS::Value reason) {+ self.process_navigate_event_handler_failure(event, reason);+ }));}// 32. If event's interception state is "none", then return true.diff --git a/Libraries/LibWeb/HTML/NavigationObserver.cpp b/Libraries/LibWeb/HTML/NavigationObserver.cppindex f69f24c4d37..a397147f202 100644--- a/Libraries/LibWeb/HTML/NavigationObserver.cpp+++ b/Libraries/LibWeb/HTML/NavigationObserver.cpp@@ -37,20 +37,14 @@ void NavigationObserver::finalize()m_navigable->unregister_navigation_observer({}, *this);}-void NavigationObserver::set_navigation_complete(Function<void()> callback)+void NavigationObserver::set_navigation_complete(GC::Ptr<GC::Function<void()>> callback){- if (callback)- m_navigation_complete = GC::create_function(GC::Heap::the(), move(callback));- else- m_navigation_complete = nullptr;+ m_navigation_complete = callback;}-void NavigationObserver::set_ongoing_navigation_changed(Function<void()> callback)+void NavigationObserver::set_ongoing_navigation_changed(GC::Ptr<GC::Function<void()>> callback){- if (callback)- m_ongoing_navigation_changed = GC::create_function(GC::Heap::the(), move(callback));- else- m_ongoing_navigation_changed = nullptr;+ m_ongoing_navigation_changed = callback;}}diff --git a/Libraries/LibWeb/HTML/NavigationObserver.h b/Libraries/LibWeb/HTML/NavigationObserver.hindex 05654c122d1..a039153c172 100644--- a/Libraries/LibWeb/HTML/NavigationObserver.h+++ b/Libraries/LibWeb/HTML/NavigationObserver.h@@ -23,10 +23,10 @@ public:[[nodiscard]] static GC::Ref<NavigationObserver> create(LocalNavigable&);[[nodiscard]] GC::Ptr<GC::Function<void()>> navigation_complete() const { return m_navigation_complete; }- void set_navigation_complete(Function<void()>);+ void set_navigation_complete(GC::Ptr<GC::Function<void()>>);[[nodiscard]] GC::Ptr<GC::Function<void()>> ongoing_navigation_changed() const { return m_ongoing_navigation_changed; }- void set_ongoing_navigation_changed(Function<void()>);+ void set_ongoing_navigation_changed(GC::Ptr<GC::Function<void()>>);private:explicit NavigationObserver(LocalNavigable&);diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cppindex 5868e528d0f..9ecd788ac8e 100644--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp@@ -220,11 +220,11 @@ void create_navigation_params_descriptor(JS::Realm& realm, NavigationParamsVariabody->fully_read(realm,- GC::create_function(realm.heap(), [descriptor = move(descriptor), completion_steps](ByteBuffer bytes) mutable {+ GC::create_function(realm.heap(), GC::captures(move(descriptor), completion_steps), [](auto& descriptor, auto& completion_steps, ByteBuffer bytes) {descriptor.response.body = move(bytes);completion_steps->function()(move(descriptor));}),- GC::create_function(realm.heap(), [completion_steps](JS::Value) {+ GC::create_function(realm.heap(), GC::captures(completion_steps), [](auto& completion_steps, JS::Value) {completion_steps->function()(NavigationParamsNullOrError { "Unable to transfer response body"_utf16 });}),GC::Ref { realm.global_object() });@@ -251,17 +251,17 @@ static RefPtr<Fetch::Infrastructure::Request> create_navigation_request_from_des}// Reports the WebDriver BiDi event that ends an adopted navigation response, unless a download has taken it over.-static Function<void(Optional<StringView>)> network_navigation_response_observer(LocalNavigable& navigable, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Optional<JsonObject> network_response, RefPtr<NavigationResponseNetworkEventState> network_response_state)+static GC::Ref<GC::Function<void(Optional<StringView>)>> network_navigation_response_observer(LocalNavigable& navigable, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Optional<JsonObject> network_response, RefPtr<NavigationResponseNetworkEventState> network_response_state){auto observed_navigable = network_response.has_value() ? GC::Weak<LocalNavigable> { navigable } : GC::Weak<LocalNavigable> {};// NB: Observing its navigable must not keep the navigable alive.- return [response = NonnullRefPtr { response }, observed_navigable = move(observed_navigable), timing_info = move(timing_info), network_response = move(network_response), network_response_state = move(network_response_state)](Optional<StringView> error) {+ return GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { response }, move(observed_navigable), move(timing_info), move(network_response), move(network_response_state)), [](auto& response, auto& observed_navigable, auto& timing_info, auto& network_response, auto& network_response_state, Optional<StringView> error) {if (!network_response.has_value() || !observed_navigable || network_response_state->owner != NavigationResponseNetworkEventState::Owner::Renderer)return;network_response_state->owner = NavigationResponseNetworkEventState::Owner::Completed;WebDriver::BiDi::network_navigation_response_finished(*observed_navigable, *network_response, *response, timing_info, error);- };+ });}static ErrorOr<GC::Ref<Fetch::Infrastructure::ResponseView>> create_navigation_response_from_descriptor(JS::Realm& realm, LocalNavigable& navigable, NavigationResponseDescriptor descriptor, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, RefPtr<NavigationResponseNetworkEventState> network_response_state)@@ -283,7 +283,7 @@ static ErrorOr<GC::Ref<Fetch::Infrastructure::ResponseView>> create_navigation_rRequests::RequestTransferLeaseKey transfer_lease { handle.request_server_client_id, handle.request_server_request_id };auto network_response = descriptor.webdriver_bidi_network_response.is_object() ? Optional<JsonObject>(descriptor.webdriver_bidi_network_response.as_object()) : Optional<JsonObject> {};auto on_network_settled = network_navigation_response_observer(navigable, response, timing_info, move(network_response), move(network_response_state));- auto body_view = Fetch::Fetching::adopt_navigation_response_body(realm, response, handle.request_server_top_level_site, transfer_lease, timing_info, move(on_network_settled));+ auto body_view = Fetch::Fetching::adopt_navigation_response_body(realm, response, handle.request_server_top_level_site, transfer_lease, timing_info, on_network_settled);if (!body_view)return Error::from_string_literal("Unable to adopt transferred navigation response body");return Fetch::Infrastructure::ResponseView::create(response, body_view);diff --git a/Libraries/LibWeb/HTML/Navigator.cpp b/Libraries/LibWeb/HTML/Navigator.cppindex 7c6f3456fc0..700b140c499 100644--- a/Libraries/LibWeb/HTML/Navigator.cpp+++ b/Libraries/LibWeb/HTML/Navigator.cpp@@ -225,7 +225,7 @@ void Navigator::request_media_key_system_access(Utf16String key_system, Vector<E// 7. Run the following steps in parallel:auto& realm = WebIDL::promise_realm(promise);- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, key_system, supported_configurations = move(supported_configurations), origin, promise]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, key_system, move(supported_configurations), origin, promise), [](auto& realm, auto& key_system, auto& supported_configurations, auto& origin, auto& promise) {TemporaryExecutionContext context(realm, TemporaryExecutionContext::CallbacksEnabled::Yes);// 1. If keySystem is not one of the Key Systems supported by the user agent, reject promise with a NotSupportedError. String comparison is case-sensitive.diff --git a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp b/Libraries/LibWeb/HTML/OffscreenCanvas.cppindex 4b19a3d7660..f46de74b55e 100644--- a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp+++ b/Libraries/LibWeb/HTML/OffscreenCanvas.cpp@@ -420,7 +420,7 @@ GC::Ref<WebIDL::Promise> convert_to_blob(JS::Realm& realm, HTML::OffscreenCanvasauto& global = offscreen_canvas.relevant_global_object();// 7. Run these steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [realm = GC::Ref(realm), &global, result_promise, bitmap, image_encode_options] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(realm), global, result_promise, bitmap, image_encode_options), [](auto& realm, auto& global, auto& result_promise, auto& bitmap, auto& image_encode_options) {// 1. Let file be a serialization of bitmap as a file, with options's type and quality if present.Optional<HTML::SerializeBitmapResult> file_result {};@@ -430,7 +430,7 @@ GC::Ref<WebIDL::Promise> convert_to_blob(JS::Realm& realm, HTML::OffscreenCanvas}// 2. Queue a global task on the canvas blob serialization task source given global to run these steps:- HTML::queue_global_task(HTML::Task::Source::CanvasBlobSerializationTask, global, GC::create_function(GC::Heap::the(), [realm, result_promise, file_result = move(file_result)] -> void {+ HTML::queue_global_task(HTML::Task::Source::CanvasBlobSerializationTask, global, GC::create_function(GC::Heap::the(), GC::captures(realm, result_promise, move(file_result)), [](auto& realm, auto& result_promise, auto& file_result) -> void {HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// 1. If file is null, then reject result with an "EncodingError" DOMException.diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cppindex ce8c02413dc..97d95148ca6 100644--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp@@ -734,9 +734,9 @@ HTMLParserEndState::HTMLParserEndState(GC::Ref<DOM::Document> document, GC::Ptr<: m_document(document), m_parser(parser), m_parser_generation(parser_generation)- , m_timeout(Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(THE_END_TIMEOUT_MS), GC::create_function(GC::Heap::the(), [this] {- if (m_phase != Phase::Completed && m_phase != Phase::Cancelled)- dbgln("HTMLParserEndState: timed out in phase {}", to_underlying(m_phase));+ , m_timeout(Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(THE_END_TIMEOUT_MS), GC::create_function(GC::Heap::the(), GC::captures(*this), [](HTMLParserEndState& self) {+ if (self.m_phase != Phase::Completed && self.m_phase != Phase::Cancelled)+ dbgln("HTMLParserEndState: timed out in phase {}", to_underlying(self.m_phase));}))){m_timeout->start();@@ -763,11 +763,11 @@ void HTMLParserEndState::schedule_progress_check()if (m_check_pending)return;m_check_pending = true;- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this] {- auto scope_guard = SVG::ScopedSVGImageDocument::create_if_needed(m_document, SVG::ScopedSVGImageDocument::FrameRequests::Suppress);+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this), [](HTMLParserEndState& self) {+ auto scope_guard = SVG::ScopedSVGImageDocument::create_if_needed(self.m_document, SVG::ScopedSVGImageDocument::FrameRequests::Suppress);perform_pre_progress_microtask_checkpoint();- check_progress();- m_check_pending = false;+ self.check_progress();+ self.m_check_pending = false;}));}@@ -888,7 +888,7 @@ void HTMLParserEndState::advance_to_dom_content_loaded_phase()m_phase = Phase::WaitingForDOMContentLoaded;// 6. Queue a global task on the DOM manipulation task source given the Document's relevant global object to run the following substeps:- queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(*m_document), GC::create_function(GC::Heap::the(), [state = GC::Ref(*this), document = m_document] {+ queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(*m_document), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_document), [](auto& state, auto& document) {if (state->m_phase != Phase::WaitingForDOMContentLoaded)return;// 1. Set the Document's load timing info's DOM content loaded event start time to the current high resolution time given the Document's relevant global object.@@ -945,7 +945,7 @@ void HTMLParserEndState::complete()m_phase = Phase::Completed;// 9. Queue a global task on the DOM manipulation task source given the Document's relevant global object to run the following steps:- queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(*m_document), GC::create_function(GC::Heap::the(), [state = GC::Ref(*this), document = m_document, parser = m_parser, parser_generation = m_parser_generation] {+ queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(*m_document), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_document, m_parser, m_parser_generation), [](auto& state, auto& document, auto& parser, auto& parser_generation) {if (state->m_phase != Phase::Completed)return;// document.open() can replace the parser after this completion task@@ -1267,10 +1267,10 @@ void HTMLParser::schedule_resume_check()if (!m_parser_pause_flag)return;m_resume_check_pending = true;- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this] {- m_resume_check_pending = false;+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this), [](HTMLParser& self) {+ self.m_resume_check_pending = false;perform_pre_progress_microtask_checkpoint();- resume_after_parser_blocking_script();+ self.resume_after_parser_blocking_script();}));}diff --git a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cppindex 0cc0c0f7db6..8d928fe0535 100644--- a/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/IncrementalDocumentParser.cpp@@ -64,7 +64,7 @@ void IncrementalDocumentParser::start()// FIXME: The spec allows starting the parse after 500 ms or 1024 bytes, whichever comes first.// We only honor the byte threshold.auto parser = GC::Ref { *this };- m_body->wait_for_sniff_bytes(GC::create_function(GC::Heap::the(), [parser](Web::Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {+ m_body->wait_for_sniff_bytes(GC::create_function(GC::Heap::the(), GC::captures(parser), [](auto& parser, Web::Fetch::Infrastructure::Body::SniffBytes sniff_bytes) {// A failed response initializes the parser too.parser->initialize_parser(sniff_bytes.bytes);}));@@ -87,19 +87,19 @@ void IncrementalDocumentParser::initialize_parser(ReadonlyBytes sniff_bytes)// The parser exists while the prescan runs, so that aborting the document aborts it. Its encoding confidence is// set along with its encoding.m_parser = HTMLParser::create_with_open_input_stream(m_document, EncodingConfidence::Tentative);- m_parser->set_change_encoding_callback(GC::create_function(GC::Heap::the(), [this](StringView encoding) {- auto result = change_encoding(encoding);+ m_parser->set_change_encoding_callback(GC::create_function(GC::Heap::the(), GC::captures(*this), [](IncrementalDocumentParser& self, StringView encoding) {+ auto result = self.change_encoding(encoding);if (result.is_error()) {- release_encoding_change_buffers();+ self.release_encoding_change_buffers();return false;}return result.release_value();}));- m_parser->set_parsing_complete_callback(GC::create_function(GC::Heap::the(), [this]() {- release_encoding_change_buffers();+ m_parser->set_parsing_complete_callback(GC::create_function(GC::Heap::the(), GC::captures(*this), [](IncrementalDocumentParser& self) {+ self.release_encoding_change_buffers();}));- m_parser->set_ready_for_more_input_callback(GC::create_function(GC::Heap::the(), [this]() {- feed_parser();+ m_parser->set_ready_for_more_input_callback(GC::create_function(GC::Heap::the(), GC::captures(*this), [](IncrementalDocumentParser& self) {+ self.feed_parser();}));m_parser->set_allow_declarative_shadow_roots(m_allow_declarative_shadow_roots);@@ -157,13 +157,13 @@ void IncrementalDocumentParser::start_incremental_read()auto parser = GC::Ref { *this };m_body->incrementally_read(m_document->relevant_settings_object().realm(),- GC::create_function(GC::Heap::the(), [parser](ByteBuffer bytes) mutable {+ GC::create_function(GC::Heap::the(), GC::captures(parser), [](auto& parser, ByteBuffer bytes) {parser->process_body_chunk(move(bytes));}),- GC::create_function(GC::Heap::the(), [parser] {+ GC::create_function(GC::Heap::the(), GC::captures(parser), [](auto& parser) {parser->process_end_of_body();}),- GC::create_function(GC::Heap::the(), [parser](JS::Value error) {+ GC::create_function(GC::Heap::the(), GC::captures(parser), [](auto& parser, JS::Value error) {parser->process_body_error(error);}),GC::Ref { m_document->relevant_settings_object().realm().global_object() });@@ -258,7 +258,7 @@ void IncrementalDocumentParser::queue_task_to_feed_parser()return;++m_times_yielded_to_event_loop;m_has_queued_task_to_feed_parser = true;- queue_global_task(Task::Source::Networking, m_document->relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), [parser = GC::Ref { *this }] {+ queue_global_task(Task::Source::Networking, m_document->relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }), [](auto& parser) {parser->m_has_queued_task_to_feed_parser = false;parser->feed_parser();}));@@ -465,7 +465,7 @@ void IncrementalDocumentParser::register_deferred_start()return;auto parser = GC::Ref { *this };- m_document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), [parser] {+ m_document->set_deferred_parser_start(GC::create_function(GC::Heap::the(), GC::captures(parser), [](auto& parser) {parser->pump();// The tokenizer can consume input again, so hand over any bytes withheld while it could not.diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cppindex 854f97abf4d..e024ec4b2a0 100644--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp@@ -145,7 +145,7 @@ void issue_speculative_fetch(JS::Realm& realm, DOM::Document& document, URL::URL// speculative fetch succeeds, offer its response to the normal parser's fetch the way a preload is, through// the document's map of preloaded resources. That fetch still runs main fetch's checks before using it.Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = [document = GC::Ref { document }, parser = GC::Weak { document.active_parser() }, request](GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { document }, GC::Weak { document.active_parser() }, request), [](GC::Ref<DOM::Document>& document, GC::Weak<HTMLParser>& parser, NonnullRefPtr<Fetch::Infrastructure::Request>& request, GC::Ref<Fetch::Infrastructure::ResponseView> response_view, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {auto response = response_view->record();auto* byte_sequence = body_bytes.get_pointer<Core::ImmutableBytes>();if (response->is_network_error() || !byte_sequence)@@ -180,7 +180,7 @@ void issue_speculative_fetch(JS::Realm& realm, DOM::Document& document, URL::URLentry->response = move(preloaded_response);entry->is_speculative = true;document->map_of_preloaded_resources().set(key, entry);- };+ });// The fetch stays alive via ResourceLoader's GC::Root callbacks for the duration of the// network request, so we don't need to retain the FetchController.diff --git a/Libraries/LibWeb/HTML/PreloadEntry.h b/Libraries/LibWeb/HTML/PreloadEntry.hindex e73a7d51a1c..5b87a40f731 100644--- a/Libraries/LibWeb/HTML/PreloadEntry.h+++ b/Libraries/LibWeb/HTML/PreloadEntry.h@@ -9,6 +9,7 @@#include <AK/HashMap.h>#include <AK/Utf16String.h>#include <AK/Utf16View.h>+#include <LibGC/Forward.h>#include <LibGC/Function.h>#include <LibGC/Ptr.h>#include <LibJS/Heap/Cell.h>@@ -116,3 +117,5 @@ struct Traits<Web::HTML::PreloadKey> : public DefaultTraits<Web::HTML::PreloadKe};}++GC_UNTRACED_CAPTURE(Web::HTML::PreloadKey);diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cppindex 29cf47851e9..e3efaf97a00 100644--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp@@ -6,6 +6,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/RefCounted.h>#include <AK/Utf16String.h>#include <LibCore/EventLoop.h>#include <LibCore/ImmutableBytes.h>@@ -23,7 +24,6 @@#include <LibWeb/DOMURL/DOMURL.h>#include <LibWeb/Fetch/Fetching/ClientContextSnapshots.h>#include <LibWeb/Fetch/Fetching/Fetching.h>-#include <LibWeb/Fetch/Fetching/RefCountedFlag.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>@@ -53,6 +53,13 @@ struct OffThreadCompiledProgram {JS::CompiledProgram compiled {};};+}++// NB: A parsed or compiled program is held outside of the GC heap.+GC_UNTRACED_CAPTURE(Web::HTML::OffThreadCompiledProgram);++namespace Web::HTML {+static ReadonlyBytes body_bytes_view(Fetch::Infrastructure::FetchAlgorithms::BodyBytes const& body_bytes){return body_bytes.get<Core::ImmutableBytes>().bytes();@@ -93,7 +100,7 @@ static Optional<CompiledScriptCacheKey> compiled_script_cache_key(Fetch::Infrast// code, which is thread-safe to share.// With a cache key, a program that the cache of compiled scripts has for the source code skips all of this, and// otherwise the program goes there before anything runs it.-static void compile_off_thread(EnvironmentSettingsObject& settings_object, NonnullRefPtr<JS::SourceCode const> source_code, JS::ProgramType type, size_t line_number_offset, Optional<CompiledScriptCacheKey> cache_key, Function<void(OffThreadCompiledProgram, NonnullRefPtr<JS::SourceCode const>)> on_compiled)+static void compile_off_thread(EnvironmentSettingsObject& settings_object, NonnullRefPtr<JS::SourceCode const> source_code, JS::ProgramType type, size_t line_number_offset, Optional<CompiledScriptCacheKey> cache_key, GC::Ref<GC::Function<void(OffThreadCompiledProgram, NonnullRefPtr<JS::SourceCode const>)>> on_compiled){// Take the code the parser needs while still on the main thread.auto source_text = source_code->code();@@ -104,12 +111,9 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Nonnu// The script runs in a task of the settings object's global, so never beside a rendering update in flight that holds// back the tasks of its document, and the microtasks it queues (e.g. promise reactions from react_to_promise during// module linking) are drained after it.- auto run_callback = [settings_object = GC::make_root(settings_object), on_compiled = move(on_compiled), source_code = move(source_code)](OffThreadCompiledProgram result) mutable {- queue_global_task(Task::Source::Networking, settings_object->global_object(), GC::create_function(GC::Heap::the(), [on_compiled = move(on_compiled), source_code = move(source_code), result = move(result)]() mutable {- // NB: The callback holds GC roots. Release them as the task runs: the roots of a function that died- // would keep what they root alive through the collection that finds it dead.- auto steps = move(on_compiled);- steps(move(result), move(source_code));+ auto run_callback = [settings_object = GC::make_root(settings_object), on_compiled = GC::make_root(on_compiled), source_code = move(source_code)](OffThreadCompiledProgram result) mutable {+ queue_global_task(Task::Source::Networking, settings_object->global_object(), GC::create_function(GC::Heap::the(), GC::captures(on_compiled, move(source_code), move(result)), [](auto& on_compiled, auto& source_code, auto& result) {+ on_compiled->function()(move(result), move(source_code));}));};@@ -146,16 +150,6 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, NonnuGC_DEFINE_ALLOCATOR(FetchContext);-OnFetchScriptComplete create_on_fetch_script_complete(GC::Heap& heap, Function<void(GC::Ptr<Script>)> function)-{- return GC::create_function(heap, move(function));-}--PerformTheFetchHook create_perform_the_fetch_hook(GC::Heap& heap, Function<WebIDL::ExceptionOr<void>(NonnullRefPtr<Fetch::Infrastructure::Request>, TopLevelModule, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction)> function)-{- return GC::create_function(heap, move(function));-}-ScriptFetchOptions default_script_fetch_options(){// The default script fetch options are a script fetch options whose cryptographic nonce is the empty string,@@ -454,7 +448,7 @@ void fetch_classic_script(JS::Realm& realm, URL::URL const& url, EnvironmentSett// NB: The script is created in several places below. They all hand it to onComplete, which is where we set its// fetch options to options.- on_complete = create_on_fetch_script_complete(GC::Heap::the(), [options, on_complete](GC::Ptr<Script> script) {+ on_complete = create_on_fetch_script_complete(GC::Heap::the(), GC::captures(options, on_complete), [](auto& options, auto& on_complete, GC::Ptr<Script> script) {if (script)script->set_fetch_options(options);on_complete->function()(script);@@ -463,7 +457,7 @@ void fetch_classic_script(JS::Realm& realm, URL::URL const& url, EnvironmentSett// 5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure,// or a byte sequence bodyBytes:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = [request, &settings_object, options = move(options), character_encoding = move(character_encoding), on_complete = move(on_complete)](auto response, auto body_bytes) {+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(request, settings_object, move(character_encoding), on_complete), [](NonnullRefPtr<Fetch::Infrastructure::Request>& request, EnvironmentSettingsObject& settings_object, Utf16String& character_encoding, OnFetchScriptComplete& on_complete, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {// NB: Whether response was CORS-cross-origin must be determined before unwrapping it, since the internal// response of an opaque filtered response is never CORS-cross-origin itself.auto response_was_cors_cross_origin = response->is_cors_cross_origin();@@ -502,8 +496,6 @@ void fetch_classic_script(JS::Realm& realm, URL::URL const& url, EnvironmentSett// options, and muted errors.auto response_url = response->url().value_or({});- auto on_complete_root = GC::make_root(on_complete);- auto settings_root = GC::make_root(settings_object);// NB: The filename is the request's URL. The response's URL could reveal where a cross-origin request was// redirected.auto filename = request->url().to_byte_string();@@ -512,15 +504,13 @@ void fetch_classic_script(JS::Realm& realm, URL::URL const& url, EnvironmentSettauto cache_key = compiled_script_cache_key(request, request->url(), response->status(), response->header_list(), JS::ProgramType::Script, 1);compile_off_thread(settings_object, move(source_code), JS::ProgramType::Script, 1, move(cache_key),- [response_url = move(response_url), filename = move(filename),- muted_errors, on_complete_root = move(on_complete_root),- settings_root = move(settings_root)](auto result, auto source_code) mutable {+ GC::create_function(GC::Heap::the(), GC::captures(move(response_url), move(filename), muted_errors, on_complete, settings_object), [](URL::URL& response_url, ByteString& filename, ClassicScript::MutedErrors muted_errors, OnFetchScriptComplete& on_complete, EnvironmentSettingsObject& settings_object, OffThreadCompiledProgram result, NonnullRefPtr<JS::SourceCode const> source_code) {auto script = result.compiled- ? ClassicScript::create_from_pre_compiled(move(filename), source_code, *settings_root, move(response_url), move(result.compiled), muted_errors)- : ClassicScript::create_from_pre_parsed(move(filename), source_code, *settings_root, move(response_url), move(result.parsed), muted_errors);- on_complete_root->function()(script);- });- };+ ? ClassicScript::create_from_pre_compiled(move(filename), source_code, settings_object, move(response_url), move(result.compiled), muted_errors)+ : ClassicScript::create_from_pre_parsed(move(filename), source_code, settings_object, move(response_url), move(result.parsed), muted_errors);+ on_complete->function()(script);+ }));+ });Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}@@ -542,7 +532,7 @@ WebIDL::ExceptionOr<void> fetch_classic_worker_script(URL::URL const& url, Fetchrequest->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);request->set_use_url_credentials(true);- auto process_response_consume_body = [&settings_object, on_complete = move(on_complete)](auto response, auto body_bytes) {+ auto process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(settings_object, on_complete), [](EnvironmentSettingsObject& settings_object, OnFetchScriptComplete& on_complete, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {// 1. Set response to response's unsafe response.response = response->unsafe_response();@@ -582,32 +572,39 @@ WebIDL::ExceptionOr<void> fetch_classic_worker_script(URL::URL const& url, Fetch// 6. Run onComplete given script.on_complete->function()(script);- };+ });// 2. If performFetch was given, run performFetch with request, true, and with processResponseConsumeBody as defined below.if (perform_fetch != nullptr) {- TRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));+ TRY(perform_fetch->function()(request, TopLevelModule::Yes, process_response_consume_body));}// Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.else {Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);+ fetch_algorithms_input.process_response_consume_body = process_response_consume_body;Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}return {};}+// NB: The response and body bytes of a classic worker imported script's fetch, which its processResponseConsumeBody+// sets while the fetching algorithm pauses.+struct ImportedScriptResponseHolder : RefCounted<ImportedScriptResponseHolder> {+ void visit_edges(GC::Cell::Visitor& visitor) const { visitor.visit(response); }++ GC::Ptr<Fetch::Infrastructure::ResponseView> response;+ Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes;+};+// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-worker-imported-scriptWebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_script(URL::URL const& url, HTML::EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch){auto& realm = settings_object.realm();// 1. Let response be null.- IGNORE_USE_IN_ESCAPING_LAMBDA GC::Ptr<Fetch::Infrastructure::ResponseView> response = nullptr;-// 2. Let bodyBytes be null.- Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes;+ auto holder = make_ref_counted<ImportedScriptResponseHolder>();// 3. Let request be a new request whose URL is url, client is settingsObject, destination is "script", initiator type is "other",// parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.@@ -619,35 +616,30 @@ WebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_scrirequest->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);request->set_use_url_credentials(true);- auto is_abandoned = Fetch::Fetching::RefCountedFlag::create(false);- auto process_response_consume_body = [&response, &body_bytes, is_abandoned](GC::Ref<Fetch::Infrastructure::ResponseView> res, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bb) {- if (is_abandoned->value())- return;-+ auto process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(holder), [](NonnullRefPtr<ImportedScriptResponseHolder>& holder, GC::Ref<Fetch::Infrastructure::ResponseView> res, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bb) {// 1. Set bodyBytes to bb.- body_bytes = move(bb);+ holder->body_bytes = move(bb);// 2. Set response to res.- response = res;- };+ holder->response = res;+ });// 4. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.if (perform_fetch) {- TRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));+ TRY(perform_fetch->function()(request, TopLevelModule::Yes, process_response_consume_body));}// Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.// AD-HOC: The fetch runs on a parallel queue, since the event loop it would otherwise queue tasks on is paused below.else {Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::SyncAccumulate };- fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);+ fetch_algorithms_input.process_response_consume_body = process_response_consume_body;Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);}// 5. Pause until response is not null.- // FIXME: Consider using a "response holder" to avoid needing to annotate response as IGNORE_USE_IN_ESCAPING_LAMBDA.auto& event_loop = settings_object.responsible_event_loop();- auto response_is_not_null = GC::create_function(GC::Heap::the(), [&]() -> bool {- return !!response;+ auto response_is_not_null = GC::create_function(GC::Heap::the(), GC::captures(holder), [](NonnullRefPtr<ImportedScriptResponseHolder>& holder) -> bool {+ return !!holder->response;});if (perform_fetch) {// AD-HOC: The event loop is spun rather than paused, since a perform the fetch hook may queue tasks on it.@@ -656,12 +648,12 @@ WebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_scriauto pause_handle = event_loop.pause(EventLoop::UpdateTheRendering::No);Platform::EventLoopPlugin::the().spin_until(response_is_not_null);}+ auto response = holder->response;+ auto body_bytes = move(holder->body_bytes);- // NB: The fetch outlives an aborted script, whose stack the steps above must not write to anymore.- if (!response) {- is_abandoned->set_value(true);+ // NB: The event loop gives up on an aborted script before the response comes.+ if (!response)return WebIDL::NetworkError::create("Network error"_utf16);- }// NB: Whether response was CORS-cross-origin must be determined before unwrapping it, since the internal// response of an opaque filtered response is never CORS-cross-origin itself.@@ -719,7 +711,7 @@ WebIDL::ExceptionOr<void> fetch_worklet_module_worker_script_graph(URL::URL cons};// onSingleFetchComplete given result is the following algorithm:- auto on_single_fetch_complete = create_on_fetch_script_complete(GC::Heap::the(), [&realm, fetch_client, destination, perform_fetch = perform_fetch, on_complete = move(on_complete)](auto result) mutable {+ auto on_single_fetch_complete = create_on_fetch_script_complete(GC::Heap::the(), GC::captures(realm, fetch_client, destination, perform_fetch, on_complete), [](auto& realm, auto& fetch_client, auto& destination, auto& perform_fetch, auto& on_complete, GC::Ptr<Script> result) {// 1. If result is null, run onComplete with null, and abort these steps.if (!result) {dbgln("on single fetch complete with nool");@@ -728,7 +720,7 @@ WebIDL::ExceptionOr<void> fetch_worklet_module_worker_script_graph(URL::URL cons}// 2. Fetch the descendants of and link result given fetchClient, destination, and onComplete. If performFetch was given, pass it along as well.- fetch_descendants_of_and_link_a_module_script(realm, as<ModuleScript>(*result), fetch_client, destination, move(perform_fetch), on_complete);+ fetch_descendants_of_and_link_a_module_script(realm, as<ModuleScript>(*result), fetch_client, destination, perform_fetch, on_complete);});// 2. Fetch a single module script given url, fetchClient, destination, options, settingsObject, "client", true,@@ -795,7 +787,7 @@ void fetch_single_module_script(JS::Realm& realm,// 6. If moduleMap[(url, moduleType)] is a list, append onComplete to moduleMap[(url, moduleType)], and return.if (entry.has_value() && entry->has<ModuleMap::CallbackList>()) {- module_map.append(url, module_type, GC::create_function(GC::Heap::the(), [on_complete](GC::Ptr<ModuleScript> module_script) {+ module_map.append(url, module_type, GC::create_function(GC::Heap::the(), GC::captures(on_complete), [](auto& on_complete, GC::Ptr<ModuleScript> module_script) {on_complete->function()(module_script);}));return;@@ -803,7 +795,7 @@ void fetch_single_module_script(JS::Realm& realm,// 7. Set moduleMap[(url, moduleType)] to « onComplete ».GC::RootVector<ModuleMap::CallbackFunction> callbacks;- callbacks.append(GC::create_function(GC::Heap::the(), [on_complete](GC::Ptr<ModuleScript> module_script) { on_complete->function()(module_script); }));+ callbacks.append(GC::create_function(GC::Heap::the(), GC::captures(on_complete), [](auto& on_complete, GC::Ptr<ModuleScript> module_script) { on_complete->function()(module_script); }));module_map.set(url, module_type, move(callbacks));// 8. Let request be a new request whose URL is url, mode is "cors", referrer is referrer, and client is fetchClient.@@ -829,7 +821,7 @@ void fetch_single_module_script(JS::Realm& realm,// 13. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.// Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.// In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:- auto process_response_consume_body = [request, &module_map, url, module_type, &settings_object, options = options](GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) mutable {+ auto process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(request, module_map, url, module_type, settings_object, options), [](NonnullRefPtr<Fetch::Infrastructure::Request>& request, ModuleMap& module_map, URL::URL& url, Utf16String& module_type, EnvironmentSettingsObject& settings_object, ScriptFetchOptions& options, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {auto internal_response = response->unsafe_response();// 1. If any of the following are true:@@ -885,7 +877,6 @@ void fetch_single_module_script(JS::Realm& realm,// the result of creating a JavaScript module script given sourceText, settingsObject, response's URL,// and options.if (mime_type.has_value() && mime_type->is_javascript() && module_type == "javascript-or-wasm"sv) {- auto settings_root = GC::make_root(settings_object);auto url_string = url.to_byte_string();auto response_url = response->url().value_or({});auto module_type_string = module_type;@@ -894,16 +885,14 @@ void fetch_single_module_script(JS::Realm& realm,auto cache_key = compiled_script_cache_key(request, url, internal_response->status(), internal_response->header_list(), JS::ProgramType::Module, 0);compile_off_thread(settings_object, move(source_code), JS::ProgramType::Module, 0, move(cache_key),- [url = move(url), url_string = move(url_string), response_url = move(response_url),- module_type_string = move(module_type_string),- options, settings_root = move(settings_root)](auto result, auto source_code) mutable {+ GC::create_function(GC::Heap::the(), GC::captures(url, move(url_string), move(response_url), move(module_type_string), options, settings_object), [](URL::URL& url, ByteString& url_string, URL::URL& response_url, Utf16String& module_type_string, ScriptFetchOptions& options, EnvironmentSettingsObject& settings_object, OffThreadCompiledProgram result, NonnullRefPtr<JS::SourceCode const> source_code) {auto module_script = result.compiled- ? ModuleScript::create_from_pre_compiled(url_string, source_code, *settings_root, move(response_url), move(result.compiled)).release_value_but_fixme_should_propagate_errors()- : ModuleScript::create_from_pre_parsed(url_string, source_code, *settings_root, move(response_url), move(result.parsed)).release_value_but_fixme_should_propagate_errors();+ ? ModuleScript::create_from_pre_compiled(url_string, source_code, settings_object, move(response_url), move(result.compiled)).release_value_but_fixme_should_propagate_errors()+ : ModuleScript::create_from_pre_parsed(url_string, source_code, settings_object, move(response_url), move(result.parsed)).release_value_but_fixme_should_propagate_errors();if (module_script)module_script->set_fetch_options(options);- settings_root->module_map().complete_fetch(url, module_type_string, module_script);- });+ settings_object.module_map().complete_fetch(url, module_type_string, module_script);+ }));return;}@@ -925,16 +914,16 @@ void fetch_single_module_script(JS::Realm& realm,// moduleMap[(url, moduleType)] to moduleScript.// 10. For each callback of callbacks: run callback given moduleScript.module_map.complete_fetch(url, module_type, module_script);- };+ });if (perform_fetch != nullptr) {- auto result = perform_fetch->function()(request, is_top_level, move(process_response_consume_body));+ auto result = perform_fetch->function()(request, is_top_level, process_response_consume_body);// NB: The perform fetch hook can abort without running processResponseConsumeBody.if (result.is_exception())module_map.complete_fetch(url, module_type, nullptr);} else {Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::ConsumeForCallback };- fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);+ fetch_algorithms_input.process_response_consume_body = process_response_consume_body;Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));}}@@ -942,7 +931,7 @@ void fetch_single_module_script(JS::Realm& realm,// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-treevoid fetch_external_module_script_graph(JS::Realm& realm, URL::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions const& options, OnFetchScriptComplete on_complete){- auto steps = create_on_fetch_script_complete(GC::Heap::the(), [&realm, &settings_object, on_complete, url](auto result) mutable {+ auto steps = create_on_fetch_script_complete(GC::Heap::the(), GC::captures(realm, settings_object, on_complete), [](auto& realm, auto& settings_object, auto& on_complete, GC::Ptr<Script> result) {// 1. If result is null, run onComplete given null, and abort these steps.if (!result) {on_complete->function()(nullptr);@@ -961,7 +950,7 @@ void fetch_external_module_script_graph(JS::Realm& realm, URL::URL const& url, E// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-modulepreload-module-script-graphvoid fetch_modulepreload_module_script_graph(JS::Realm& realm, URL::URL const& url, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, ScriptFetchOptions const& options, OnFetchScriptComplete on_complete){- auto steps = create_on_fetch_script_complete(GC::Heap::the(), [&realm, &settings_object, destination, on_complete](auto result) mutable {+ auto steps = create_on_fetch_script_complete(GC::Heap::the(), GC::captures(realm, settings_object, destination, on_complete), [](auto& realm, auto& settings_object, auto& destination, auto& on_complete, GC::Ptr<Script> result) {// 1. Run onComplete given result.on_complete->function()(result);@@ -1089,7 +1078,7 @@ void fetch_descendants_of_and_link_a_module_script(JS::Realm& realm,WebIDL::react_to_promise(loading_promise,// 6. Upon fulfillment of loadingPromise, run the following steps:- GC::create_function(GC::Heap::the(), [&realm, record, &module_script, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, record, module_script, on_complete), [](auto& realm, auto& record, auto& module_script, auto& on_complete, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {// 1. Perform record.Link().auto linking_result = record.visit([](Empty) -> JS::ThrowCompletionOr<void> { VERIFY_NOT_REACHED(); },@@ -1106,7 +1095,7 @@ void fetch_descendants_of_and_link_a_module_script(JS::Realm& realm,}),// 7. Upon rejection of loadingPromise, run the following steps:- GC::create_function(GC::Heap::the(), [state, &module_script, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(state, module_script, on_complete), [](auto& state, auto& module_script, auto& on_complete, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {// 1. If state.[[ErrorToRethrow]] is not null, set moduleScript's error to rethrow to state.[[ErrorToRethrow]] and run// onComplete given moduleScript.if (!state->error_to_rethrow.is_null()) {diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.h b/Libraries/LibWeb/HTML/Scripting/Fetching.hindex fb6ba10d3e3..077ef6ee328 100644--- a/Libraries/LibWeb/HTML/Scripting/Fetching.h+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.h@@ -26,10 +26,20 @@ enum class TopLevelModule {};using OnFetchScriptComplete = GC::Ref<GC::Function<void(GC::Ptr<Script>)>>;-using PerformTheFetchHook = GC::Ptr<GC::Function<WebIDL::ExceptionOr<void>(NonnullRefPtr<Fetch::Infrastructure::Request>, TopLevelModule, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction)>>;+using ProcessCustomFetchResponse = GC::Ref<GC::Function<Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction::FunctionType>>;+using PerformTheFetchHook = GC::Ptr<GC::Function<WebIDL::ExceptionOr<void>(NonnullRefPtr<Fetch::Infrastructure::Request>, TopLevelModule, ProcessCustomFetchResponse)>>;-WEB_API OnFetchScriptComplete create_on_fetch_script_complete(GC::Heap& heap, Function<void(GC::Ptr<Script>)> function);-WEB_API PerformTheFetchHook create_perform_the_fetch_hook(GC::Heap& heap, Function<WebIDL::ExceptionOr<void>(NonnullRefPtr<Fetch::Infrastructure::Request>, TopLevelModule, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction)> function);+template<typename... Values, typename Callable>+OnFetchScriptComplete create_on_fetch_script_complete(GC::Heap& heap, GC::CaptureList<Values...>&& captures, Callable&& callable)+{+ return GC::create_function<void(GC::Ptr<Script>)>(heap, move(captures), forward<Callable>(callable));+}++template<typename Callable>+OnFetchScriptComplete create_on_fetch_script_complete(GC::Heap& heap, Callable&& callable)+{+ return GC::create_function<void(GC::Ptr<Script>)>(heap, GC::CaptureList<> {}, forward<Callable>(callable));+}class FetchContext : public JS::Cell {GC_CELL(FetchContext, JS::Cell);diff --git a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cppindex 95438f07d8c..82040f6c191 100644--- a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp+++ b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp@@ -327,7 +327,7 @@ GC::Ptr<WebIDL::Promise> ModuleScript::run(PreventErrorReporting prevent_error_r// 8. If preventErrorReporting is false, then upon rejection of evaluationPromise with reason, report the exception given by reason for script.if (prevent_error_reporting == PreventErrorReporting::No) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- WebIDL::upon_rejection(*evaluation_promise, GC::create_function(GC::Heap::the(), [&realm, script = GC::Ref { *this }](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ WebIDL::upon_rejection(*evaluation_promise, GC::create_function(GC::Heap::the(), GC::captures(realm, GC::Ref { *this }), [](auto& realm, auto& script, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {report_an_exception(realm.global_object(), reason, OmitError::No, script);return JS::js_undefined();}));diff --git a/Libraries/LibWeb/HTML/Scripting/ScriptFetchOptions.h b/Libraries/LibWeb/HTML/Scripting/ScriptFetchOptions.hindex 0eb78e2d94f..3864af8c836 100644--- a/Libraries/LibWeb/HTML/Scripting/ScriptFetchOptions.h+++ b/Libraries/LibWeb/HTML/Scripting/ScriptFetchOptions.h@@ -7,6 +7,7 @@#pragma once#include <AK/Utf16String.h>+#include <LibGC/Forward.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>@@ -42,3 +43,5 @@ struct ScriptFetchOptions {ScriptFetchOptions default_script_fetch_options();}++GC_UNTRACED_CAPTURE(Web::HTML::ScriptFetchOptions);diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp b/Libraries/LibWeb/HTML/SharedResourceRequest.cppindex ffc8bba7530..4b83db1b3ff 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp@@ -69,13 +69,13 @@ GC::Ref<SharedResourceRequest> SharedResourceRequest::create_from_navigation_resrequest->m_load_event_delayer.emplace(document);GC::Weak weak_request { *request };- auto process_body = GC::create_function(GC::Heap::the(), [weak_request, on_body_read](ByteBuffer data) {+ auto process_body = GC::create_function(GC::Heap::the(), GC::captures(weak_request, on_body_read), [](auto& weak_request, auto& on_body_read, ByteBuffer data) {// NB: A document for an SVG image is an XML document, so this is never an SVG image.if (auto request = weak_request.ptr())request->handle_successful_fetch(request->url(), IsSVGImage::No, move(data), false);on_body_read->function()();});- auto process_body_error = GC::create_function(GC::Heap::the(), [weak_request, on_body_read](JS::Value) {+ auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(weak_request, on_body_read), [](auto& weak_request, auto& on_body_read, JS::Value) {if (auto request = weak_request.ptr())request->handle_failed_fetch();on_body_read->function()();@@ -168,7 +168,7 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::GC::Weak weak_this { *this };Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = [weak_this, &realm, request](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ fetch_algorithms_input.process_response = GC::create_function<void(GC::Ref<Fetch::Infrastructure::ResponseView>)>(GC::Heap::the(), GC::captures(weak_this, realm, request), [](auto& weak_this, auto& realm, auto& request, GC::Ref<Fetch::Infrastructure::ResponseView> response) {auto self = weak_this.ptr();if (!self)return;@@ -179,7 +179,7 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::// https://github.com/whatwg/html/issues/9355response = response->unsafe_response();- auto process_body = GC::create_function(GC::Heap::the(), [weak_this, request, response, image_data_is_cors_cross_origin](ByteBuffer data) {+ auto process_body = GC::create_function(GC::Heap::the(), GC::captures(weak_this, request, response, image_data_is_cors_cross_origin), [](auto& weak_this, auto& request, auto& response, auto& image_data_is_cors_cross_origin, ByteBuffer data) {auto self = weak_this.ptr();if (!self)return;@@ -192,7 +192,7 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::self->m_image_mime_type = extracted_mime_type->essence();self->handle_successful_fetch(response->url().value_or(request->url()), is_svg_image ? IsSVGImage::Yes : IsSVGImage::No, move(data), image_data_is_cors_cross_origin);});- auto process_body_error = GC::create_function(GC::Heap::the(), [weak_this](JS::Value) {+ auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(weak_this), [](auto& weak_this, JS::Value) {auto self = weak_this.ptr();if (!self)return;@@ -218,7 +218,7 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::}response->body()->fully_read(realm, process_body, process_body_error, GC::Ref { realm.global_object() });- };+ });m_state = State::Fetching;// NB: A user that waits for the fetch decides if the fetch delays the load event; a lazy image's callbacks don't.@@ -233,7 +233,7 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::request,Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));- fetch_controller->set_stop_steps(GC::create_function(GC::Heap::the(), [weak_this] {+ fetch_controller->set_stop_steps(GC::create_function(GC::Heap::the(), GC::captures(weak_this), [](auto& weak_this) {if (auto self = weak_this.ptr())self->handle_stopped_fetch();}));@@ -247,40 +247,37 @@ void SharedResourceRequest::wait_without_callbacks()m_load_event_delayer.emplace(*m_document);}-void SharedResourceRequest::add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop)+void SharedResourceRequest::add_callbacks(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail, GC::Ptr<GC::Function<void()>> on_stop){- (void)add_removable_callbacks(move(on_finish), move(on_fail), move(on_stop));+ (void)add_removable_callbacks(on_finish, on_fail, on_stop);}-Optional<u64> SharedResourceRequest::add_removable_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop, DelaysLoadEvent delays_load_event)+Optional<u64> SharedResourceRequest::add_removable_callbacks(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail, GC::Ptr<GC::Function<void()>> on_stop, DelaysLoadEvent delays_load_event){if (m_state == State::Finished) {if (on_finish)- on_finish();+ on_finish->function()();return {};}if (m_state == State::Failed) {if (on_fail)- on_fail();+ on_fail->function()();return {};}if (m_state == State::Stopped) {if (on_stop)- on_stop();+ on_stop->function()();return {};}Callbacks callbacks;callbacks.id = m_next_callbacks_id++;callbacks.delays_load_event = delays_load_event;- if (on_finish)- callbacks.on_finish = GC::create_function(GC::Heap::the(), move(on_finish));- if (on_fail)- callbacks.on_fail = GC::create_function(GC::Heap::the(), move(on_fail));- if (on_stop)- callbacks.on_stop = GC::create_function(GC::Heap::the(), move(on_stop));+ callbacks.on_finish = on_finish;+ callbacks.on_fail = on_fail;+ callbacks.on_stop = on_stop;auto id = callbacks.id;m_callbacks.append(move(callbacks));diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.h b/Libraries/LibWeb/HTML/SharedResourceRequest.hindex 37412642ef0..12ef52f241f 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.h+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.h@@ -63,7 +63,7 @@ public:// Records a user that waits for the fetch without callbacks, so that the fetch delays the load event for it.void wait_without_callbacks();- void add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop = {});+ void add_callbacks(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail, GC::Ptr<GC::Function<void()>> on_stop = {});enum class DelaysLoadEvent : u8 {No,@@ -71,7 +71,7 @@ public:};// Returns an ID for remove_callbacks(), or nothing if the callbacks already ran.- Optional<u64> add_removable_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop = {}, DelaysLoadEvent = DelaysLoadEvent::Yes);+ Optional<u64> add_removable_callbacks(GC::Ptr<GC::Function<void()>> on_finish, GC::Ptr<GC::Function<void()>> on_fail, GC::Ptr<GC::Function<void()>> on_stop = {}, DelaysLoadEvent = DelaysLoadEvent::Yes);void remove_callbacks(u64 id);bool is_fetching() const;diff --git a/Libraries/LibWeb/HTML/TextTrackObserver.cpp b/Libraries/LibWeb/HTML/TextTrackObserver.cppindex 7851651730d..ea27747426c 100644--- a/Libraries/LibWeb/HTML/TextTrackObserver.cpp+++ b/Libraries/LibWeb/HTML/TextTrackObserver.cpp@@ -35,12 +35,9 @@ void TextTrackObserver::finalize()m_text_track->unregister_observer({}, *this);}-void TextTrackObserver::set_track_readiness_observer(Function<void(TextTrack::ReadinessState)> callback)+void TextTrackObserver::set_track_readiness_observer(GC::Ptr<GC::Function<void(TextTrack::ReadinessState)>> callback){- if (callback)- m_track_readiness_observer = GC::create_function(GC::Heap::the(), move(callback));- else- m_track_readiness_observer = nullptr;+ m_track_readiness_observer = callback;}}diff --git a/Libraries/LibWeb/HTML/TextTrackObserver.h b/Libraries/LibWeb/HTML/TextTrackObserver.hindex af165c30d7a..5ea2284a2ef 100644--- a/Libraries/LibWeb/HTML/TextTrackObserver.h+++ b/Libraries/LibWeb/HTML/TextTrackObserver.h@@ -22,7 +22,7 @@ public:[[nodiscard]] static GC::Ref<TextTrackObserver> create(TextTrack&);[[nodiscard]] GC::Ptr<GC::Function<void(TextTrack::ReadinessState)>> track_readiness_observer() const { return m_track_readiness_observer; }- void set_track_readiness_observer(Function<void(TextTrack::ReadinessState)>);+ void set_track_readiness_observer(GC::Ptr<GC::Function<void(TextTrack::ReadinessState)>>);private:explicit TextTrackObserver(TextTrack&);diff --git a/Libraries/LibWeb/HTML/UniversalGlobalScope.cpp b/Libraries/LibWeb/HTML/UniversalGlobalScope.cppindex 43b3495e4e4..49b669f291b 100644--- a/Libraries/LibWeb/HTML/UniversalGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/UniversalGlobalScope.cpp@@ -82,7 +82,8 @@ void UniversalGlobalScopeMixin::notify_about_rejected_promises(Badge<EventLoop>)auto& global_object = relevant_realm_for_universal_global_scope(global).global_object();// 5. Queue a global task on the DOM manipulation task source given global to run the following substep:- queue_global_task(Task::Source::DOMManipulation, global_object, GC::create_function(GC::Heap::the(), [this, &global, list = move(list)] {+ queue_global_task(Task::Source::DOMManipulation, global_object, GC::create_function(GC::Heap::the(), GC::captures(global, move(list)), [](auto& global, auto& list) {+ auto& self = as<UniversalGlobalScopeMixin>(global);auto& realm = relevant_realm_for_universal_global_scope(global);// 1. For each promise p in list:@@ -113,7 +114,7 @@ void UniversalGlobalScopeMixin::notify_about_rejected_promises(Badge<EventLoop>)// 4. If p's [[PromiseIsHandled]] internal slot is false, add p to settings object's outstanding rejected promises weak set.if (!promise->is_handled())- m_outstanding_rejected_promises_weak_set.append(*promise);+ self.m_outstanding_rejected_promises_weak_set.append(*promise);// This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors.// If a rejection is still not handled after this, then the rejection may be reported to a developer console.diff --git a/Libraries/LibWeb/HTML/VideoTrack.cpp b/Libraries/LibWeb/HTML/VideoTrack.cppindex d68781e5545..a20fc7b55eb 100644--- a/Libraries/LibWeb/HTML/VideoTrack.cpp+++ b/Libraries/LibWeb/HTML/VideoTrack.cpp@@ -83,9 +83,9 @@ void VideoTrack::set_selected(bool selected)// task given the media element to fire an event named change at the VideoTrackList object. This task must be queued before// the task that fires the resize event, if any.if (previously_unselected_track_is_selected || selected_track_was_unselected_without_another_selection) {- media_element().queue_a_media_element_task([this, video_track_list](HTMLMediaElement&) {- video_track_list->dispatch_event(create_event_for_element(media_element(), HTML::EventNames::change));- });+ media_element().queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this, video_track_list), [](auto& self, auto& video_track_list, HTMLMediaElement&) {+ video_track_list->dispatch_event(create_event_for_element(self.media_element(), HTML::EventNames::change));+ }));}}diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cppindex b89bf458cbe..c4caa4b36aa 100644--- a/Libraries/LibWeb/HTML/Window.cpp+++ b/Libraries/LibWeb/HTML/Window.cpp@@ -223,13 +223,13 @@ WebIDL::UnsignedLong request_animation_frame(HTML::Window& window, WebIDL::Callb// handler belongs to the window, so the callback lives exactly as long as the window's document. A root here// would keep a callback that never runs (a hidden document gets no animation frames) alive for the life of// the process, and with it the window, its document, and everything the document holds.- auto handler = [callback = GC::Ref { callback }](double now) {+ auto handler = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { callback }), [](GC::Ref<WebIDL::CallbackType>& callback, double now) {auto& callback_realm = callback->callback->shape().realm();auto result = WebIDL::invoke_callback(*callback, {}, { { JS::Value(now) } });if (result.is_error())HTML::report_exception(result, callback_realm);- };- return window.request_animation_frame(move(handler));+ });+ return window.request_animation_frame(handler);}WebIDL::ExceptionOr<WebIDL::UnsignedLong> request_animation_frame(HTML::DedicatedWorkerGlobalScope& scope, WebIDL::CallbackType& callback)@@ -241,11 +241,11 @@ WebIDL::UnsignedLong request_idle_callback(HTML::Window& window, WebIDL::Callbac{// NB: A plain GC reference rather than a GC::Root, for the same reason as in request_animation_frame() above: the// window's idle callback lists trace the handler, so the callback lives exactly as long as the window's document.- auto handler = [callback = GC::Ref { callback }](GC::Ref<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {+ auto handler = GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { callback }), [](GC::Ref<WebIDL::CallbackType>& callback, GC::Ref<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {auto& callback_realm = callback->callback->shape().realm();return WebIDL::invoke_callback(*callback, {}, { { wrap(host_defined_wrapper_world(callback_realm), callback_realm, deadline) } });- };- return window.request_idle_callback(move(handler), options);+ });+ return window.request_idle_callback(handler, options);}void define_internals_property(JS::Realm& realm, HTML::Window& window, JS::Object& global_object)@@ -1010,8 +1010,8 @@ void Window::start_an_idle_period()// 5. Queue a task on the queue associated with the idle-task task source,// which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.- queue_global_task(Task::Source::IdleTask, relevant_global_object(*this), GC::create_function(GC::Heap::the(), [this] {- invoke_idle_callbacks();+ queue_global_task(Task::Source::IdleTask, relevant_global_object(*this), GC::create_function(GC::Heap::the(), GC::captures(*this), [](Window& self) {+ self.invoke_idle_callbacks();}),Task::Priority::Idle);}@@ -1041,8 +1041,8 @@ void Window::invoke_idle_callbacks()// 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps// in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithmif (!m_runnable_idle_callbacks.is_empty()) {- queue_global_task(Task::Source::IdleTask, relevant_global_object(*this), GC::create_function(GC::Heap::the(), [this] {- invoke_idle_callbacks();+ queue_global_task(Task::Source::IdleTask, relevant_global_object(*this), GC::create_function(GC::Heap::the(), GC::captures(*this), [](Window& self) {+ self.invoke_idle_callbacks();}),Task::Priority::Idle);}@@ -1300,7 +1300,7 @@ void Window::close()traversable->set_closing(true);// 2. Queue a task on the DOM manipulation task source to definitely close thisTraversable.- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(incumbent_global_object), GC::create_function(GC::Heap::the(), [traversable] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object(incumbent_global_object), GC::create_function(GC::Heap::the(), GC::captures(traversable), [](auto& traversable) {as<LocalTraversableNavigable>(*traversable).definitely_close_top_level_traversable();}));}@@ -2162,7 +2162,7 @@ double Window::device_pixel_ratio() constWebIDL::UnsignedLong Window::request_animation_frame(AnimationFrameCallbackHandler callback){// FIXME: Make this fully spec compliant. Currently implements a mix of 'requestAnimationFrame()' and 'run the animation frame callbacks'.- auto handle = animation_frame_callback_driver().add(GC::create_function(GC::Heap::the(), move(callback)));+ auto handle = animation_frame_callback_driver().add(callback);if (Core::StatsLog::the())set_rendering_pending(associated_document(), RenderingPendingReason::ScheduledAnimationFrameCallbacks, animation_frame_callback_driver().callback_count());page().client().request_frame();@@ -2210,7 +2210,7 @@ u32 Window::request_idle_callback(IdleCallbackHandler callback, IdleRequestOptioauto handle = m_idle_callback_identifier;// 4. Push callback to the end of window's list of idle request callbacks, associated with handle.- auto idle_callback = GC::Heap::the().allocate<IdleCallback>(GC::create_function(GC::Heap::the(), move(callback)), handle);+ auto idle_callback = GC::Heap::the().allocate<IdleCallback>(callback, handle);m_idle_request_callbacks.set(handle, idle_callback);main_thread_event_loop().did_request_idle_callback();@@ -2220,17 +2220,17 @@ u32 Window::request_idle_callback(IdleCallbackHandler callback, IdleRequestOptioif (options.timeout.has_value() && *options.timeout > 0) {// 1. Wait for timeout milliseconds.auto timeout = min(*options.timeout, static_cast<u32>(NumericLimits<i32>::max()));- auto timeout_timer_id = run_steps_after_a_timeout(static_cast<i32>(timeout), [this, handle] {+ auto timeout_timer_id = run_steps_after_a_timeout(static_cast<i32>(timeout), GC::create_function(GC::Heap::the(), GC::captures(*this, handle), [](Window& self, u32 handle) {// FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.// FIXME: 3. Optionally, wait a further user-agent defined length of time.// 4. Queue a task on the queue associated with the idle-task task source, which performs the invoke idle callback timeout algorithm, passing handle and window as arguments.// NB: A timed-out idle task has normal scheduling priority so that higher-priority work cannot keep it from// running indefinitely. Its task source remains the idle-task task source as required by the specification.- queue_global_task(Task::Source::IdleTask, relevant_global_object(*this), GC::create_function(GC::Heap::the(), [this, handle] {- invoke_idle_callback_timeout(handle);+ queue_global_task(Task::Source::IdleTask, relevant_global_object(self), GC::create_function(GC::Heap::the(), GC::captures(self, handle), [](Window& self, u32 handle) {+ self.invoke_idle_callback_timeout(handle);}));- });+ }));idle_callback->set_timeout_timer_id(timeout_timer_id);}diff --git a/Libraries/LibWeb/HTML/Window.h b/Libraries/LibWeb/HTML/Window.hindex 786644ae319..a2f5c52dcf3 100644--- a/Libraries/LibWeb/HTML/Window.h+++ b/Libraries/LibWeb/HTML/Window.h@@ -74,8 +74,8 @@ WEB_API JS::Value window_named_item_value(WrapperWorld&, JS::Realm&, HTML::Windonamespace Web::HTML {class IdleCallback;-using AnimationFrameCallbackHandler = Function<void(double)>;-using IdleCallbackHandler = Function<JS::Completion(GC::Ref<RequestIdleCallback::IdleDeadline>)>;+using AnimationFrameCallbackHandler = GC::Ref<GC::Function<void(double)>>;+using IdleCallbackHandler = GC::Ref<GC::Function<JS::Completion(GC::Ref<RequestIdleCallback::IdleDeadline>)>>;// https://html.spec.whatwg.org/multipage/webappapis.html#specifier-resolution-record// A specifier resolution record is a struct. It has the following items:diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex c8d838b1f35..11b0aad6b4b 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -237,7 +237,7 @@ void WindowOrWorkerGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callbdocument = &static_cast<Window&>(this_impl()).associated_document();// The queueMicrotask(callback) method must queue a microtask to invoke callback with « » and "report".- HTML::queue_a_microtask(document, GC::create_function(GC::Heap::the(), [&callback] {+ HTML::queue_a_microtask(document, GC::create_function(GC::Heap::the(), GC::captures(callback), [](auto& callback) {(void)WebIDL::invoke_callback(callback, {}, WebIDL::ExceptionBehavior::Report, {});}));}@@ -584,7 +584,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,begin_rendering_pending_operation(GC::as_cell(p.ptr()), window->associated_document(), RenderingPendingReason::ImageDecodes);}// Run these step in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [=]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(blob, p, sx, sy, sw, sh, options), [](auto& blob, auto& p, auto& sx, auto& sy, auto& sw, auto& sh, auto& options) {// 1. Let imageData be the result of reading image's data. If an error occurs during reading of the// object, then queue a global task, using the bitmap task source, to reject promise with an// "InvalidStateError" DOMException and abort these steps.@@ -603,7 +603,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,// (e.g., a vector graphic with no natural size), then queue a global task, using the bitmap// task source, to reject promise with an "InvalidStateError" DOMException and abort these steps.auto& realm = WebIDL::promise_realm(*p);- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p), [](auto& p) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image does not contain a supported image format"_utf16));@@ -625,7 +625,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,// Spec issue: https://github.com/whatwg/html/issues/3323if (cropped_bitmap_or_error.is_error()) {auto& realm = WebIDL::promise_realm(*p);- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p), [](auto& p) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));@@ -637,7 +637,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,auto& realm = WebIDL::promise_realm(*p);// 5. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p, image_bitmap), [](auto& p, auto& image_bitmap) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };Bindings::resolve_image_bitmap_promise(realm, *p, GC::Ref { *image_bitmap });@@ -680,7 +680,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());// 4. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p, image_bitmap), [](auto& p, auto& image_bitmap) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };Bindings::resolve_image_bitmap_promise(realm, *p, image_bitmap);@@ -712,7 +712,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,image_bitmap->set_origin_clean(canvas->is_origin_clean());// 3. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p, image_bitmap), [](auto& p, auto& image_bitmap) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };Bindings::resolve_image_bitmap_promise(realm, *p, image_bitmap);@@ -741,7 +741,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,image_bitmap->set_origin_clean(source_image_bitmap->is_origin_clean());// 3. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p, image_bitmap), [](auto& p, auto& image_bitmap) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };Bindings::resolve_image_bitmap_promise(realm, *p, image_bitmap);@@ -780,7 +780,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,image_bitmap->set_origin_clean(false);// 4. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p, image_bitmap), [](auto& p, auto& image_bitmap) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };Bindings::resolve_image_bitmap_promise(realm, *p, image_bitmap);@@ -841,7 +841,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,image_bitmap->set_origin_clean(false);// 5. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.- queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {+ queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(p, image_bitmap), [](auto& p, auto& image_bitmap) {auto& realm = WebIDL::promise_realm(*p);TemporaryExecutionContext const context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };Bindings::resolve_image_bitmap_promise(realm, *p, image_bitmap);@@ -954,11 +954,13 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// FIXME: 8. Let uniqueHandle be null.// 9. Let task be a task that runs the following substeps:- auto task = GC::create_function(GC::Heap::the(), Function<void()>([this, handler = move(function_or_string), timeout, arguments = move(arguments), repeat, id, initiating_script]() {+ auto task = GC::create_function(GC::Heap::the(), GC::captures(this_impl(), move(function_or_string), timeout, move(arguments), repeat, id, initiating_script), [](auto& this_object, auto& handler, auto& timeout, auto& arguments, auto& repeat, auto& id, auto& initiating_script) {+ auto& self = as<WindowOrWorkerGlobalScopeMixin>(this_object);+// FIXME: 1. Assert: uniqueHandle is a unique internal value, not null.// 2. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.- if (!m_timers.contains(id))+ if (!self.m_timers.contains(id))return;// FIXME: 3. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.@@ -968,10 +970,10 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// 5. If handler is a Function, then invoke handler given arguments and "report", and with callback this value set to thisArg.[&](GC::Root<WebIDL::CallbackType> const& callback) {auto this_value = [&]() -> JS::Value {- if (auto* window = as_if<Window>(this_impl()))+ if (auto* window = as_if<Window>(self.this_impl()))return &window->window()->object();- auto& realm = relevant_realm(*this);- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { this_impl() });+ auto& realm = relevant_realm(self);+ return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { self.this_impl() });}();(void)WebIDL::invoke_callback(*callback, this_value, WebIDL::ExceptionBehavior::Report, arguments);},@@ -980,7 +982,7 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// 1. Assert: handler is a string.// 2. Let settings object be global's relevant settings object.- auto& settings_object = relevant_settings_object(*this);+ auto& settings_object = relevant_settings_object(self);// 3. Let fetch options be the default classic script fetch options.auto options = default_script_fetch_options();@@ -1020,7 +1022,7 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio});// 7. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.- if (!m_timers.contains(id))+ if (!self.m_timers.contains(id))return;// FIXME: 8. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.@@ -1028,15 +1030,17 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatioswitch (repeat) {// 9. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.case Repeat::Yes:- MUST(run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id));+ // NB: The arguments are copied rather than moved, as this task may run again while its callback is on the+ // stack, e.g. from a nested event loop the callback spins.+ MUST(self.run_timer_initialization_steps(handler, timeout, GC::RootVector<JS::Value> { arguments.span() }, repeat, id));break;// 10. Otherwise, remove global's map of active timers[id].case Repeat::No:- m_timers.remove(id);+ self.m_timers.remove(id);break;}- }));+ });// 11. Increment nesting level by one.nesting_level++;@@ -1046,31 +1050,34 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::run_timer_initializatio// NB: The task the event loop runs is the one completionStep queues — so that's what carries step 12's nesting// level. queue_global_task() creates its task internally; so, this queues one by hand to get at it — and a// fresh one per firing.- Function<void()> completion_step = [this, task = move(task), nesting_level, id]() mutable {+ auto completion_step = GC::create_function(GC::Heap::the(), GC::captures(this_impl(), task, nesting_level, id), [](auto& this_object, auto& task, auto& nesting_level, auto& id) {+ auto& self = as<WindowOrWorkerGlobalScopeMixin>(this_object);+// NB: The spec arms a timer's next firing only once its task has run — so only a firing that timer claims// queues one. Queueing the rest would run a burst of callbacks back to back, at a stale nesting level// that keeps them from being clamped, and the burst grows the busier the event loop is.- auto timer = m_timers.get(id);+ auto timer = self.m_timers.get(id);if (!timer.has_value() || !(*timer)->claim_firing())return;- auto& global = relevant_global_object(*this);+ auto& global = relevant_global_object(self);GC::Ptr<DOM::Document const> document;if (auto* window = window_from_global_object(global))document = &window->associated_document();- auto queued_task = Task::create(Task::Source::TimerTask, document, GC::create_function(GC::Heap::the(), [this, task, timer = *timer] {+ auto queued_task = Task::create(Task::Source::TimerTask, document, GC::create_function(GC::Heap::the(), GC::captures(this_object, task, *timer), [](auto& this_object, auto& task, auto& timer) {+ auto& self = as<WindowOrWorkerGlobalScopeMixin>(this_object);timer->release_firing();- HTML::TemporaryExecutionContext execution_context { relevant_settings_object(*this), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ HTML::TemporaryExecutionContext execution_context { relevant_settings_object(self), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };task->function()();}));queued_task->set_timer_nesting_level(nesting_level);relevant_agent(global).event_loop->task_queue().add(queued_task);- };+ });// 14. Set uniqueHandle to the result of running steps after a timeout given global, "setTimeout/setInterval",// timeout, and completionStep.// FIXME: run_steps_after_a_timeout() needs to be updated to return a unique internal value that can be used here.- run_steps_after_a_timeout_impl(timeout, throttling_class, move(completion_step), id, repeat);+ run_steps_after_a_timeout_impl(timeout, throttling_class, completion_step, id, repeat);// FIXME: 15. Set global's map of setTimeout and setInterval IDs[id] to uniqueHandle.@@ -1257,15 +1264,16 @@ void WindowOrWorkerGlobalScopeMixin::queue_the_performance_observer_task()// 3. Queue a task that consists of running the following substeps. The task source for the queued task is the performance// timeline task source.- queue_global_task(Task::Source::PerformanceTimeline, relevant_global_object(*this), GC::create_function(GC::Heap::the(), [this]() {- auto& realm = relevant_realm(*this);+ queue_global_task(Task::Source::PerformanceTimeline, relevant_global_object(*this), GC::create_function(GC::Heap::the(), GC::captures(this_impl()), [](auto& this_object) {+ auto& self = as<WindowOrWorkerGlobalScopeMixin>(this_object);+ auto& realm = relevant_realm(self);HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Unset performance observer task queued flag of relevantGlobal.- m_performance_observer_task_queued = false;+ self.m_performance_observer_task_queued = false;// 2. Let notifyList be a copy of relevantGlobal's list of registered performance observer objects.- GC::RootVector notify_list { m_registered_performance_observer_objects.values() };+ GC::RootVector notify_list { self.m_registered_performance_observer_objects.values() };// 3. For each registered performance observer object registeredObserver in notifyList, run these steps:for (auto& registered_observer : notify_list) {@@ -1297,9 +1305,9 @@ void WindowOrWorkerGlobalScopeMixin::queue_the_performance_observer_task()// 2. For each PerformanceObserverInit item in registeredObserver's options list:for (auto const& item : registered_observer->options_list()) {// 1. For each DOMString entryType that appears either as item's type or in item's entryTypes:- auto increment_dropped_entries_count = [this, &dropped_entries_count](Utf16FlyString const& type) {+ auto increment_dropped_entries_count = [&self, &dropped_entries_count](Utf16FlyString const& type) {// 1. Let map be relevantGlobal's performance entry buffer map.- auto const& map = m_performance_entry_buffer_map;+ auto const& map = self.m_performance_entry_buffer_map;// 2. Let tuple be the result of getting the value of entry on map given entryType as key.auto const& tuple = map.get(type);@@ -1354,8 +1362,8 @@ void WindowOrWorkerGlobalScopeMixin::add_resource_timing_entry(Badge<ResourceTimm_resource_timing_buffer_full_event_pending = true;// b. Queue a task on the performance timeline task source to run fire a buffer full event.- HTML::queue_a_task(HTML::Task::Source::PerformanceTimeline, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {- fire_resource_timing_buffer_full_event();+ HTML::queue_a_task(HTML::Task::Source::PerformanceTimeline, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(this_impl()), [](auto& this_object) {+ as<WindowOrWorkerGlobalScopeMixin>(this_object).fire_resource_timing_buffer_full_event();}));}@@ -1498,20 +1506,20 @@ WindowOrWorkerGlobalScopeMixin::AffectedAnyWebSockets WindowOrWorkerGlobalScopeM}// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#run-steps-after-a-timeout-i32 WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout(i32 timeout, Function<void()> completion_step)+i32 WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout(i32 timeout, GC::Ref<GC::Function<void()>> completion_step){auto timer_key = m_timer_id_allocator.allocate();- auto remove_timer_and_complete = [this, timer_key, completion_step = move(completion_step)] mutable {- m_timers.remove(timer_key);- completion_step();- };+ auto remove_timer_and_complete = GC::create_function(GC::Heap::the(), GC::captures(this_impl(), timer_key, completion_step), [](auto& this_object, auto& timer_key, auto& completion_step) {+ as<WindowOrWorkerGlobalScopeMixin>(this_object).m_timers.remove(timer_key);+ completion_step->function()();+ });// NB: A timeout another specification waits on — an idle callback's, an AbortSignal's — isn't one of the page's// own yield points, so a hidden document holds it back like a chained timer, however short it is.- run_steps_after_a_timeout_impl(timeout, TimerThrottlingClass::Chained, move(remove_timer_and_complete), timer_key);+ run_steps_after_a_timeout_impl(timeout, TimerThrottlingClass::Chained, remove_timer_and_complete, timer_key);return timer_key;}-void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout_impl(i32 timeout, TimerThrottlingClass throttling_class, Function<void()> completion_step, Optional<i32> timer_key, Repeat repeat)+void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout_impl(i32 timeout, TimerThrottlingClass throttling_class, GC::Ref<GC::Function<void()>> completion_step, Optional<i32> timer_key, Repeat repeat){// 1. Assert: if timerKey is given, then the caller of this algorithm is the timer initialization steps. (Other specifications must not pass timerKey.)// Note: This is enforced by the caller.@@ -1531,18 +1539,16 @@ void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout_impl(i32 timeout,m_earliest_timer_deadline = min(m_earliest_timer_deadline, deadline);// NB: The intensive tier paces chained timers by their wake-ups (see throttled_timer_delay()), so note when one- // runs while the document is hidden. The step itself goes into a GC::Function rather than into the wrapper's- // captures: Timer::visit_edges() scans only the bytes of the callable the timer holds, and an AK::Function- // nested in there keeps its own captures out of line once they outgrow its inline storage, where that scan- // can't see them. An AbortSignal.timeout() signal lives nowhere else until it aborts, so a collection would- // sweep it. A GC::Function scans its own callable's captures, whatever their size.+ // runs while the document is hidden.+ Function<void()> timer_callback;if (throttling_class == TimerThrottlingClass::Chained) {- auto step = GC::create_function(GC::Heap::the(), move(completion_step));- completion_step = [this, step] {+ timer_callback = [this, completion_step] {if (timers_are_throttled())m_last_chained_timer_wake_up = HighResolutionTime::unsafe_shared_current_time();- step->function()();+ completion_step->function()();};+ } else {+ timer_callback = [completion_step] { completion_step->function()(); };}// NB: We deviate from the spec here slightly by reusing existing timers if a timer_key is provided.@@ -1551,7 +1557,7 @@ void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout_impl(i32 timeout,auto result = m_timers.get(timer_key.value());if (result.has_value()) {existing_timer = result.value().ptr();- existing_timer->set_callback(move(completion_step));+ existing_timer->set_callback(move(timer_callback));existing_timer->set_throttling_class(throttling_class);existing_timer->set_deadline(deadline);// A throttled delay runs from now to the wake-up, so the timer restarts on it; unthrottled, a repeating@@ -1573,7 +1579,7 @@ void WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout_impl(i32 timeout,// completed. The task callback still calls run_timer_initialization_steps to update nesting// levels and potentially clamp the interval.auto repeating = repeat == Repeat::Yes ? Timer::Repeating::Yes : Timer::Repeating::No;- auto timer = existing_timer ? GC::Ref { *existing_timer } : Timer::create(throttled_delay.value_or(timeout), move(completion_step), timer_key.value(), repeating, throttling_class, deadline);+ auto timer = existing_timer ? GC::Ref { *existing_timer } : Timer::create(throttled_delay.value_or(timeout), move(timer_callback), timer_key.value(), repeating, throttling_class, deadline);// FIXME: 4. Set global's map of active timers[timerKey] to startTime plus milliseconds.m_timers.set(timer_key.value(), timer);@@ -1772,8 +1778,9 @@ void WindowOrWorkerGlobalScopeMixin::notify_about_rejected_promises(Badge<EventLauto& global_object = relevant_global_object(*this);// 5. Queue a global task on the DOM manipulation task source given global to run the following substep:- queue_global_task(Task::Source::DOMManipulation, global_object, GC::create_function(GC::Heap::the(), [this, &global, list = move(list)] {- auto& realm = relevant_realm(*this);+ queue_global_task(Task::Source::DOMManipulation, global_object, GC::create_function(GC::Heap::the(), GC::captures(global, move(list)), [](auto& global, auto& list) {+ auto& self = as<WindowOrWorkerGlobalScopeMixin>(global);+ auto& realm = relevant_realm(self);// 1. For each promise p in list:for (auto const& promise : list->elements()) {@@ -1803,7 +1810,7 @@ void WindowOrWorkerGlobalScopeMixin::notify_about_rejected_promises(Badge<EventL// 4. If p's [[PromiseIsHandled]] internal slot is false, add p to settings object's outstanding rejected promises weak set.if (!promise->is_handled())- m_outstanding_rejected_promises_weak_set.append(*promise);+ self.m_outstanding_rejected_promises_weak_set.append(*promise);// This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors.// If a rejection is still not handled after this, then the rejection may be reported to a developer console.diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.hindex c19b8f41cd2..b25e0d124a8 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h@@ -105,7 +105,7 @@ public:bool has_pending_activity(DOM::EventTarget const&) const;void clear_objects_with_pending_activity() { m_objects_with_pending_activity.clear(); }- i32 run_steps_after_a_timeout(i32 timeout, Function<void()> completion_step);+ i32 run_steps_after_a_timeout(i32 timeout, GC::Ref<GC::Function<void()>> completion_step);void document_visibility_state_changed(Badge<DOM::Document>);void document_audio_play_state_changed(Badge<DOM::Document>);@@ -163,7 +163,7 @@ private:};WebIDL::ExceptionOr<i32> run_timer_initialization_steps(TimerHandler handler, i32 timeout, GC::RootVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id = {});bool has_expired_timer_yet_to_fire(double now);- void run_steps_after_a_timeout_impl(i32 timeout, TimerThrottlingClass, Function<void()> completion_step, Optional<i32> timer_key, Repeat repeat = Repeat::No);+ void run_steps_after_a_timeout_impl(i32 timeout, TimerThrottlingClass, GC::Ref<GC::Function<void()>> completion_step, Optional<i32> timer_key, Repeat repeat = Repeat::No);bool document_is_hidden() const;bool timers_are_throttled() const;Optional<i32> throttled_timer_delay(TimerThrottlingClass, double deadline) const;diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cppindex f5503333e41..5d978631dca 100644--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp@@ -239,7 +239,7 @@ void WorkerAgentParent::dispatch_error_event()auto outside_global_object = GC::Ref { m_outside_settings->global_object() };auto event_target = GC::Ref { *m_worker_event_target };queue_global_task(Task::Source::DOMManipulation, *outside_global_object,- GC::create_function(GC::Heap::the(), [event_target, outside_global_object] {+ GC::create_function(GC::Heap::the(), GC::captures(event_target, outside_global_object), [](auto& event_target, auto& outside_global_object) {event_target->dispatch_event(DOM::Event::create(EventNames::error,HighResolutionTime::current_high_resolution_time(*outside_global_object)));@@ -250,8 +250,8 @@ void WorkerAgentParent::dispatch_worker_exception(Utf16String message, Utf16Stri{// https://html.spec.whatwg.org/multipage/webappapis.html#report-an-exception// 7.2: If global implements DedicatedWorkerGlobalScope, queue a global task on the DOM manipulation task source with the global's associated Worker's relevant global object to run these steps:- queue_global_task(Task::Source::DOMManipulation, m_outside_settings->global_object(), GC::create_function(GC::Heap::the(), [this, message = move(message), filename = move(filename), lineno, colno]() {- auto& realm = m_outside_settings->realm();+ queue_global_task(Task::Source::DOMManipulation, m_outside_settings->global_object(), GC::create_function(GC::Heap::the(), GC::captures(*this, move(message), move(filename), lineno, colno), [](WorkerAgentParent& self, Utf16String& message, Utf16String& filename, u32 lineno, u32 colno) {+ auto& realm = self.m_outside_settings->realm();// 2. Set notHandled to the result of firing an event named error at workerObject, using ErrorEvent, with the// cancelable attribute initialized to true, and additional attributes initialized according to errorInfo.@@ -263,11 +263,11 @@ void WorkerAgentParent::dispatch_worker_exception(Utf16String message, Utf16Strievent_init.colno = colno;event_init.error = JS::js_null();auto error = ErrorEvent::create(EventNames::error, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object()));- bool not_handled = m_worker_event_target->dispatch_event(error);+ bool not_handled = self.m_worker_event_target->dispatch_event(error);// 3. If notHandled is true, then report exception for workerObject's relevant global object with omitError set to true.if (not_handled) {- auto* window_or_worker = window_or_worker_global_scope_from_global_object(m_outside_settings->global_object());+ auto* window_or_worker = window_or_worker_global_scope_from_global_object(self.m_outside_settings->global_object());VERIFY(window_or_worker);report_worker_exception(*window_or_worker, error);}diff --git a/Libraries/LibWeb/HTML/Worklet.cpp b/Libraries/LibWeb/HTML/Worklet.cppindex 16286597917..04172a340a7 100644--- a/Libraries/LibWeb/HTML/Worklet.cpp+++ b/Libraries/LibWeb/HTML/Worklet.cpp@@ -75,8 +75,8 @@ GC::Ref<WebIDL::Promise> Worklet::add_module(Utf16String const& module_url, Bind// 2. Let script be the result of fetching a worklet script graph given moduleURLRecord, outsideSettings,// workletType's fetch destination, credentialOptions's credentials, insideSettings, and the following// options:...- auto on_complete = create_on_fetch_script_complete(realm.heap(),- [promise, &realm](GC::Ptr<Script> script) {+ auto on_complete = create_on_fetch_script_complete(realm.heap(), GC::captures(promise, realm),+ [](auto& promise, auto& realm, GC::Ptr<Script> script) {// 3. If script is null, then reject promise with an "AbortError" DOMException and abort these steps.TemporaryExecutionContext execution_context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };if (!script) {@@ -105,7 +105,7 @@ GC::Ref<WebIDL::Promise> Worklet::add_module(Utf16String const& module_url, Bind// 1. Set pendingTasks to pendingTasks − 1.// 2. If pendingTasks is 0, then resolve promise.// NB: With our single global scope, pendingTasks is 1 here.- queue_global_task(Task::Source::Networking, realm.global_object(), GC::create_function(realm.heap(), [promise, &realm] {+ queue_global_task(Task::Source::Networking, realm.global_object(), GC::create_function(realm.heap(), GC::captures(promise, realm), [](auto& promise, auto& realm) {TemporaryExecutionContext execution_context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::resolve_promise(realm, promise, JS::js_undefined());}));diff --git a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp b/Libraries/LibWeb/IndexedDB/RustIntegration.cppindex 99e182f0806..dafbb3fdb45 100644--- a/Libraries/LibWeb/IndexedDB/RustIntegration.cpp+++ b/Libraries/LibWeb/IndexedDB/RustIntegration.cpp@@ -88,8 +88,8 @@ JSObject* web_indexed_db_create_dom_string_list(void* realm, FlatPtr const* strivoid web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*)){GC::Ref<GC::Cell> function = *static_cast<GC::Cell*>(cell);- // NB: The task's captures, which the collector scans, keep the function alive until the steps run.- HTML::queue_a_task(HTML::Task::Source::DatabaseAccess, nullptr, nullptr, GC::create_function(GC::Heap::the(), [function, steps] {+ // NB: The task's captures, which the collector traces, keep the function alive until the steps run.+ HTML::queue_a_task(HTML::Task::Source::DatabaseAccess, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(function, steps), [](auto& function, auto& steps) {steps(JS::HostABI::vm_to_abi(JS::VM::the()), function.ptr());}));}@@ -97,8 +97,8 @@ void web_indexed_db_queue_a_database_task(void* cell, void (*steps)(JSVM*, void*void web_indexed_db_run_in_parallel(void* cell, void (*steps)(JSVM*, void*)){GC::Ref<GC::Cell> function = *static_cast<GC::Cell*>(cell);- // NB: The function's captures, which the collector scans, keep the cell alive until the steps run.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [function, steps] {+ // NB: The function's captures, which the collector traces, keep the cell alive until the steps run.+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(function, steps), [](auto& function, auto& steps) {steps(JS::HostABI::vm_to_abi(JS::VM::the()), function.ptr());}));}diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 54bd0514bce..6bcb9d764cf 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -756,7 +756,7 @@ void Internals::send_mouse_events_through_ui_process(Vector<Web::MouseEvent> eveauto unhandled_events = make_ref_counted<MouseEventsTheUIProcessHasNotHandledYet>();unhandled_events->count = events.size();for (auto& event : events) {- page.client().page_did_request_webdriver_mouse_event(local_root_id, move(event), GC::create_function(heap(), [&realm, promise, unhandled_events] {+ page.client().page_did_request_webdriver_mouse_event(local_root_id, move(event), GC::create_function(heap(), GC::captures(realm, promise, unhandled_events), [](auto& realm, auto& promise, auto& unhandled_events) {if (--unhandled_events->count != 0)return;HTML::TemporaryExecutionContext execution_context { realm };@@ -819,17 +819,17 @@ void Internals::perform_actions(Utf16String const& json, GC::Ref<WebIDL::Promiselet_compositor_take_in_every_rendered_frame(window());m_actions_running = true;auto executor = WebDriver::dispatch_actions(input_state, actions.release_value(), *window().associated_document().browsing_context(), options,- GC::create_function(heap(), [this, promise, realm = GC::Ref { realm }](WebDriver::Response response) {- HTML::TemporaryExecutionContext context { *realm };- m_actions_running = false;- m_actions_executor = {};+ GC::create_function(heap(), GC::captures(*this, promise, realm), [](auto& self, auto& promise, auto& realm, WebDriver::Response response) {+ HTML::TemporaryExecutionContext context { realm };+ self.m_actions_running = false;+ self.m_actions_executor = {};if (response.is_error())- WebIDL::reject_promise(*realm, promise, JS::PrimitiveString::create(realm->vm(), Utf16String::from_utf8(response.error().message)));+ WebIDL::reject_promise(realm, promise, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(response.error().message)));else- WebIDL::resolve_promise(*realm, promise);- if (m_pending_action_test_result.has_value()) {- auto text = m_pending_action_test_result.release_value();- signal_test_is_done(text);+ WebIDL::resolve_promise(realm, promise);+ if (self.m_pending_action_test_result.has_value()) {+ auto text = self.m_pending_action_test_result.release_value();+ self.signal_test_is_done(text);}}));if (m_actions_running)@@ -1000,11 +1000,14 @@ void Internals::wheel(GC::Ref<WebIDL::Promise> promise, double x, double y, doubnavigable->wait_for_wheel_scrolls(scroll_promises);}auto& realm = window().principal_realm();- auto resolve = [&realm, promise] {+ auto resolve = GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(realm, promise);- };- WebIDL::wait_for_all(realm, scroll_promises, [resolve](auto const&) { resolve(); }, [resolve](auto) { resolve(); });+ });+ WebIDL::wait_for_all(+ realm, scroll_promises,+ GC::create_function(GC::Heap::the(), GC::captures(resolve), [](auto& resolve, Vector<JS::Value> const&) { resolve->function()(); }),+ GC::create_function(GC::Heap::the(), GC::captures(resolve), [](auto& resolve, JS::Value) { resolve->function()(); }));}void Internals::wheel(double x, double y, double delta_x, double delta_y, bool precise, Bindings::ScrollGesturePhase phase, Bindings::WheelTicks const& ticks, GC::Ref<WebIDL::Promise> promise)@@ -2440,7 +2443,7 @@ GC::Ref<WebIDL::Promise> Internals::flush_session_history_traversal_queue()navigable->page().history_executor().request_history_operation(FlushSessionHistoryTraversalQueueOperationParameters {},{- .on_complete = GC::create_function(heap(), [&realm, promise] {+ .on_complete = GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(promise);}),@@ -2550,7 +2553,7 @@ GC::Ref<WebIDL::Promise> Internals::request_permission(Utf16String const& name)auto& realm = window().principal_realm();auto promise = WebIDL::create_promise_for(window());auto& settings = window().associated_document().relevant_settings_object();- PermissionsAPI::request_permission_with_user_prompt({ name }, settings, GC::create_function(realm.heap(), [&realm, promise](PermissionsAPI::PermissionState state) {+ PermissionsAPI::request_permission_with_user_prompt({ name }, settings, GC::create_function(realm.heap(), GC::captures(realm, promise), [](auto& realm, auto& promise, PermissionsAPI::PermissionState state) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(realm, promise, JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(state)));}));@@ -2564,7 +2567,7 @@ static GC::Ref<WebIDL::Promise> apply_snapshot_then_resolve(HTML::Window& windowauto promise = WebIDL::create_promise_for(window);if (snapshot.has_value())PermissionsAPI::PermissionStore::the().apply_snapshot(snapshot.release_value());- HTML::queue_global_task(HTML::Task::Source::Permissions, window.associated_document().relevant_settings_object().global_object(), GC::create_function(window.heap(), [&window, promise] {+ HTML::queue_global_task(HTML::Task::Source::Permissions, window.associated_document().relevant_settings_object().global_object(), GC::create_function(window.heap(), GC::captures(window, promise), [](auto& window, auto& promise) {auto& realm = window.principal_realm();HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(realm, promise);@@ -3705,7 +3708,7 @@ GC::Ref<Streams::ReadableStream> Internals::create_stream_pulling_from_bytes(Strauto stream = Streams::ReadableStream::create(realm);auto unpulled = make_ref_counted<UnpulledBytes>(MUST(ByteBuffer::copy(bytes.bytes())));- auto pull_algorithm = GC::create_function(realm.heap(), [realm = GC::Ref { realm }, stream, unpulled, pull_size] {+ auto pull_algorithm = GC::create_function(realm.heap(), GC::captures(GC::Ref { realm }, stream, unpulled, pull_size), [](auto& realm, auto& stream, auto& unpulled, auto& pull_size) {auto& remaining = unpulled->bytes;auto size = min(remaining.size(), static_cast<size_t>(pull_size));if (auto view_byte_length = stream->current_byob_request_view_byte_length(); view_byte_length.has_value())@@ -3813,7 +3816,7 @@ GC::Ref<WebIDL::Promise> Internals::check_spelling_for_testing(Utf16String constWebIDL::reject_promise(realm, promise, JS::PrimitiveString::create(vm(), "Spellchecking is unavailable"_utf16));return promise;}- page.request_spell_check(text, GC::create_function(heap(), [&realm, promise](Vector<SpellingError> errors) {+ page.request_spell_check(text, GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise, Vector<SpellingError> errors) {HTML::TemporaryExecutionContext execution_context { realm };StringBuilder builder;for (auto const& error : errors) {@@ -3830,7 +3833,7 @@ GC::Ref<WebIDL::Promise> Internals::spell_check_settled(){auto& realm = window().principal_realm();auto promise = WebIDL::create_promise_for(window());- page().when_spell_checking_settled(GC::create_function(heap(), [&realm, promise] {+ page().when_spell_checking_settled(GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(promise);}));@@ -3846,7 +3849,7 @@ GC::Ref<WebIDL::Promise> Internals::translation_settled(){auto& realm = window().principal_realm();auto promise = WebIDL::create_promise_for(window());- page().when_translation_settled(GC::create_function(heap(), [&realm, promise] {+ page().when_translation_settled(GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(promise);}));@@ -3862,7 +3865,7 @@ GC::Ref<WebIDL::Promise> Internals::request_writing_suggestion_for_testing(Utf16WebIDL::reject_promise(realm, promise, JS::PrimitiveString::create(vm(), "Writing suggestions are unavailable"_utf16));return promise;}- page.request_writing_suggestion(text, caret_offset, GC::create_function(heap(), [&realm, promise](Optional<WritingSuggestion> suggestion) {+ page.request_writing_suggestion(text, caret_offset, GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise, Optional<WritingSuggestion> suggestion) {HTML::TemporaryExecutionContext execution_context { realm };auto result = suggestion.has_value()? Utf16String::formatted("{}-{}:{}", suggestion->replacement_start, suggestion->replacement_length, suggestion->text)@@ -3890,7 +3893,7 @@ GC::Ref<WebIDL::Promise> Internals::writing_suggestion_settled(){auto& realm = window().principal_realm();auto promise = WebIDL::create_promise_for(window());- page().when_writing_suggestions_settled(GC::create_function(heap(), [&realm, promise] {+ page().when_writing_suggestions_settled(GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(promise);}));@@ -3901,7 +3904,7 @@ GC::Ref<WebIDL::Promise> Internals::writing_suggestion_request_sent(){auto& realm = window().principal_realm();auto promise = WebIDL::create_promise_for(window());- page().when_writing_suggestion_requested(GC::create_function(heap(), [&realm, promise] {+ page().when_writing_suggestion_requested(GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(promise);}));@@ -3925,7 +3928,7 @@ GC::Ref<WebIDL::Promise> Internals::activate_spelling_menu_item(Bindings::Spelli}VERIFY_NOT_REACHED();}();- page().request_spelling_menu_action_for_testing(action, guess_index, GC::create_function(heap(), [&realm, promise](String menu) {+ page().request_spelling_menu_action_for_testing(action, guess_index, GC::create_function(heap(), GC::captures(realm, promise), [](auto& realm, auto& promise, String menu) {HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(realm, promise, JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(menu)));}));diff --git a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cppindex 8ba89985284..559d6cfc371 100644--- a/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp+++ b/Libraries/LibWeb/IntersectionObserver/IntersectionObserver.cpp@@ -34,7 +34,7 @@ GC_DEFINE_ALLOCATOR(IntersectionObserver);GC::Ref<WebIDL::CallbackType> create_lazy_load_intersection_observer_callback(DOM::Document& document){auto& realm = document.relevant_settings_object().realm();- auto callback = JS::NativeFunction::create(realm, Utf16FlyString {}, [&document](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto callback = JS::NativeFunction::create(realm, Utf16FlyString {}, GC::create_function(GC::Heap::the(), GC::captures(document), [](DOM::Document& document, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {auto& entries = as<JS::Array>(vm.argument(0).as_object());auto entries_length = MUST(MUST(entries.get(vm.names.length)).to_length(vm));@@ -49,7 +49,7 @@ GC::Ref<WebIDL::CallbackType> create_lazy_load_intersection_observer_callback(DOdocument.process_lazy_load_intersection_observer_entries(intersection_observer_entries);return JS::js_undefined();- });+ }));return GC::Heap::the().allocate<WebIDL::CallbackType>(callback, realm);}diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cppindex 0d75a017e9f..9fd5f7fdbae 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp@@ -31,6 +31,9 @@#include <LibWeb/Platform/Timer.h>#include <LibWebCommon/Loader/UserAgent.h>+// NB: A load request keeps its page in a GC::Root, and holds no other cell.+GC_UNTRACED_CAPTURE(Web::LoadRequest);+namespace Web {static RefPtr<ResourceLoader>& resource_loader()@@ -401,8 +404,8 @@ void ResourceLoader::handle_file_load_request(LoadRequest& request, FileHandlerpage->client().request_file(move(file_request));}-template<typename ResourceHandler, typename ErrorHandler>-void ResourceLoader::handle_about_load_request(LoadRequest const& request, ResourceHandler on_resource, ErrorHandler on_error)+template<typename ResourceHandler>+void ResourceLoader::handle_about_load_request(LoadRequest const& request, ResourceHandler on_resource, GC::Ref<GC::Function<void(ByteString const&)>> on_error){auto const& url = request.url().value();@@ -430,9 +433,8 @@ void ResourceLoader::handle_about_load_request(LoadRequest const& request, Resou}Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(- m_heap,- [on_error, error_message = ByteString::formatted("No such about page: {}", serialized_path)]() {- on_error(error_message);+ m_heap, GC::captures(on_error, ByteString::formatted("No such about page: {}", serialized_path)), [](auto& on_error, auto& error_message) {+ on_error->function()(error_message);}));}@@ -500,11 +502,11 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&on_data_received->function()(Requests::ResponseData::from_bytes(data));on_complete->function()(true, timing_info, {});},- [on_complete, request](ByteString const& message) {+ GC::create_function(m_heap, GC::captures(on_complete, request), [](auto& on_complete, auto& request, ByteString const& message) {log_failure(request, message);Requests::RequestTimingInfo fixme_implement_timing_info {};on_complete->function()(false, fixme_implement_timing_info, StringView(message));- });+ }));return nullptr;}diff --git a/Libraries/LibWeb/Loader/ResourceLoader.h b/Libraries/LibWeb/Loader/ResourceLoader.hindex f5e8bbc8d4c..3329ad060cd 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.h+++ b/Libraries/LibWeb/Loader/ResourceLoader.h@@ -86,8 +86,8 @@ private:};template<typename FileHandler, typename ErrorHandler>void handle_file_load_request(LoadRequest& request, FileHandler on_file, ErrorHandler on_error);- template<typename ResourceHandler, typename ErrorHandler>- void handle_about_load_request(LoadRequest const& request, ResourceHandler on_resource, ErrorHandler on_error);+ template<typename ResourceHandler>+ void handle_about_load_request(LoadRequest const& request, ResourceHandler on_resource, GC::Ref<GC::Function<void(ByteString const&)>> on_error);template<typename ResourceHandler, typename ErrorHandler>void handle_resource_load_request(LoadRequest const& request, ResourceHandler on_resource, ErrorHandler on_error);diff --git a/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.cpp b/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.cppindex ce55ee0236e..a9354ce587d 100644--- a/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.cpp+++ b/Libraries/LibWeb/MediaCapabilitiesAPI/MediaCapabilities.cpp@@ -19,14 +19,16 @@#include <LibWeb/WebIDL/Promise.h>#include <LibWebCommon/MimeSniff/MimeType.h>+GC_UNTRACED_CAPTURE(Media::DecoderCapabilities);+namespace Web::MediaCapabilitiesAPI {// https://w3c.github.io/media-capabilities/#queue-a-media-capabilities-task-static void queue_a_media_capabilities_task(JS::Object& global_object, Function<void()> steps)+static void queue_a_media_capabilities_task(JS::Object& global_object, GC::Ref<GC::Function<void()>> steps){// When an algorithm queues a Media Capabilities task T, the user agent MUST queue a global task T on the// media capabilities task source using the global object of the the current realm record.- HTML::queue_global_task(HTML::Task::Source::MediaCapabilities, global_object, GC::create_function(GC::Heap::the(), move(steps)));+ HTML::queue_global_task(HTML::Task::Source::MediaCapabilities, global_object, steps);}// https://w3c.github.io/media-capabilities/#valid-mediaconfiguration@@ -220,12 +222,12 @@ void MediaCapabilities::decoding_info(MediaDecodingConfiguration const& configur// 1. Run the Create a MediaCapabilitiesDecodingInfo algorithm with configuration.// 2. Queue a Media Capabilities task to resolve p with its result.- queue_a_media_capabilities_task(WebIDL::promise_realm(*pending_promise).global_object(), [promise = GC::Root { *pending_promise }, configuration, capabilities] {+ queue_a_media_capabilities_task(WebIDL::promise_realm(*pending_promise).global_object(), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *pending_promise }, configuration, capabilities), [](auto& promise, auto& configuration, auto& capabilities) {auto& realm = WebIDL::promise_realm(*promise);HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);auto result = Bindings::media_capabilities_decoding_info_to_value(realm, create_a_media_capabilities_decoding_info(configuration, capabilities));WebIDL::resolve_promise(*promise, result);- });+ }));};request_media_decoding_capabilities(configuration)->when_resolved([resolve_with_capabilities](Optional<Media::DecoderCapabilities>& capabilities) {diff --git a/Libraries/LibWeb/MediaCapture/MediaDevices.cpp b/Libraries/LibWeb/MediaCapture/MediaDevices.cppindex 25163fc2b65..54cd54d9ebf 100644--- a/Libraries/LibWeb/MediaCapture/MediaDevices.cpp+++ b/Libraries/LibWeb/MediaCapture/MediaDevices.cpp@@ -85,10 +85,10 @@ MediaDevices::MediaDevices(HTML::Window& window)void MediaDevices::initialize_pending_request_state_change_listener(){auto& realm = m_window->principal_realm();- auto pending_request_state_change_callback_function = JS::NativeFunction::create(realm, [media_devices = GC::Ref(*this)](JS::VM&) {- media_devices->process_pending_enumerate_devices_requests();- media_devices->process_pending_get_user_media_requests();- return JS::js_undefined(); }, 0, Utf16FlyString {}, &realm);+ auto pending_request_state_change_callback_function = JS::NativeFunction::create(realm, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& media_devices, JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {+ media_devices.process_pending_enumerate_devices_requests();+ media_devices.process_pending_get_user_media_requests();+ return JS::js_undefined(); }), 0, Utf16FlyString {}, &realm);auto pending_request_state_change_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*pending_request_state_change_callback_function, realm);m_pending_request_state_change_listener = DOM::IDLEventListener::create(pending_request_state_change_callback);@@ -186,7 +186,7 @@ void MediaDevices::system_focus_changed()// 11.7 While hasSystemFocus is false, the User Agent MUST wait to proceed to the next step until a task queued to set// hasSystemFocus to the result of the has system focus algorithm, would set hasSystemFocus to true.HTML::queue_global_task(HTML::Task::Source::UserInteraction, HTML::relevant_global_object(*m_window),- GC::create_function(heap(), [media_devices = GC::Ref(*this)] {+ GC::create_function(heap(), GC::captures(GC::Ref(*this)), [](auto& media_devices) {media_devices->process_pending_enumerate_devices_requests();media_devices->process_pending_get_user_media_requests();}));@@ -401,7 +401,7 @@ void MediaDevices::queue_get_user_media_task(GC::Ref<WebIDL::Promise> promise, O// FIXME: Add camera/videoauto audio_input_devices = Audio::AudioDevices::the().input_devices();- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [promise = GC::Root(promise), media_devices, device_id_constraint = move(device_id_constraint), audio_input_devices = move(audio_input_devices)] mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(GC::Root(promise), media_devices, move(device_id_constraint), move(audio_input_devices)), [](auto& promise, auto& media_devices, auto& device_id_constraint, auto& audio_input_devices) {auto& realm = WebIDL::promise_realm(*promise);HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -470,7 +470,7 @@ void MediaDevices::queue_get_user_media_task(GC::Ref<WebIDL::Promise> promise, O// 11.5 For each media type kind in requestedMediaTypes, run the following sub steps, preferably at the same time.// 11.5.1 Request permission to use a PermissionDescriptor with its name member set to the permission name associated with kind.auto& settings_object = HTML::relevant_settings_object(*media_devices->m_window);- PermissionsAPI::request_permission_with_user_prompt(microphone_permission, settings_object, GC::create_function(GC::Heap::the(), [promise, media_devices, device_id_constraint, stream](PermissionsAPI::PermissionState microphone_permission_result) {+ PermissionsAPI::request_permission_with_user_prompt(microphone_permission, settings_object, GC::create_function(GC::Heap::the(), GC::captures(promise, media_devices, device_id_constraint, stream), [](auto& promise, auto& media_devices, auto& device_id_constraint, auto& stream, PermissionsAPI::PermissionState microphone_permission_result) {auto& realm = WebIDL::promise_realm(*promise);HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -489,7 +489,7 @@ void MediaDevices::queue_get_user_media_task(GC::Ref<WebIDL::Promise> promise, O// AD-HOC: The input devices' names and ids reach this process only once the Browser has told its AudioServer// of the grant, so finalSet is gathered again from a list fetched after it.- media_devices->run_with_fresh_audio_device_list(GC::create_function(GC::Heap::the(), [promise, media_devices, device_id_constraint, stream] {+ media_devices->run_with_fresh_audio_device_list(GC::create_function(GC::Heap::the(), GC::captures(promise, media_devices, device_id_constraint, stream), [](auto& promise, auto& media_devices, auto& device_id_constraint, auto& stream) {auto& realm = WebIDL::promise_realm(*promise);HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -583,7 +583,7 @@ void MediaDevices::queue_enumerate_devices_task(GC::Ref<WebIDL::Promise> promise{GC::Ref<MediaDevices> media_devices = *this;- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [promise = GC::Root(promise), media_devices] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(GC::Root(promise), media_devices), [](auto& promise, auto& media_devices) {auto& realm = WebIDL::promise_realm(*promise);HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -665,11 +665,10 @@ void MediaDevices::run_device_change_notification_steps(Vector<StoredDevice> conauto& relevant_global_object = HTML::relevant_global_object(*m_window);HTML::queue_global_task(HTML::Task::Source::DOMManipulation,relevant_global_object,- GC::create_function(GC::Heap::the(),- [media_devices = GC::Ref(*this), relevant_global_object = GC::Ref(relevant_global_object)] {- media_devices->dispatch_event(DOM::Event::create(HTML::EventNames::devicechange,- HighResolutionTime::current_high_resolution_time(*relevant_global_object)));- }));+ GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), GC::Ref(relevant_global_object)), [](auto& media_devices, auto& relevant_global_object) {+ media_devices->dispatch_event(DOM::Event::create(HTML::EventNames::devicechange,+ HighResolutionTime::current_high_resolution_time(*relevant_global_object)));+ }));}// https://w3c.github.io/mediacapture-main/#dom-mediadevices-getusermedia@@ -880,7 +879,7 @@ void MediaDevices::end_tracks(GC::RootVector<GC::Ref<MediaStreamTrack>> tracks_t// When a MediaStreamTrack track ends for any reason other than the stop() method being invoked, the User Agent// MUST queue a task that runs the following steps:HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(*m_window),- GC::create_function(heap(), [tracks = move(tracks_to_end), window = m_window] {+ GC::create_function(heap(), GC::captures(move(tracks_to_end), m_window), [](auto& tracks, auto& window) {HTML::TemporaryExecutionContext execution_context { window->principal_realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If the track's [[ReadyState]] slot has the value "ended", abort these steps.// 2. Set track's [[ReadyState]] slot to "ended".diff --git a/Libraries/LibWeb/MediaCapture/MediaDevices.h b/Libraries/LibWeb/MediaCapture/MediaDevices.hindex a9f5ee0f8bf..186f87be932 100644--- a/Libraries/LibWeb/MediaCapture/MediaDevices.h+++ b/Libraries/LibWeb/MediaCapture/MediaDevices.h@@ -128,3 +128,5 @@ private:};}++GC_UNTRACED_CAPTURE(Web::MediaCapture::DeviceIdConstraint);diff --git a/Libraries/LibWeb/MediaSourceExtensions/MediaSource.cpp b/Libraries/LibWeb/MediaSourceExtensions/MediaSource.cppindex 084d344b4df..e48fc6f094e 100644--- a/Libraries/LibWeb/MediaSourceExtensions/MediaSource.cpp+++ b/Libraries/LibWeb/MediaSourceExtensions/MediaSource.cpp@@ -107,9 +107,9 @@ void MediaSource::set_ready_state_to_open_and_fire_sourceopen_event()source_buffer.clear_reached_end_of_stream({});}- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- auto event = create_associated_event(EventNames::sourceopen);- dispatch_event(event);+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ auto event = self.create_associated_event(EventNames::sourceopen);+ self.dispatch_event(event);}));}@@ -152,7 +152,7 @@ void MediaSource::detach_from_media_element(Badge<HTML::HTMLMediaElement>)m_active_source_buffers->remove_all_buffers({});// 7. Queue a task to fire an event named removesourcebuffer at activeSourceBuffers.- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_active_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_active_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::removesourcebuffer));}));@@ -160,13 +160,13 @@ void MediaSource::detach_from_media_element(Badge<HTML::HTMLMediaElement>)m_source_buffers->remove_all_buffers({});// 9. Queue a task to fire an event named removesourcebuffer at sourceBuffers.- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::removesourcebuffer));}));// 10. Queue a task to fire an event named sourceclose at the MediaSource.- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(create_associated_event(EventNames::sourceclose));+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.create_associated_event(EventNames::sourceclose));}));// AD-HOC: Sever the media element assignment that was established when this MediaSource was attached.@@ -204,7 +204,7 @@ void MediaSource::selected_video_track_changed(Badge<HTML::VideoTrack>, GC::Ptr<m_active_source_buffers->remove(*previously_selected_track_source_buffer);// 2. Queue a task to fire an event named removesourcebuffer at activeSourceBuffers- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_active_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_active_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::removesourcebuffer));}));}@@ -216,7 +216,7 @@ void MediaSource::selected_video_track_changed(Badge<HTML::VideoTrack>, GC::Ptr<m_active_source_buffers->insert_in_order_of(*newly_selected_track_source_buffer, m_source_buffers);// 2. Queue a task to fire an event named addsourcebuffer at activeSourceBuffers- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_active_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_active_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::addsourcebuffer));}));}@@ -232,7 +232,7 @@ void MediaSource::audio_track_enabled_changed(Badge<HTML::AudioTrack>, SourceBufm_active_source_buffers->remove(source_buffer);// 2. Queue a task to fire an event named removesourcebuffer at activeSourceBuffers- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_active_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_active_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::removesourcebuffer));}));}@@ -244,7 +244,7 @@ void MediaSource::audio_track_enabled_changed(Badge<HTML::AudioTrack>, SourceBufm_active_source_buffers->insert_in_order_of(source_buffer, m_source_buffers);// 2. Queue a task to fire an event named addsourcebuffer at activeSourceBuffers- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_active_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_active_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::addsourcebuffer));}));}@@ -330,7 +330,7 @@ WebIDL::ExceptionOr<GC::Ref<SourceBuffer>> MediaSource::add_source_buffer(Utf16Sm_source_buffers->append(buffer);// 9. Queue a task to fire an event named addsourcebuffer at this's sourceBuffers.- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [media_source = GC::Ref(*this), source_buffers = m_source_buffers] {+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*this), m_source_buffers), [](auto& media_source, auto& source_buffers) {source_buffers->dispatch_event(media_source->create_associated_event(EventNames::addsourcebuffer));}));@@ -366,8 +366,8 @@ void MediaSource::run_end_of_stream_algorithm(Optional<EndOfStreamError> const&m_ready_state = ReadyState::Ended;// 2. Queue a task to fire an event named sourceended at the MediaSource.- queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(create_associated_event(EventNames::sourceended));+ queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.create_associated_event(EventNames::sourceended));}));// AD-HOC: Notify all demuxers that end of stream was reached, so that they can return the requisite error anddiff --git a/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cpp b/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cppindex c1c6e0d2b30..3f861a781ef 100644--- a/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cpp+++ b/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cpp@@ -504,16 +504,16 @@ WebIDL::ExceptionOr<void> SourceBuffer::append_buffer(WebIDL::BufferSourceVarianset_updating(true);// 4. Queue a task to fire an event named updatestart at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updatestart));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updatestart));}));// 5. Asynchronously run the buffer append algorithm.// NB: The queued task captures the current append generation, so a bump by abort_buffer_append_algorithm()// before the task runs makes the task do nothing; see run_buffer_append_algorithm().m_remote_source_buffer->enqueue_append(move(appended_data));- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this, append_generation = m_append_generation] {- run_buffer_append_algorithm(append_generation);+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this, m_append_generation), [](auto& self, auto& append_generation) {+ self.run_buffer_append_algorithm(append_generation);}));return {};@@ -544,13 +544,13 @@ void SourceBuffer::abort_if_updating(Badge<MediaSource>)set_updating(false);// 2.3. Queue a task to fire an event named abort at sourceBuffer.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::abort));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::abort));}));// 2.4. Queue a task to fire an event named updateend at sourceBuffer.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updateend));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updateend));}));}@@ -580,13 +580,13 @@ WebIDL::ExceptionOr<void> SourceBuffer::abort()set_updating(false);// 4.3. Queue a task to fire an event named abort at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::abort));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::abort));}));// 4.4. Queue a task to fire an event named updateend at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updateend));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updateend));}));}@@ -737,22 +737,22 @@ void SourceBuffer::run_range_removal(AK::Duration start, AK::Duration end)set_updating(true);// 4. Queue a task to fire an event named updatestart at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updatestart));+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updatestart));}));// 5. Return control to the caller and run the rest of the steps asynchronously.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [this, start, end] {+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(*this, start, end), [](auto& self, auto& start, auto& end) {// NB: Removing this SourceBuffer from the parent media source runs the removeSourceBuffer() steps, which abort// this algorithm and fire the abort and updateend events in place of the ones below.- if (!m_media_source->source_buffers()->contains(*this)) {- m_range_removal_running = false;+ if (!self.m_media_source->source_buffers()->contains(self)) {+ self.m_range_removal_running = false;return;}// 6. Run the coded frame removal algorithm with start and end as the start and end of the removal range.// NB: The media server reports its completion, which runs finish_range_removal() for the remaining steps.- m_remote_source_buffer->remove_coded_frames(start, end);+ self.m_remote_source_buffer->remove_coded_frames(start, end);}));}@@ -774,13 +774,13 @@ void SourceBuffer::finish_range_removal()set_updating(false);// 8. Queue a task to fire an event named update at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::update));+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::update));}));// 9. Queue a task to fire an event named updateend at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updateend));+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updateend));}));}@@ -794,13 +794,13 @@ void SourceBuffer::run_append_error_algorithm()set_updating(false);// 3. Queue a task to fire an event named error at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::error));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::error));}));// 4. Queue a task to fire an event named updateend at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updateend));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updateend));}));// 5. Run the end of stream algorithm with the error parameter set to "decode".@@ -864,7 +864,7 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Track// NOTE: This should trigger AudioTrackList [HTML] logic to queue a task to fire an event named// addtrack using TrackEvent with the track attribute initialized to new audio track, at the// AudioTrackList object referenced by the audioTracks attribute on this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [media_source = m_media_source, audio_tracks = m_audio_tracks, new_audio_track] {+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(m_media_source, m_audio_tracks, new_audio_track), [](auto& media_source, auto& audio_tracks, auto& new_audio_track) {dispatch_addtrack_event(media_source->relevant_global_object(), audio_tracks, new_audio_track);}));@@ -880,9 +880,9 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Track// addtrack using TrackEvent with the track attribute initialized to mirrored audio track or new// audio track, at the AudioTrackList object referenced by the audioTracks attribute on the// HTMLMediaElement.- m_media_source->media_element_assigned_to()->queue_a_media_element_task([new_audio_track](HTML::HTMLMediaElement& media_element) {+ m_media_source->media_element_assigned_to()->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(new_audio_track), [](auto& new_audio_track, HTML::HTMLMediaElement& media_element) {dispatch_addtrack_event(HTML::relevant_global_object(media_element), media_element.audio_tracks(), new_audio_track);- });+ }));}// 7. Create a new track buffer to store coded frames for this track.@@ -936,7 +936,7 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Track// NOTE: This should trigger VideoTrackList [HTML] logic to queue a task to fire an event named addtrack// using TrackEvent with the track attribute initialized to new video track, at the VideoTrackList// object referenced by the videoTracks attribute on this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [media_source = m_media_source, video_tracks = m_video_tracks, new_video_track] {+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(m_media_source, m_video_tracks, new_video_track), [](auto& media_source, auto& video_tracks, auto& new_video_track) {dispatch_addtrack_event(media_source->relevant_global_object(), video_tracks, new_video_track);}));@@ -952,9 +952,9 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Track// using TrackEvent with the track attribute initialized to mirrored video track or new video// track, at the VideoTrackList object referenced by the videoTracks attribute on the// HTMLMediaElement.- m_media_source->media_element_assigned_to()->queue_a_media_element_task([new_video_track](HTML::HTMLMediaElement& media_element) {+ m_media_source->media_element_assigned_to()->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(new_video_track), [](auto& new_video_track, HTML::HTMLMediaElement& media_element) {dispatch_addtrack_event(HTML::relevant_global_object(media_element), media_element.video_tracks(), new_video_track);- });+ }));}// 7. Create a new track buffer to store coded frames for this track.@@ -1012,7 +1012,7 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Track// NOTE: This should trigger TextTrackList [HTML] logic to queue a task to fire an event named addtrack// using TrackEvent with the track attribute initialized to new text track, at the TextTrackList// object referenced by the textTracks attribute on this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(heap(), [media_source = m_media_source, text_tracks = m_text_tracks, new_text_track] {+ m_media_source->queue_a_media_source_task(GC::create_function(heap(), GC::captures(m_media_source, m_text_tracks, new_text_track), [](auto& media_source, auto& text_tracks, auto& new_text_track) {dispatch_addtrack_event(media_source->relevant_global_object(), text_tracks, new_text_track);}));@@ -1027,9 +1027,9 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Track// NOTE: This should trigger TextTrackList [HTML] logic to queue a task to fire an event named addtrack// using TrackEvent with the track attribute initialized to mirrored text track or new text track,// at the TextTrackList object referenced by the textTracks attribute on the HTMLMediaElement.- m_media_source->media_element_assigned_to()->queue_a_media_element_task([new_text_track](HTML::HTMLMediaElement& media_element) {+ m_media_source->media_element_assigned_to()->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(new_text_track), [](auto& new_text_track, HTML::HTMLMediaElement& media_element) {dispatch_addtrack_event(HTML::relevant_global_object(media_element), media_element.text_tracks(), new_text_track);- });+ }));}// 7. Create a new track buffer to store coded frames for this track.@@ -1045,10 +1045,9 @@ void SourceBuffer::on_first_initialization_segment_processed(Vector<Media::Trackm_media_source->active_source_buffers()->insert_in_order_of(*this, m_media_source->source_buffers());// 2. Queue a task to fire an event named addsourcebuffer at activeSourceBuffers.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(),- [media_source = GC::Ref(*m_media_source), source_buffers = m_media_source->active_source_buffers()] {- source_buffers->dispatch_event(media_source->create_associated_event(EventNames::addsourcebuffer));- }));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(*m_media_source), m_media_source->active_source_buffers()), [](auto& media_source, auto& source_buffers) {+ source_buffers->dispatch_event(media_source->create_associated_event(EventNames::addsourcebuffer));+ }));}// 6. Set [[first initialization segment received flag]] to true.@@ -1107,13 +1106,13 @@ void SourceBuffer::finish_buffer_append()set_updating(false);// 4. Queue a task to fire an event named update at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::update));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::update));}));// 5. Queue a task to fire an event named updateend at this SourceBuffer object.- m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {- dispatch_event(m_media_source->create_associated_event(EventNames::updateend));+ m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.dispatch_event(self.m_media_source->create_associated_event(EventNames::updateend));}));}diff --git a/Libraries/LibWeb/NotificationsAPI/Notification.cpp b/Libraries/LibWeb/NotificationsAPI/Notification.cppindex 8a529a8fa90..6a76ed5d455 100644--- a/Libraries/LibWeb/NotificationsAPI/Notification.cpp+++ b/Libraries/LibWeb/NotificationsAPI/Notification.cpp@@ -277,7 +277,7 @@ WebIDL::ExceptionOr<GC::Ref<Notification>> Notification::create_with_global_scop// AD-HOC: The steps run from a task on the relevant global instead of in parallel: Showing crosses to the UI// process asynchronously anyway, and a task keeps the permission read and the event firing on the main// thread, after the constructor's caller has had its turn to attach event handlers.- HTML::queue_global_task(HTML::Task::Source::Unspecified, relevant_global_object, GC::create_function(GC::Heap::the(), [this_notification] {+ HTML::queue_global_task(HTML::Task::Source::Unspecified, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(this_notification), [](auto& this_notification) {this_notification->run_steps_in_parallel_after_construction();}));@@ -332,18 +332,18 @@ void Notification::show_steps()// be set (if any), as well as the icon resources for the notification's actions (if any).// AD-HOC: The wait for the fetch is bounded: An icon that hasn't arrived after a few seconds isn't worth holding// the notification back for, so it then shows without one.- m_fetch_timeout = Platform::Timer::create_single_shot(heap(), icon_fetch_timeout, GC::create_function(heap(), [this] {- if (m_icon_fetch_controller)- m_icon_fetch_controller->stop_fetch();- m_icon_fetch_controller = nullptr;- display();+ m_fetch_timeout = Platform::Timer::create_single_shot(heap(), icon_fetch_timeout, GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ if (self.m_icon_fetch_controller)+ self.m_icon_fetch_controller->stop_fetch();+ self.m_icon_fetch_controller = nullptr;+ self.display();}));m_fetch_timeout->start();- run_the_fetch_steps(GC::create_function(heap(), [this] {- if (!m_fetch_timeout)+ run_the_fetch_steps(GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ if (!self.m_fetch_timeout)return;- m_fetch_timeout->stop();- display();+ self.m_fetch_timeout->stop();+ self.display();}));}@@ -362,8 +362,8 @@ void Notification::run_the_fetch_steps(GC::Ref<GC::Function<void()>> on_done)on_done->function()();return;}- fetch_a_notification_resource(*m_notification.icon_url, GC::create_function(heap(), [this, on_done](RefPtr<Gfx::Bitmap const> resource) {- m_icon_resource = move(resource);+ fetch_a_notification_resource(*m_notification.icon_url, GC::create_function(heap(), GC::captures(*this, on_done), [](auto& self, auto& on_done, RefPtr<Gfx::Bitmap const> resource) {+ self.m_icon_resource = move(resource);on_done->function()();}));@@ -399,12 +399,12 @@ void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GC// 3. Fetch request with useParallelQueue set to true and processResponseConsumeBody set to the following steps// given a response response and null, failure, or a byte sequence bytes:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response_consume_body = [this, process_resource](GC::Ref<Fetch::Infrastructure::ResponseView>, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bytes) {- m_icon_fetch_controller = nullptr;+ fetch_algorithms_input.process_response_consume_body = GC::create_function(heap(), GC::captures(*this, process_resource), [](auto& self, auto& process_resource, GC::Ref<Fetch::Infrastructure::ResponseView>, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bytes) {+ self.m_icon_fetch_controller = nullptr;// The bytes are here, so the wait is no longer on the network: Decoding them finishes on its own, however// long a busy machine takes over it.- if (m_fetch_timeout)- m_fetch_timeout->stop();+ if (self.m_fetch_timeout)+ self.m_fetch_timeout->stop();// 1. If bytes is null or failure, then return.// AD-HOC: The show steps wait on this fetch, so an absent resource is reported as such, rather than left@@ -419,7 +419,7 @@ void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GC// NB: The decoder answers from outside the heap's view, so the notification and the step it hands the// resource to are rooted for the wait: Nothing else holds the step once the fetch is over. An answer for a// notification that's gone in the meantime is dropped.- auto on_decoded = [self = GC::Root(*this), process_resource = GC::Root(*process_resource)](Platform::DecodedImage& decoded_image) -> ErrorOr<void> {+ auto on_decoded = [self = GC::Root(self), process_resource = GC::Root(*process_resource)](Platform::DecodedImage& decoded_image) -> ErrorOr<void> {// NB: Only the first frame is used, so an animation the decoder opened is stopped right away.if (decoded_image.session_id != 0)Platform::ImageCodecPlugin::the().stop_animation_decode(decoded_image.session_id);@@ -447,13 +447,13 @@ void Notification::fetch_a_notification_resource(URL::URL const& url, GC::Ref<GCprocess_resource->function()(move(bitmap));return {};};- auto on_decode_failed = [self = GC::Root(*this), process_resource = GC::Root(*process_resource)](Error&) {+ auto on_decode_failed = [self = GC::Root(self), process_resource = GC::Root(*process_resource)](Error&) {if (self->m_state != State::Pending)return;process_resource->function()(nullptr);};(void)Platform::ImageCodecPlugin::the().decode_image(bytes.get<Core::ImmutableBytes>().bytes(), move(on_decoded), move(on_decode_failed));- };+ });m_icon_fetch_controller = Fetch::Fetching::fetch(settings.realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);}@@ -549,19 +549,19 @@ void Notification::did_click()return;// Otherwise, queue a task to run these steps:- HTML::queue_global_task(HTML::Task::Source::UserInteraction, *m_relevant_global, GC::create_function(GC::Heap::the(), [this] {+ HTML::queue_global_task(HTML::Task::Source::UserInteraction, *m_relevant_global, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 1. Let intoFocus be the result of firing an event named click on the Notification object representing// notification, with its cancelable attribute initialized to true.// NB: The user activated the notification, so the window gets transient activation first: That's what lets// focus() work from within the event listener, as the spec encourages.- if (auto* window = HTML::window_from_global_object(*m_relevant_global))- window->set_last_activation_timestamp(HighResolutionTime::current_high_resolution_time(*m_relevant_global));- auto into_focus = dispatch_event(DOM::Event::create(*m_relevant_global, HTML::EventNames::click, { .cancelable = true }));+ if (auto* window = HTML::window_from_global_object(*self.m_relevant_global))+ window->set_last_activation_timestamp(HighResolutionTime::current_high_resolution_time(*self.m_relevant_global));+ auto into_focus = self.dispatch_event(DOM::Event::create(*self.m_relevant_global, HTML::EventNames::click, { .cancelable = true }));// 2. If intoFocus is true, then the user agent should bring the notification's related browsing context's// viewport into focus.- if (m_page)- m_page->client().page_did_handle_notification_click(m_id, into_focus);+ if (self.m_page)+ self.m_page->client().page_did_handle_notification_click(self.m_id, into_focus);}));}@@ -606,8 +606,8 @@ void Notification::did_close(bool)void Notification::queue_task_to_fire_event(Utf16FlyString const& event_name){- HTML::queue_global_task(HTML::Task::Source::Unspecified, *m_relevant_global, GC::create_function(GC::Heap::the(), [this, event_name] {- dispatch_event(DOM::Event::create(*m_relevant_global, event_name));+ HTML::queue_global_task(HTML::Task::Source::Unspecified, *m_relevant_global, GC::create_function(GC::Heap::the(), GC::captures(*this, event_name), [](auto& self, auto& event_name) {+ self.dispatch_event(DOM::Event::create(*self.m_relevant_global, event_name));}));}@@ -680,12 +680,12 @@ GC::Ref<WebIDL::Promise> Notification::request_permission(GC::Ptr<WebIDL::Callba// 3. Run these steps in parallel:// 1. Let permissionState be the result of requesting permission to use "notifications".// 2. Queue a global task on the DOM manipulation task source given global to run these steps:- auto settle = GC::create_function(realm.heap(), [&realm, global, promise, deprecated_callback, settings = GC::Ref(settings)](PermissionsAPI::PermissionState) {+ auto settle = GC::create_function(realm.heap(), GC::captures(realm, global, promise, deprecated_callback, GC::Ref(settings)), [](auto& realm, auto& global, auto& promise, auto& deprecated_callback, auto& settings, PermissionsAPI::PermissionState) {// AD-HOC: "Request permission to use" reports "denied" for a prompt the user dismissed, though it stores nothing// for it, and the page would then take a shrug for a refusal. The state the store holds once the// answer is in is reported instead: "default" after a dismissal, so the page may ask again later.auto permission_state = get_the_notifications_permission_state(settings);- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, GC::create_function(realm.heap(), [&realm, promise, deprecated_callback, permission_state] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, GC::create_function(realm.heap(), GC::captures(realm, promise, deprecated_callback, permission_state), [](auto& realm, auto& promise, auto& deprecated_callback, auto& permission_state) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };auto permission = JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(notification_permission_from(permission_state)));diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex bb5119afdaa..536b4221643 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -2845,7 +2845,7 @@ EventResult EventHandler::perform_paste_action()// NB: The system clipboard lives in the UI process. So, retrieve its contents first — and run the rest of the paste// action once the contents arrive.- document->page().request_clipboard_entries(GC::create_function(document->heap(), [document = GC::Ref { *document }](Vector<Clipboard::SystemClipboardItem> items) {+ document->page().request_clipboard_entries(GC::create_function(document->heap(), GC::captures(GC::Ref { *document }), [](auto& document, Vector<Clipboard::SystemClipboardItem> items) {auto data_store = HTML::DragDataStore::create();auto add_text_item = [&](Utf16FlyString type, Utf16String data) {diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex d6ea0e108e6..cfe9e11e5cb 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -1167,11 +1167,11 @@ void Page::discard()m_local_roots_left_to_discard = navigables.size();for (auto const& navigable : navigables) {- auto detach_navigable = GC::create_function(heap(), [this, navigable] {+ auto detach_navigable = GC::create_function(heap(), GC::captures(*this, navigable), [](Page& page, GC::Ref<HTML::LocalNavigable> navigable) {navigable->set_has_been_destroyed();navigable->remove_from_all_local_navigables();- if (--m_local_roots_left_to_discard == 0)- finish_discarding();+ if (--page.m_local_roots_left_to_discard == 0)+ page.finish_discarding();});// NB: The task destroying a document only runs while the document is fully active, so its navigable can only@@ -1244,14 +1244,16 @@ void Page::did_complete_window_rect_request(u64 completion_id)m_window_rect_observer->function()({ window_position(), window_size() }, completion_id);}-template<typename ResponseType>-static ResponseType spin_event_loop_until_dialog_closed(PageClient& client, Optional<ResponseType>& response, HTML::EventLoop* event_loop = nullptr, SourceLocation location = SourceLocation::current())+// NB: The response is named as a member of the page, so that the function waiting for it captures only the page.+template<auto response>+static auto spin_event_loop_until_dialog_closed(Page& page, HTML::EventLoop* event_loop = nullptr, SourceLocation location = SourceLocation::current()){+ auto& client = page.client();auto& responsible_event_loop = event_loop ? *event_loop : Web::HTML::current_settings_object().responsible_event_loop();auto pause_handle = responsible_event_loop.pause();- Web::Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), [&]() {- return response.has_value() || !client.is_connection_open();+ Web::Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), GC::captures(page), [](Page& page) {+ return (page.*response).has_value() || !page.client().is_connection_open();}));if (!client.is_connection_open()) {@@ -1259,7 +1261,7 @@ static ResponseType spin_event_loop_until_dialog_closed(PageClient& client, Optiexit(0);}- return response.release_value();+ return (page.*response).release_value();}void Page::did_request_alert(Utf16String const& message)@@ -1270,7 +1272,7 @@ void Page::did_request_alert(Utf16String const& message)if (!message.is_empty())m_pending_dialog_text = message;- spin_event_loop_until_dialog_closed(*m_client, m_pending_alert_response);+ spin_event_loop_until_dialog_closed<&Page::m_pending_alert_response>(*this);}void Page::alert_closed()@@ -1286,7 +1288,7 @@ bool Page::did_request_before_unload(String const& source, HTML::EventLoop& evenm_pending_dialog = PendingDialog::BeforeUnload;m_client->page_did_request_before_unload(source);- return spin_event_loop_until_dialog_closed(*m_client, m_pending_before_unload_response, &event_loop);+ return spin_event_loop_until_dialog_closed<&Page::m_pending_before_unload_response>(*this, &event_loop);}void Page::before_unload_closed(bool accepted)@@ -1305,7 +1307,7 @@ bool Page::did_request_confirm(Utf16String const& message)if (!message.is_empty())m_pending_dialog_text = message;- return spin_event_loop_until_dialog_closed(*m_client, m_pending_confirm_response);+ return spin_event_loop_until_dialog_closed<&Page::m_pending_confirm_response>(*this);}void Page::confirm_closed(bool accepted)@@ -1324,7 +1326,7 @@ Optional<Utf16String> Page::did_request_prompt(Utf16String const& message, Utf16if (!message.is_empty())m_pending_dialog_text = message;- return spin_event_loop_until_dialog_closed(*m_client, m_pending_prompt_response);+ return spin_event_loop_until_dialog_closed<&Page::m_pending_prompt_response>(*this);}void Page::prompt_closed(Optional<Utf16String> response)@@ -2429,8 +2431,8 @@ void Page::enqueue_fullscreen_enter(GC::Ref<DOM::Element> element, GC::Ref<DOM::m_pending_fullscreen_operations.enqueue(PendingFullscreenEnter { element, pending_doc, error, promise, request_type });// NOTE: Processing is deferred because the spec says "run the remaining steps in parallel",// meaning the caller's synchronous JS should complete before we process the operation.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this]() {- process_pending_fullscreen_operations();+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this), [](Page& self) {+ self.process_pending_fullscreen_operations();}));}@@ -2439,8 +2441,8 @@ void Page::enqueue_fullscreen_exit(GC::Ref<DOM::Document> doc, bool resize, GC::m_pending_fullscreen_operations.enqueue(PendingFullscreenExit { doc, resize, promise, requesting_navigable_id });// NOTE: Processing is deferred because the spec says "run the remaining steps in parallel",// meaning the caller's synchronous JS should complete before we process the operation.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this]() {- process_pending_fullscreen_operations();+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this), [](Page& self) {+ self.process_pending_fullscreen_operations();}));}diff --git a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cpp b/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cppindex 186bd4835b6..8d14eaa7230 100644--- a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cpp+++ b/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cpp@@ -81,13 +81,13 @@ void PermissionStatus::update_from_store()return;// NB: The state is read again when the task runs, so a status that heard of several changes ends with the last.- HTML::queue_global_task(HTML::Task::Source::Permissions, global, GC::create_function(heap(), [this] {- auto& global = relevant_global_object();- auto state = permission_state(m_query, HTML::relevant_settings_object(global));- if (state == m_state)+ HTML::queue_global_task(HTML::Task::Source::Permissions, global, GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ auto& global = self.relevant_global_object();+ auto state = permission_state(self.m_query, HTML::relevant_settings_object(global));+ if (state == self.m_state)return;- m_state = state;- dispatch_event(DOM::Event::create(global, HTML::EventNames::change));+ self.m_state = state;+ self.dispatch_event(DOM::Event::create(global, HTML::EventNames::change));}));}diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp b/Libraries/LibWeb/PermissionsAPI/Permissions.cppindex c6ea9ecd587..aa85f30de3e 100644--- a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp@@ -79,7 +79,7 @@ static void store_permission_decision(PermissionDescriptor const& descriptor, HTPermissionStore::the().set_permission_store_entry(descriptor, key, current_state);// 7. Queue a task on the current settings object's responsible event loop to set a permission store entry with descriptor, key, and current state.- HTML::queue_global_task(HTML::Task::Source::Permissions, settings.global_object(), GC::create_function(GC::Heap::the(), [descriptor, key, current_state] {+ HTML::queue_global_task(HTML::Task::Source::Permissions, settings.global_object(), GC::create_function(GC::Heap::the(), GC::captures(descriptor, key, current_state), [](auto& descriptor, auto& key, auto& current_state) {PermissionStore::the().set_permission_store_entry(descriptor, key, current_state);}));}@@ -104,7 +104,7 @@ void request_permission_with_user_prompt(PermissionDescriptor const& descriptor,return;}- auto settle = GC::create_function(GC::Heap::the(), [descriptor, settings = GC::Ref(settings), on_decided](Web::Permissions::EffectiveState answer) {+ auto settle = GC::create_function(GC::Heap::the(), GC::captures(descriptor, GC::Ref(settings), on_decided), [](auto& descriptor, auto& settings, auto& on_decided, Web::Permissions::EffectiveState answer) {// 4. If the user gives express permission to use the powerful feature, set current state to "granted"; otherwise to "denied".// The user's interaction may provide new information about the user's intent for the origin.// AD-HOC: A prompt the user dismisses or ignores leaves the permission at "prompt", rather than storing "denied";@@ -234,7 +234,7 @@ void Permissions::query(GC::Ref<JS::Object> permission_desc, GC::Ref<WebIDL::Propermission_query_algorithm(query, status, HTML::relevant_settings_object(relevant_global_object));// 4. Queue a global task on the permissions task source with this's relevant global object to resolve promise with status.- HTML::queue_global_task(HTML::Task::Source::Permissions, relevant_global_object, GC::create_function(GC::Heap::the(), [relevant_global_object = GC::Ref(relevant_global_object), promise, status]() mutable {+ HTML::queue_global_task(HTML::Task::Source::Permissions, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(relevant_global_object), promise, status), [](auto& relevant_global_object, auto& promise, auto& status) {auto& realm = HTML::relevant_realm(relevant_global_object);HTML::TemporaryExecutionContext execution_context { realm };WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, status));diff --git a/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cppindex a69b20b1be4..e8536b4a679 100644--- a/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp+++ b/Libraries/LibWeb/PictureInPicture/PictureInPictureController.cpp@@ -112,7 +112,7 @@ void PictureInPictureController::process_pending_operations()// AD-HOC: There is no media element to take the task source from, so this uses the DOM// manipulation task source. The promise is rejected, as the overhaul's reviewers asked.if (exit.promise) {- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(*exit.document), GC::create_function(GC::Heap::the(), [promise = GC::Ref { *exit.promise }] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(*exit.document), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *exit.promise }), [](auto& promise) {reject_promise_with_invalid_state_error(promise, "There is no Picture-in-Picture element to exit"_utf16);}));}@@ -167,7 +167,7 @@ void PictureInPictureController::run_request_steps(Request const& request)if (video.is_picture_in_picture_element()) {// 1. Queue a global task on the media element event task source given global to resolve p with the// Picture-in-Picture window associated with this.- HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), [video = request.video, promise = request.promise] {+ HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), GC::captures(request.video, request.promise), [](auto& video, auto& promise) {if (video->take_pending_picture_in_picture_promise(promise))resolve_promise(promise, video->picture_in_picture_window());}));@@ -193,7 +193,7 @@ void PictureInPictureController::run_request_steps(Request const& request)if (!new_web_view.page) {// 1. Queue a global task on the media element event task source given global to reject p with// InvalidStateError DOMException.- HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), [video = request.video, promise = request.promise] {+ HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), GC::captures(request.video, request.promise), [](auto& video, auto& promise) {if (video->take_pending_picture_in_picture_promise(promise))reject_promise_with_invalid_state_error(promise, "Unable to open a Picture-in-Picture window"_utf16);}));@@ -255,13 +255,13 @@ void PictureInPictureController::did_open_window(Gfx::IntSize window_size)}// 6. Queue a global task on the media element event task source given global, to perform the following steps:- HTML::queue_global_task(video.media_element_event_task_source(), global, GC::create_function(GC::Heap::the(), [this, video = request.video, promise = request.promise, picture_in_picture_window] {+ HTML::queue_global_task(video.media_element_event_task_source(), global, GC::create_function(GC::Heap::the(), GC::captures(*this, request.video, request.promise, picture_in_picture_window), [](auto& self, auto& video, auto& promise, auto& picture_in_picture_window) {auto& document = video->document();// NB: When the disable Picture-in-Picture steps rejected p while the window opened, it is closed again// rather than entered.if (!video->take_pending_picture_in_picture_promise(promise)) {- close_window(picture_in_picture_window, WindowIsOpenInUserInterface::Yes);+ self.close_window(picture_in_picture_window, WindowIsOpenInUserInterface::Yes);return;}@@ -305,7 +305,7 @@ void PictureInPictureController::run_exit_steps(DOM::Document& document, GC::Ptrclose_window(*video.picture_in_picture_window(), window_is_open_in_user_interface);// 4. Queue a global task on the media element event task source given global, to perform the following steps:- HTML::queue_global_task(video.media_element_event_task_source(), global, GC::create_function(GC::Heap::the(), [document = GC::Ref { document }, promise] {+ HTML::queue_global_task(video.media_element_event_task_source(), global, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { document }, promise), [](auto& document, auto& promise) {// 1. If doc is not fully active or doc's Picture-in-Picture element is null:if (!document->is_fully_active() || !document->picture_in_picture_element()) {// 1. If p is not null, resolve p with undefined.@@ -364,7 +364,7 @@ void PictureInPictureController::window_did_resize(Gfx::IntSize window_size)// When the size of a Picture-in-Picture window pipWindow changes, the user agent MUST queue a task to fire an// event named resize at pipWindow.auto& video = m_open_window->video();- HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), [window = GC::Ref { *m_open_window }] {+ HTML::queue_global_task(video.media_element_event_task_source(), HTML::relevant_global_object(video), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *m_open_window }), [](auto& window) {window->dispatch_event(DOM::Event::create(HTML::relevant_global_object(window->video()), HTML::EventNames::resize));}));}diff --git a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp b/Libraries/LibWeb/SVG/SVGDecodedImageData.cppindex f26b8ae39f3..2cb0ede91f4 100644--- a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp+++ b/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp@@ -32,6 +32,15 @@namespace Web::SVG {+struct DocumentObserverRoot : RefCounted<DocumentObserverRoot> {+ explicit DocumentObserverRoot(DOM::DocumentObserver& observer)+ : observer(observer)+ {+ }++ GC::Root<DOM::DocumentObserver> observer;+};+GC_DEFINE_ALLOCATOR(SVGDecodedImageData);GC_DEFINE_ALLOCATOR(SVGDecodedImageData::SVGPageClient);@@ -157,12 +166,14 @@ NonnullRefPtr<SVGDecodedImageData::DecodePromise> SVGDecodedImageData::decode(GCauto promise = DecodePromise::construct();auto observer = DOM::DocumentObserver::create(*document);// Keep the loading state alive until the document finishes loading its internal resources.- observer->set_document_completely_loaded([page_client, document, svg_root = GC::Ref { *svg_root }, observer = GC::Root { observer }, promise] {- observer->set_document_completely_loaded(nullptr);+ // NB: The observer's own function cannot keep the observer alive, as what it captures is traced from the observer.+ auto observer_root = make_ref_counted<DocumentObserverRoot>(*observer);+ observer->set_document_completely_loaded(GC::create_function(GC::Heap::the(), GC::captures(page_client, document, GC::Ref { *svg_root }, move(observer_root), promise), [](auto& page_client, auto& document, auto& svg_root, auto& observer_root, auto& promise) {+ observer_root->observer->set_document_completely_loaded(nullptr);auto svg_image_data = create(page_client->page(), page_client, document, svg_root);page_client->register_svg_image_data(svg_image_data);promise->resolve(svg_image_data);- });+ }));return promise;}@@ -544,7 +555,7 @@ void SVGDecodedImageData::did_request_frame()if (m_has_pending_client_notification)return;m_has_pending_client_notification = true;- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), [self = GC::Ref { *this }] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), GC::captures(GC::Ref { *this }), [](auto& self) {self->m_has_pending_client_notification = false;self->notify_clients_did_update();}));diff --git a/Libraries/LibWeb/SVG/SVGFEImageElement.cpp b/Libraries/LibWeb/SVG/SVGFEImageElement.cppindex 7858134860b..aeac9f4d103 100644--- a/Libraries/LibWeb/SVG/SVGFEImageElement.cpp+++ b/Libraries/LibWeb/SVG/SVGFEImageElement.cpp@@ -86,11 +86,11 @@ void SVGFEImageElement::process_href(Optional<Utf16String> const& href)m_resource_request = HTML::SharedResourceRequest::get_or_create(document(), *m_href, HTML::CORSSettingAttribute::NoCORS);m_resource_request->add_callbacks(- [this, resource_request = GC::Root { m_resource_request }] {- document().note_svg_paint_resources_changed();- document().schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::EveryBox);- document().set_needs_repaint(Badge<SVGFEImageElement> {}, InvalidateDisplayList::PaintCommands);- },+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](SVGFEImageElement& self) {+ self.document().note_svg_paint_resources_changed();+ self.document().schedule_full_accumulated_visual_context_rebuild(Layout::RustFFI::VisualContextUpdateScope::EveryBox);+ self.document().set_needs_repaint(Badge<SVGFEImageElement> {}, InvalidateDisplayList::PaintCommands);+ }),nullptr);if (m_resource_request->needs_fetching()) {diff --git a/Libraries/LibWeb/SVG/SVGImageElement.cpp b/Libraries/LibWeb/SVG/SVGImageElement.cppindex b75221b880a..084aa10e6b2 100644--- a/Libraries/LibWeb/SVG/SVGImageElement.cpp+++ b/Libraries/LibWeb/SVG/SVGImageElement.cpp@@ -162,40 +162,40 @@ void SVGImageElement::fetch_the_document(URL::URL const& url)// must not fire events or release the load event delayer of the current request. Shared resource requests// are shared per URL and CORS mode, so each fetch gets its own ID instead of comparing requests.resource_request->add_callbacks(- [this, fetch_id] {- if (fetch_id != m_current_fetch_id)+ GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, fetch_id), [](SVGImageElement& self, auto& fetch_id) {+ if (fetch_id != self.m_current_fetch_id)return;- m_load_event_delayer.clear();- register_with_decoded_image_data_if_needed();- CSS::record_element_replaced_content_input(*this);- Painting::push_replaced_image_paint_facts(*this, *this);- set_needs_layout_update(DOM::SetNeedsLayoutReason::SVGImageElementFetchTheDocument);+ self.m_load_event_delayer.clear();+ self.register_with_decoded_image_data_if_needed();+ CSS::record_element_replaced_content_input(self);+ Painting::push_replaced_image_paint_facts(self, self);+ self.set_needs_layout_update(DOM::SetNeedsLayoutReason::SVGImageElementFetchTheDocument);// https://w3c.github.io/paint-timing/#sec-modifications-dom// When an Element element's associated image request has become completely available, run the algorithm// to process an image that finished loading passing in element and its associated image request as// inputs.- PaintTiming::process_an_image_that_finished_loading(*this, PaintTiming::image_request_info(Utf16String::from_utf8(m_resource_request->url().serialize()), m_resource_request->image_data()));+ PaintTiming::process_an_image_that_finished_loading(self, PaintTiming::image_request_info(Utf16String::from_utf8(self.m_resource_request->url().serialize()), self.m_resource_request->image_data()));- dispatch_event(DOM::Event::create(HTML::EventNames::load,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));- },- [this, fetch_id] {- if (fetch_id != m_current_fetch_id)+ self.dispatch_event(DOM::Event::create(HTML::EventNames::load,+ HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self))));+ }),+ GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, fetch_id), [](SVGImageElement& self, auto& fetch_id) {+ if (fetch_id != self.m_current_fetch_id)return;- m_load_event_delayer.clear();+ self.m_load_event_delayer.clear();- dispatch_event(DOM::Event::create(HTML::EventNames::error,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));- },- [this, fetch_id] {- if (fetch_id != m_current_fetch_id)+ self.dispatch_event(DOM::Event::create(HTML::EventNames::error,+ HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(self))));+ }),+ GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, fetch_id), [](SVGImageElement& self, auto& fetch_id) {+ if (fetch_id != self.m_current_fetch_id)return;- m_load_event_delayer.clear();- });+ self.m_load_event_delayer.clear();+ }));// NB: A request that has already completed runs its callbacks right away, and an event handler can change href.// Then this fetch is no longer the current one.diff --git a/Libraries/LibWeb/SVG/SVGUseElement.cpp b/Libraries/LibWeb/SVG/SVGUseElement.cppindex 11da6d16fee..d25f95950bf 100644--- a/Libraries/LibWeb/SVG/SVGUseElement.cpp+++ b/Libraries/LibWeb/SVG/SVGUseElement.cpp@@ -47,16 +47,16 @@ void SVGUseElement::initialize_element()set_shadow_root(shadow_root);m_document_observer = DOM::DocumentObserver::create(document());- m_document_observer->set_document_readiness_observer([this](HTML::DocumentReadyState readiness) {+ m_document_observer->set_document_readiness_observer(GC::create_function(GC::Heap::the(), GC::captures(*this), [](SVGUseElement& self, HTML::DocumentReadyState readiness) {if (readiness != HTML::DocumentReadyState::Interactive)return;// The href processing path already populated the shadow tree for resolved references,// unless the referenced subtree changed while the document was still being parsed.- if (instance_root() && !m_needs_parsing_complete_reclone)+ if (self.instance_root() && !self.m_needs_parsing_complete_reclone)return;- m_needs_parsing_complete_reclone = false;- clone_element_tree_as_our_shadow_tree(referenced_element());- });+ self.m_needs_parsing_complete_reclone = false;+ self.clone_element_tree_as_our_shadow_tree(self.referenced_element());+ }));}void SVGUseElement::visit_edges(Cell::Visitor& visitor)@@ -371,18 +371,18 @@ void SVGUseElement::fetch_the_document(URL::URL const& url)m_load_event_delayer.emplace(document());m_resource_request = HTML::SharedResourceRequest::get_or_create(document(), *request);m_resource_request_callbacks_id = m_resource_request->add_removable_callbacks(- [this] {+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](SVGUseElement& self) {// Only a connected use element builds its shadow tree; inserted() builds it otherwise.- if (is_connected())- clone_element_tree_as_our_shadow_tree(referenced_element());- m_load_event_delayer.clear();- },- [this] {- m_load_event_delayer.clear();- },- [this] {- m_load_event_delayer.clear();- });+ if (self.is_connected())+ self.clone_element_tree_as_our_shadow_tree(self.referenced_element());+ self.m_load_event_delayer.clear();+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](SVGUseElement& self) {+ self.m_load_event_delayer.clear();+ }),+ GC::create_function(GC::Heap::the(), GC::captures(*this), [](SVGUseElement& self) {+ self.m_load_event_delayer.clear();+ }));if (m_resource_request->needs_fetching())m_resource_request->fetch_resource(request);diff --git a/Libraries/LibWeb/ServiceWorker/Cache.cpp b/Libraries/LibWeb/ServiceWorker/Cache.cppindex efdb0d58748..d31bc35b080 100644--- a/Libraries/LibWeb/ServiceWorker/Cache.cpp+++ b/Libraries/LibWeb/ServiceWorker/Cache.cpp@@ -65,16 +65,16 @@ void Cache::visit_edges(GC::Cell::Visitor& visitor)void Cache::match(JS::Realm& realm, Fetch::RequestInfo request, CacheQueryOptions options, GC::Ref<WebIDL::Promise> promise){// 2. Run these substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, promise, request = move(request), options]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, promise, move(request), options), [](auto& self, auto& realm, auto& promise, auto& request, auto& options) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Let p be the result of running the algorithm specified in matchAll(request, options) method with request and options.// 2. Wait until p settles.auto match_all_promise = WebIDL::create_promise(realm);- match_all(realm, move(request), options, match_all_promise);+ self.match_all(realm, move(request), options, match_all_promise);WebIDL::react_to_promise(match_all_promise,// 4. Else if p resolves with an array, responses, then:- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If responses is an empty array, then:@@ -93,7 +93,7 @@ void Cache::match(JS::Realm& realm, Fetch::RequestInfo request, CacheQueryOption}),// 3. If p rejects with an exception, then:- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value exception) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value exception) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Reject promise with that exception.@@ -154,14 +154,14 @@ void Cache::match_all(JS::Realm& realm, Optional<Fetch::RequestInfo> request, Ca}// 5. Run these substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, inner_request, promise, request = move(request), options]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, inner_request, promise, move(request), options), [](auto& self, auto& realm, auto& inner_request, auto& promise, auto& request, auto& options) {// 1. Let responses be an empty list.auto responses = GC::Heap::the().allocate<GC::HeapVector<GC::Ref<Fetch::Infrastructure::ResponseView>>>();// 2. If the optional argument request is omitted, then:if (!request.has_value()) {// 1. For each requestResponse of the relevant request response list:- for (auto& request_response : m_request_response_list->elements()) {+ for (auto& request_response : self.m_request_response_list->elements()) {// 1. Add a copy of requestResponse’s response to responses.responses->elements().append(request_response->response->clone(realm));}@@ -169,7 +169,7 @@ void Cache::match_all(JS::Realm& realm, Optional<Fetch::RequestInfo> request, Ca// 3. Else:else {// 1. Let requestResponses be the result of running Query Cache with r and options.- auto request_responses = query_cache(realm, *inner_request, options);+ auto request_responses = self.query_cache(realm, *inner_request, options);// 2. For each requestResponse of requestResponses:for (auto request_response : request_responses->elements()) {@@ -195,7 +195,7 @@ void Cache::match_all(JS::Realm& realm, Optional<Fetch::RequestInfo> request, CaHTML::Task::Source::DOMManipulation,HTML::relevant_settings_object(promise->promise()).responsible_event_loop(),{},- GC::create_function(GC::Heap::the(), [&realm, promise, responses]() {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise, responses), [](auto& realm, auto& promise, auto& responses) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };resolve_cache_response_list(realm, promise, responses);@@ -214,11 +214,11 @@ void Cache::add(JS::Realm& realm, Fetch::RequestInfo request, GC::Ref<WebIDL::Pr// 3. Return the result of reacting to responseArrayPromise with a fulfillment handler that returns undefined.WebIDL::react_to_promise(add_all_promise,- GC::create_function(GC::Heap::the(), [promise](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {WebIDL::resolve_promise(promise);return JS::js_undefined();}),- GC::create_function(GC::Heap::the(), [promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {WebIDL::reject_promise(promise, reason);return JS::js_undefined();}));@@ -286,12 +286,12 @@ void Cache::add_all(JS::Realm& realm, ReadonlySpan<Fetch::RequestInfo> requests,auto response_promise = WebIDL::create_promise(realm);// 6. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, fetch_controllers, inner_request, response_promise]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, fetch_controllers, inner_request, response_promise), [](auto& realm, auto& fetch_controllers, auto& inner_request, auto& response_promise) {// * Append the result of fetching r.Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };// * To processResponse for response, run these substeps:- fetch_algorithms_input.process_response = [&realm, fetch_controllers, response_promise](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(realm, fetch_controllers, response_promise), [](auto& realm, auto& fetch_controllers, auto& response_promise, GC::Ref<Fetch::Infrastructure::ResponseView> response) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };bool did_reject_promise = false;@@ -343,7 +343,7 @@ void Cache::add_all(JS::Realm& realm, ReadonlySpan<Fetch::RequestInfo> requests,// 2. Resolve responsePromise with response.WebIDL::resolve_promise(response_promise, response);- };+ });auto fetch_controller = Fetch::Fetching::fetch(realm, inner_request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));fetch_controllers->elements().append(fetch_controller);@@ -360,7 +360,7 @@ void Cache::add_all(JS::Realm& realm, ReadonlySpan<Fetch::RequestInfo> requests,// 7. Return the result of reacting to p with a fulfillment handler that, when called with argument responses, performs the following substeps:WebIDL::react_to_promise(wait_for_responses_promise,- GC::create_function(GC::Heap::the(), [this, &realm, request_list = move(request_list), promise](JS::Value result) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(*this, realm, move(request_list), promise), [](auto& self, auto& realm, auto& request_list, auto& promise, JS::Value result) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context { realm };auto& responses = result.as<JS::Array>();@@ -390,11 +390,11 @@ void Cache::add_all(JS::Realm& realm, ReadonlySpan<Fetch::RequestInfo> requests,// 5. Let cacheJobPromise be a new promise.// 6. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, operations, promise]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(self, realm, operations, promise), [](auto& self, auto& realm, auto& operations, auto& promise) {// 1. Let errorData be null.// 2. Invoke Batch Cache Operations with operations. If this throws an exception, set errorData to the// exception.- auto error_data = batch_cache_operations(realm, operations);+ auto error_data = self.batch_cache_operations(realm, operations);// 3. Queue a task, on cacheJobPromise’s relevant settings object’s responsible event loop using the DOM// manipulation task source, to perform the following substeps:@@ -402,7 +402,7 @@ void Cache::add_all(JS::Realm& realm, ReadonlySpan<Fetch::RequestInfo> requests,HTML::Task::Source::DOMManipulation,HTML::relevant_settings_object(promise->promise()).responsible_event_loop(),{},- GC::create_function(GC::Heap::the(), [&realm, promise, error_data = move(error_data)]() mutable {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(error_data)), [](auto& realm, auto& promise, auto& error_data) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If errorData is null, resolve cacheJobPromise with undefined.@@ -416,7 +416,7 @@ void Cache::add_all(JS::Realm& realm, ReadonlySpan<Fetch::RequestInfo> requests,return JS::js_undefined();}),- GC::create_function(GC::Heap::the(), [promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {WebIDL::reject_promise(promise, reason);return JS::js_undefined();}));@@ -533,14 +533,14 @@ void Cache::put(JS::Realm& realm, Fetch::RequestInfo request, GC::Ref<Fetch::Resoperations->elements().append(operation);// 19. Return the result of the fulfillment of bodyReadPromise:WebIDL::react_to_promise(body_read_promise,- GC::create_function(GC::Heap::the(), [this, &realm, operations, promise](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(*this, realm, operations, promise), [](auto& self, auto& realm, auto& operations, auto& promise, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context { realm };// 2. Return cacheJobPromise and run these steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, operations, promise]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(self, realm, operations, promise), [](auto& self, auto& realm, auto& operations, auto& promise) {// 1. Let errorData be null.// 2. Invoke Batch Cache Operations with operations. If this throws an exception, set errorData to the exception.- auto error_data = batch_cache_operations(realm, operations);+ auto error_data = self.batch_cache_operations(realm, operations);// 3. Queue a task, on cacheJobPromise’s relevant settings object’s responsible event loop using the DOM// manipulation task source, to perform the following substeps:@@ -548,7 +548,7 @@ void Cache::put(JS::Realm& realm, Fetch::RequestInfo request, GC::Ref<Fetch::ResHTML::Task::Source::DOMManipulation,HTML::relevant_settings_object(promise->promise()).responsible_event_loop(),{},- GC::create_function(GC::Heap::the(), [&realm, promise, error_data = move(error_data)]() mutable {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(error_data)), [](auto& realm, auto& promise, auto& error_data) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If errorData is null, resolve cacheJobPromise with undefined.@@ -562,7 +562,7 @@ void Cache::put(JS::Realm& realm, Fetch::RequestInfo request, GC::Ref<Fetch::Resreturn JS::js_undefined();}),- GC::create_function(GC::Heap::the(), [promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {WebIDL::reject_promise(promise, reason);return JS::js_undefined();}));@@ -629,11 +629,11 @@ void Cache::delete_(JS::Realm& realm, Fetch::RequestInfo request, CacheQueryOpti// 9. Append operation to operations.operations->elements().append(operation);// 12. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, operations, promise]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, operations, promise), [](auto& self, auto& realm, auto& operations, auto& promise) {// 1. Let errorData be null.// 2. Let requestResponses be the result of running Batch Cache Operations with operations. If this throws an// exception, set errorData to the exception.- auto error_data = batch_cache_operations(realm, operations);+ auto error_data = self.batch_cache_operations(realm, operations);// 3. Queue a task, on cacheJobPromise’s relevant settings object’s responsible event loop using the DOM// manipulation task source, to perform the following substeps:@@ -641,7 +641,7 @@ void Cache::delete_(JS::Realm& realm, Fetch::RequestInfo request, CacheQueryOptiHTML::Task::Source::DOMManipulation,HTML::relevant_settings_object(promise->promise()).responsible_event_loop(),{},- GC::create_function(GC::Heap::the(), [&realm, promise, error_data = move(error_data)]() mutable {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(error_data)), [](auto& realm, auto& promise, auto& error_data) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If errorData is null, then:@@ -708,14 +708,14 @@ void Cache::keys(JS::Realm& realm, Optional<Fetch::RequestInfo> request, CacheQu}// 5. Run these substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, inner_request, promise, request = move(request), options]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, inner_request, promise, move(request), options), [](auto& self, auto& realm, auto& inner_request, auto& promise, auto& request, auto& options) {// 1. Let requests be an empty list.Vector<NonnullRefPtr<Fetch::Infrastructure::Request>> requests;// 2. If the optional argument request is omitted, then:if (!request.has_value()) {// 1. For each requestResponse of the relevant request response list:- for (auto& request_response : m_request_response_list->elements()) {+ for (auto& request_response : self.m_request_response_list->elements()) {// 1. Add requestResponse’s request to requests.requests.append(request_response->request);}@@ -724,7 +724,7 @@ void Cache::keys(JS::Realm& realm, Optional<Fetch::RequestInfo> request, CacheQuelse {// 1. Let requestResponses be the result of running Query Cache with r and options.// NB: Only the requests are used, so we copy them below. Copying the responses would tee their bodies.- auto request_responses = query_cache(realm, *inner_request, options, {}, CloneCache::No);+ auto request_responses = self.query_cache(realm, *inner_request, options, {}, CloneCache::No);// 2. For each requestResponse of requestResponses:for (auto request_response : request_responses->elements()) {@@ -739,7 +739,7 @@ void Cache::keys(JS::Realm& realm, Optional<Fetch::RequestInfo> request, CacheQuHTML::Task::Source::DOMManipulation,HTML::relevant_settings_object(promise->promise()).responsible_event_loop(),{},- GC::create_function(GC::Heap::the(), [&realm, promise, requests = move(requests)]() {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise, move(requests)), [](auto& realm, auto& promise, auto& requests) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };resolve_cache_request_list(realm, promise, requests);diff --git a/Libraries/LibWeb/ServiceWorker/Cache.h b/Libraries/LibWeb/ServiceWorker/Cache.hindex 05791f18984..a7849e2b343 100644--- a/Libraries/LibWeb/ServiceWorker/Cache.h+++ b/Libraries/LibWeb/ServiceWorker/Cache.h@@ -8,6 +8,7 @@#include <AK/Optional.h>#include <AK/String.h>+#include <LibGC/Function.h>#include <LibWeb/Bindings/CacheStorage.h>#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Fetch/Request.h>diff --git a/Libraries/LibWeb/ServiceWorker/CacheStorage.cpp b/Libraries/LibWeb/ServiceWorker/CacheStorage.cppindex ca06f78289a..bd7cdd0df75 100644--- a/Libraries/LibWeb/ServiceWorker/CacheStorage.cpp+++ b/Libraries/LibWeb/ServiceWorker/CacheStorage.cpp@@ -36,12 +36,12 @@ void CacheStorage::match(JS::Realm& realm, Fetch::RequestInfo request, MultiCach// 1. If options["cacheName"] exists, then:if (options.cache_name.has_value()) {// 1. Return a new promise promise and run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, &realm, promise, request = move(request), options = move(options)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, promise, move(request), move(options)), [](auto& self, auto& realm, auto& promise, auto& request, auto& options) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. For each cacheName → cache of the relevant name to cache map:// 1. If options["cacheName"] matches cacheName, then:- if (auto result = relevant_name_to_cache_map().get(*options.cache_name); result.has_value()) {+ if (auto result = self.relevant_name_to_cache_map().get(*options.cache_name); result.has_value()) {// 1. Resolve promise with the result of running the algorithm specified in match(request, options)// method of Cache interface with request and options (providing cache as thisArgument to the// [[Call]] internal method of match(request, options).)@@ -67,7 +67,7 @@ void CacheStorage::match(JS::Realm& realm, Fetch::RequestInfo request, MultiCachfor (auto const& [cache_name, cache_list] : relevant_name_to_cache_map()) {// 1. Set promise to the result of reacting to itself with a fulfillment handler that, when called with// argument response, performs the following substeps:- internal_promise = WebIDL::upon_fulfillment(internal_promise, GC::create_function(GC::Heap::the(), [&realm, cache_list, request, options](JS::Value response) mutable -> WebIDL::ExceptionOr<JS::Value> {+ internal_promise = WebIDL::upon_fulfillment(internal_promise, GC::create_function(GC::Heap::the(), GC::captures(realm, cache_list, request, options), [](auto& realm, auto& cache_list, auto& request, auto& options, JS::Value response) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If response is not undefined, return response.@@ -85,11 +85,11 @@ void CacheStorage::match(JS::Realm& realm, Fetch::RequestInfo request, MultiCach}WebIDL::react_to_promise(internal_promise,- GC::create_function(GC::Heap::the(), [promise](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {WebIDL::resolve_promise(promise, value);return JS::js_undefined();}),- GC::create_function(GC::Heap::the(), [promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {WebIDL::reject_promise(promise, reason);return JS::js_undefined();}));@@ -100,13 +100,13 @@ void CacheStorage::match(JS::Realm& realm, Fetch::RequestInfo request, MultiCachvoid CacheStorage::has(JS::Realm& realm, Utf16String const& cache_name, GC::Ref<WebIDL::Promise> promise){// 2. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, this, promise, cache_name] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, promise, cache_name), [](auto& self, auto& realm, auto& promise, auto& cache_name) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. For each key -> value of the relevant name to cache map:// 1. If cacheName matches key, resolve promise with true and abort these steps.// 2. Resolve promise with false.- WebIDL::resolve_promise(promise, JS::Value { contains_cache(cache_name) });+ WebIDL::resolve_promise(promise, JS::Value { self.contains_cache(cache_name) });}));}@@ -114,7 +114,7 @@ void CacheStorage::has(JS::Realm& realm, Utf16String const& cache_name, GC::Ref<void CacheStorage::open(JS::Realm& realm, Utf16String const& cache_name, GC::Ref<WebIDL::Promise> promise){// 2. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, this, promise, cache_name] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, promise, cache_name), [](auto& self, auto& realm, auto& promise, auto& cache_name) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If cacheName matches an existing cache, resolve promise with a new Cache object that represents it.@@ -122,7 +122,7 @@ void CacheStorage::open(JS::Realm& realm, Utf16String const& cache_name, GC::Ref// If this cache write operation failed due to exceeding the granted quota limit, reject promise with a// QuotaExceededError and abort these steps.// FIXME: Handle cache quotas in CacheStorage::get_or_create_cache().- auto cache = get_or_create_cache(cache_name);+ auto cache = self.get_or_create_cache(cache_name);// 4. Resolve promise with a new Cache object that represents cache.auto cache_object = GC::Heap::the().allocate<Cache>(cache);@@ -134,12 +134,12 @@ void CacheStorage::open(JS::Realm& realm, Utf16String const& cache_name, GC::Refvoid CacheStorage::delete_(JS::Realm& realm, Utf16String const& cache_name, GC::Ref<WebIDL::Promise> promise){// 2. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, this, promise, cache_name] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, promise, cache_name), [](auto& self, auto& realm, auto& promise, auto& cache_name) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. If cacheName does not match an entry, resolve promise with false and abort these steps.// 2. Otherwise, remove the relevant name to cache map[cacheName] and resolve promise with true.- auto const removed_cache = delete_cache(cache_name);+ auto const removed_cache = self.delete_cache(cache_name);WebIDL::resolve_promise(promise, JS::Value { removed_cache });// Note: After this step, the existing DOM objects (i.e. the currently referenced Cache, Request, and Response@@ -151,11 +151,11 @@ void CacheStorage::delete_(JS::Realm& realm, Utf16String const& cache_name, GC::void CacheStorage::keys(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise){// 2. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, this, promise] {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, realm, promise), [](auto& self, auto& realm, auto& promise) {HTML::TemporaryExecutionContext context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Let cacheKeys be the result of getting the keys of the relevant name to cache map.- auto cache_keys = this->cache_keys();+ auto cache_keys = self.cache_keys();// Note: The items in the result ordered set are in the order that their corresponding entry was added to the// name to cache map.diff --git a/Libraries/LibWeb/ServiceWorker/Job.cpp b/Libraries/LibWeb/ServiceWorker/Job.cppindex bb443e29943..31fa92b6e56 100644--- a/Libraries/LibWeb/ServiceWorker/Job.cpp+++ b/Libraries/LibWeb/ServiceWorker/Job.cpp@@ -7,6 +7,7 @@#include <AK/HashMap.h>#include <AK/NeverDestroyed.h>#include <AK/NonnullOwnPtr.h>+#include <AK/RefCounted.h>#include <LibGC/Heap.h>#include <LibJS/Runtime/VM.h>#include <LibTextCodec/Decoder.h>@@ -156,22 +157,29 @@ static void register_(JS::VM& vm, GC::Ref<Job> job)}// Used to share internal Update algorithm state b/w fetch callbacks-class UpdateAlgorithmState : JS::Cell {+class UpdateAlgorithmState : public JS::Cell {GC_CELL(UpdateAlgorithmState, JS::Cell);GC_DECLARE_ALLOCATOR(UpdateAlgorithmState);public:- static GC::Ref<UpdateAlgorithmState> create()+ static GC::Ref<UpdateAlgorithmState> create(Registration& registration, ServiceWorkerRecord* newest_worker){- return GC::Heap::the().allocate<UpdateAlgorithmState>();+ return GC::Heap::the().allocate<UpdateAlgorithmState>(registration, newest_worker);}+ Registration& registration() const { return m_registration; }+ ServiceWorkerRecord* newest_worker() const { return m_newest_worker; }+OrderedHashMap<URL::URL, GC::Ref<Fetch::Infrastructure::ResponseView>>& updated_resource_map() { return m_map; }bool has_updated_resources() const { return m_has_updated_resources; }void set_has_updated_resources(bool b) { m_has_updated_resources = b; }private:- UpdateAlgorithmState() = default;+ UpdateAlgorithmState(Registration& registration, ServiceWorkerRecord* newest_worker)+ : m_registration(registration)+ , m_newest_worker(newest_worker)+ {+ }virtual void visit_edges(JS::Cell::Visitor& visitor) override{@@ -179,24 +187,40 @@ private:visitor.visit(m_map);}+ // NB: The registration and the newest worker are not GC-allocated. The fetch callbacks of the Update algorithm+ // reach them through this state.+ Registration& m_registration;+ ServiceWorkerRecord* m_newest_worker { nullptr };OrderedHashMap<URL::URL, GC::Ref<Fetch::Infrastructure::ResponseView>> m_map;bool m_has_updated_resources { false };};GC_DEFINE_ALLOCATOR(UpdateAlgorithmState);+// NB: The result of the processResponse steps of a job's top-level script fetch, which the perform the fetch hook+// waits for.+struct ProcessResponseCompletionResult : RefCounted<ProcessResponseCompletionResult> {+ void visit_edges(GC::Cell::Visitor& visitor) const+ {+ if (value.has_value())+ value->visit_edges(visitor);+ }++ Optional<WebIDL::ExceptionOr<void>> value;+};+// The consume-body steps of one of a job's script fetches. They run once: when the fetch consumes its body, or when it// is stopped.-class ScriptFetchConsumeBody : JS::Cell {+class ScriptFetchConsumeBody : public JS::Cell {GC_CELL(ScriptFetchConsumeBody, JS::Cell);GC_DECLARE_ALLOCATOR(ScriptFetchConsumeBody);public:using Steps = GC::Function<Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction::FunctionType>;- static GC::Ref<ScriptFetchConsumeBody> create(Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction steps)+ static GC::Ref<ScriptFetchConsumeBody> create(GC::Ref<Steps> steps){- return GC::Heap::the().allocate<ScriptFetchConsumeBody>(GC::create_function(GC::Heap::the(), move(steps)));+ return GC::Heap::the().allocate<ScriptFetchConsumeBody>(steps);}void run(GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes)@@ -224,9 +248,9 @@ GC_DEFINE_ALLOCATOR(ScriptFetchConsumeBody);static GC::Ref<Fetch::Infrastructure::FetchController> fetch_job_script(Job const& job, Fetch::Infrastructure::Request& request, Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input, GC::Ref<ScriptFetchConsumeBody> consume_body){- fetch_algorithms_input.process_response_consume_body = [consume_body](GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(consume_body), [](auto& consume_body, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {consume_body->run(response, move(body_bytes));- };+ });// FIXME: Soft-Update has no clientauto& realm = job.client->realm();@@ -234,7 +258,7 @@ static GC::Ref<Fetch::Infrastructure::FetchController> fetch_job_script(Job cons// AD-HOC: Stopping a fetch does not guarantee that its consume-body steps run, so the stop completes the script// fetch as with a network error.- fetch_controller->set_stop_steps(GC::create_function(realm.heap(), [consume_body] {+ fetch_controller->set_stop_steps(GC::create_function(realm.heap(), GC::captures(consume_body), [](auto& consume_body) {consume_body->run(Fetch::Infrastructure::ResponseView::network_error("Service Worker script fetch was stopped"_string), Empty {});}));return fetch_controller;@@ -271,14 +295,17 @@ static void update(JS::VM& vm, GC::Ref<Job> job)// 5. Let hasUpdatedResources be false.// 6. Let updatedResourceMap be an ordered map where the keys are URLs and the values are responses.- auto state = UpdateAlgorithmState::create();+ auto state = UpdateAlgorithmState::create(*registration, newest_worker);// Fetch time, with a few caveats:// - The spec says to use the 'to be created environment settings object for this service worker'// - Soft-Update has no client// To perform the fetch hook given request, run the following steps:- auto perform_the_fetch_hook_function = [®istration = *registration, job, newest_worker, state](NonnullRefPtr<Fetch::Infrastructure::Request> request, HTML::TopLevelModule top_level, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction process_custom_fetch_response) -> WebIDL::ExceptionOr<void> {+ HTML::PerformTheFetchHook perform_the_fetch_hook = GC::create_function(GC::Heap::the(), GC::captures(job, state), [](auto& job, auto& state, NonnullRefPtr<Fetch::Infrastructure::Request> request, HTML::TopLevelModule top_level, GC::Ref<ScriptFetchConsumeBody::Steps> process_custom_fetch_response) -> WebIDL::ExceptionOr<void> {+ auto& registration = state->registration();+ auto* newest_worker = state->newest_worker();+// 1. Append `Service-Worker`/`script` to request’s header list.// Note: See https://w3c.github.io/ServiceWorker/#service-workerrequest->header_list()->append(HTTP::Header::isomorphic_encode("Service-Worker"sv, "script"sv));@@ -297,7 +324,7 @@ static void update(JS::VM& vm, GC::Ref<Job> job)request->set_service_workers_mode(Fetch::Infrastructure::Request::ServiceWorkersMode::None);Web::Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };- auto consume_body = ScriptFetchConsumeBody::create(move(process_custom_fetch_response));+ auto consume_body = ScriptFetchConsumeBody::create(process_custom_fetch_response);// 4. If the isTopLevel flag is unset, then return the result of fetching request.// FIXME: Needs spec issue, this wording is confusing and contradicts the way perform the fetch hook is used in `run a worker`@@ -315,9 +342,12 @@ static void update(JS::VM& vm, GC::Ref<Job> job)// FIXME: Is there a better way to 'wait' for the fetch's processResponse to complete?// Is this actually what the spec wants us to do?- IGNORE_USE_IN_ESCAPING_LAMBDA auto process_response_completion_result = Optional<WebIDL::ExceptionOr<void>> {};+ auto process_response_completion_result = make_ref_counted<ProcessResponseCompletionResult>();++ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(request, job, state, consume_body, process_response_completion_result), [](auto& request, auto& job, auto& state, auto& consume_body, auto& process_response_completion_result, GC::Ref<Fetch::Infrastructure::ResponseView> response) -> void {+ auto& registration = state->registration();+ auto* newest_worker = state->newest_worker();- fetch_algorithms_input.process_response = [request, job, state, newest_worker, ®istration, consume_body, &process_response_completion_result](GC::Ref<Fetch::Infrastructure::ResponseView> response) mutable -> void {// 7. Extract a MIME type from the response’s header list. If s MIME type (ignoring parameters) is not a JavaScript MIME type, then:auto mime_type = Fetch::Infrastructure::extract_mime_type(response->header_list());if (!mime_type.has_value() || !mime_type->is_javascript()) {@@ -326,7 +356,7 @@ static void update(JS::VM& vm, GC::Ref<Job> job)// 2. Asynchronously complete these steps with a network error.consume_body->run(Fetch::Infrastructure::ResponseView::network_error("Service Worker script response is not a JavaScript MIME type"_string), Empty {});- process_response_completion_result = WebIDL::ExceptionOr<void> {};+ process_response_completion_result->value = WebIDL::ExceptionOr<void> {};return;}@@ -372,7 +402,7 @@ static void update(JS::VM& vm, GC::Ref<Job> job)if (!max_scope.has_value()) {// 1. Asynchronously complete these steps with a network error.consume_body->run(Fetch::Infrastructure::ResponseView::network_error("Failed to parse Service-Worker-Allowed header as a URL"_string), Empty {});- process_response_completion_result = WebIDL::ExceptionOr<void> {};+ process_response_completion_result->value = WebIDL::ExceptionOr<void> {};return;}@@ -393,7 +423,7 @@ static void update(JS::VM& vm, GC::Ref<Job> job)// 2. Asynchronously complete these steps with a network error.consume_body->run(Fetch::Infrastructure::ResponseView::network_error("Service Worker script scope does not match Service-Worker-Allowed header"_string), Empty {});- process_response_completion_result = WebIDL::ExceptionOr<void> {};+ process_response_completion_result->value = WebIDL::ExceptionOr<void> {};return;}@@ -444,37 +474,40 @@ static void update(JS::VM& vm, GC::Ref<Job> job)}// 22. Asynchronously complete these steps with response.- process_response_completion_result = WebIDL::ExceptionOr<void> {};- };+ process_response_completion_result->value = WebIDL::ExceptionOr<void> {};+ });auto fetch_controller = fetch_job_script(*job, *request, move(fetch_algorithms_input), consume_body);// FIXME: This feels.. uncomfortable but it should work to block the current task until the fetch has progressed past our processResponse hook or abortedauto& event_loop = job->client ? job->client->responsible_event_loop() : HTML::current_event_loop();- event_loop.spin_until(GC::create_function(GC::Heap::the(), [fetch_controller, &process_response_completion_result]() -> bool {- if (process_response_completion_result.has_value())+ event_loop.spin_until(GC::create_function(GC::Heap::the(), GC::captures(fetch_controller, process_response_completion_result), [](auto& fetch_controller, auto& process_response_completion_result) -> bool {+ if (process_response_completion_result->value.has_value())return true;if (fetch_controller->state() == Fetch::Infrastructure::FetchController::State::Terminated || fetch_controller->state() == Fetch::Infrastructure::FetchController::State::Aborted) {- process_response_completion_result = WebIDL::AbortError::create("Service Worker fetch was terminated or aborted"_utf16);+ process_response_completion_result->value = WebIDL::AbortError::create("Service Worker fetch was terminated or aborted"_utf16);return true;}// NB: A stopped fetch's stop steps have completed the script fetch.if (fetch_controller->state() == Fetch::Infrastructure::FetchController::State::Stopped) {- process_response_completion_result = WebIDL::ExceptionOr<void> {};+ process_response_completion_result->value = WebIDL::ExceptionOr<void> {};return true;}return false;}));// NB: The event loop gave up on an aborted script.- if (!process_response_completion_result.has_value())+ if (!process_response_completion_result->value.has_value())return WebIDL::AbortError::create("Service Worker fetch was terminated or aborted"_utf16);- return process_response_completion_result.release_value();- };- auto perform_the_fetch_hook = HTML::create_perform_the_fetch_hook(GC::Heap::the(), move(perform_the_fetch_hook_function));+ return process_response_completion_result->value.release_value();+ });// When the algorithm asynchronously completes, continue the rest of these steps, with script being the asynchronous completion value.- auto on_fetch_complete = HTML::create_on_fetch_script_complete(GC::Heap::the(), [job, newest_worker, state, ®istration = *registration, &vm](GC::Ptr<HTML::Script> script) -> void {+ HTML::OnFetchScriptComplete on_fetch_complete = GC::create_function(GC::Heap::the(), GC::captures(job, state), [](auto& job, auto& state, GC::Ptr<HTML::Script> script) -> void {+ auto& vm = JS::VM::the();+ auto& registration = state->registration();+ auto* newest_worker = state->newest_worker();+// 8. If script is null or Is Async Module with script’s record, script’s base URL, and « » is true, then:// FIXME: Reject async modulesif (!script) {@@ -550,13 +583,18 @@ static void unregister(JS::VM& vm, GC::Ref<Job> job)}// https://w3c.github.io/ServiceWorker/#run-job-algorithm-static void run_job(JS::VM& vm, JobQueue& job_queue)+static void run_job(JS::VM&, JobQueue& job_queue){// 1. Assert: jobQueue is not empty.VERIFY(!job_queue.is_empty());// 2. Queue a task to run these steps:- auto job_run_steps = GC::create_function(GC::Heap::the(), [&vm, &job_queue] {+ // NB: The job queue is not GC-allocated, so the task reaches it through the job at its front, which is not dequeued+ // before the task runs.+ auto job_run_steps = GC::create_function(GC::Heap::the(), GC::captures(job_queue.first()), [](auto& first_job) {+ auto& vm = JS::VM::the();+ auto& job_queue = *first_job->containing_job_queue;+// 1. Let job be the first item in jobQueue.auto& job = job_queue.first();@@ -609,7 +647,7 @@ static void resolve_job_promise(GC::Ref<Job> job, Optional<Registration const&>,// 1. If job’s client is not null, queue a task, on job’s client's responsible event loop using the DOM manipulation task source, to run the following substeps:if (job->client) {auto& realm = job->client->realm();- HTML::queue_a_task(HTML::Task::Source::DOMManipulation, job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), [&realm, job, value] {+ HTML::queue_a_task(HTML::Task::Source::DOMManipulation, job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), GC::captures(realm, job, value), [](auto& realm, auto& job, auto& value) {HTML::TemporaryExecutionContext const context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// FIXME: Resolve to a ServiceWorkerRegistration platform object// 1. Let convertedValue be null.@@ -630,7 +668,7 @@ static void resolve_job_promise(GC::Ref<Job> job, Optional<Registration const&>,// 2. Queue a task, on equivalentJob’s client's responsible event loop using the DOM manipulation task source,// to run the following substeps:auto& realm = equivalent_job->client->realm();- HTML::queue_a_task(HTML::Task::Source::DOMManipulation, equivalent_job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), [&realm, equivalent_job, value] {+ HTML::queue_a_task(HTML::Task::Source::DOMManipulation, equivalent_job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), GC::captures(realm, equivalent_job, value), [](auto& realm, auto& equivalent_job, auto& value) {HTML::TemporaryExecutionContext const context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);// FIXME: Resolve to a ServiceWorkerRegistration platform object// 1. Let convertedValue be null.@@ -651,7 +689,7 @@ static void reject_job_promise(GC::Ref<Job> job, Utf16String message)// to reject job’s job promise with a new exception with errorData and a user agent-defined message, in job’s client's Realm.if (job->client) {auto& realm = job->client->realm();- HTML::queue_a_task(HTML::Task::Source::DOMManipulation, job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), [&realm, job, message] {+ HTML::queue_a_task(HTML::Task::Source::DOMManipulation, job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), GC::captures(realm, job, message), [](auto& realm, auto& job, auto& message) {HTML::TemporaryExecutionContext const context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(*job->job_promise, Error::create(realm, message));}));@@ -667,7 +705,7 @@ static void reject_job_promise(GC::Ref<Job> job, Utf16String message)// to reject equivalentJob’s job promise with a new exception with errorData and a user agent-defined message,// in equivalentJob’s client's Realm.auto& realm = equivalent_job->client->realm();- HTML::queue_a_task(HTML::Task::Source::DOMManipulation, equivalent_job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), [&realm, equivalent_job, message] {+ HTML::queue_a_task(HTML::Task::Source::DOMManipulation, equivalent_job->client->responsible_event_loop(), nullptr, GC::create_function(GC::Heap::the(), GC::captures(realm, equivalent_job, message), [](auto& realm, auto& equivalent_job, auto& message) {HTML::TemporaryExecutionContext const context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);WebIDL::reject_promise(*equivalent_job->job_promise, Error::create(realm, message));}));diff --git a/Libraries/LibWeb/ServiceWorker/ServiceWorkerContainer.cpp b/Libraries/LibWeb/ServiceWorker/ServiceWorkerContainer.cppindex 13ec254b66a..c9341682b70 100644--- a/Libraries/LibWeb/ServiceWorker/ServiceWorkerContainer.cpp+++ b/Libraries/LibWeb/ServiceWorker/ServiceWorkerContainer.cpp@@ -72,7 +72,7 @@ static void resolve_service_worker_registration_promise(JS::Realm& realm, WebIDLWebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, registration));}-static void resolve_service_worker_registration_list_promise(JS::Realm& realm, WebIDL::Promise& promise, GC::RootVector<GC::Ref<ServiceWorkerRegistration>> const& registrations)+static void resolve_service_worker_registration_list_promise(JS::Realm& realm, WebIDL::Promise& promise, ReadonlySpan<GC::Ref<ServiceWorkerRegistration>> registrations){GC::RootVector<JS::Value> registration_values;for (auto registration : registrations)@@ -193,7 +193,7 @@ void ServiceWorkerContainer::get_registration(JS::Realm& realm, Utf16String cons}// 8. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [promise, storage_key, parsed_client_url = *parsed_client_url]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(promise, storage_key, *parsed_client_url), [](auto& promise, auto& storage_key, auto& parsed_client_url) {auto& realm = HTML::relevant_realm(promise->promise());HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -227,7 +227,7 @@ void ServiceWorkerContainer::get_registrations(JS::Realm& realm, GC::Ref<WebIDL:}// 4. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [promise, client_storage_key = client_storage_key.release_value()]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(promise, client_storage_key.release_value()), [](auto& promise, auto& client_storage_key) {// 1. Let registrations be a new list.// 2. For each (storage key, scope) -> registration of registration map:// 1. If storage key equals client storage key, then append registration to registrations.@@ -238,7 +238,7 @@ void ServiceWorkerContainer::get_registrations(JS::Realm& realm, GC::Ref<WebIDL:registration_objects.append(HTML::relevant_settings_object(promise->promise()).get_service_worker_registration_object(*registration));// 3. Queue a task on promise's relevant settings object's responsible event loop, using the DOM manipulation task source, to run the following steps:- HTML::queue_a_task(HTML::Task::Source::DOMManipulation, HTML::relevant_settings_object(promise->promise()).responsible_event_loop(), {}, GC::create_function(GC::Heap::the(), [promise, registration_objects = move(registration_objects)]() {+ HTML::queue_a_task(HTML::Task::Source::DOMManipulation, HTML::relevant_settings_object(promise->promise()).responsible_event_loop(), {}, GC::create_function(GC::Heap::the(), GC::captures(promise, move(registration_objects)), [](auto& promise, auto& registration_objects) {auto& realm = HTML::relevant_realm(promise->promise());HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -342,9 +342,9 @@ void ServiceWorkerContainer::start_register(JS::Realm& realm, Optional<URL::URL>void ServiceWorkerContainer::start_ready_promise_steps(GC::Ref<WebIDL::Promise> ready_promise){// 3. If readyPromise is pending, run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [this, ready_promise]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, ready_promise), [](auto& self, auto& ready_promise) {// 1. Let client be this’s service worker client.- auto client = m_service_worker_client;+ auto client = self.m_service_worker_client;// 2. Let storage key be the result of running obtain a storage key given client.auto storage_key = StorageAPI::obtain_a_storage_key(client);@@ -362,7 +362,7 @@ void ServiceWorkerContainer::start_ready_promise_steps(GC::Ref<WebIDL::Promise>// registration in readyPromise’s relevant settings object.if (maybe_registration.has_value() && maybe_registration->active_worker() != nullptr) {auto registration_object = HTML::relevant_settings_object(ready_promise->promise()).get_service_worker_registration_object(maybe_registration.value());- queue_a_task(HTML::Task::Source::DOMManipulation, nullptr, nullptr, GC::create_function(GC::Heap::the(), [ready_promise, registration_object]() {+ queue_a_task(HTML::Task::Source::DOMManipulation, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(ready_promise, registration_object), [](auto& ready_promise, auto& registration_object) {auto& realm = HTML::relevant_realm(ready_promise->promise());HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };resolve_service_worker_registration_promise(realm, ready_promise, registration_object);diff --git a/Libraries/LibWeb/Streams/ReadableStream.cpp b/Libraries/LibWeb/Streams/ReadableStream.cppindex 6a5516e8475..53396d0eb83 100644--- a/Libraries/LibWeb/Streams/ReadableStream.cpp+++ b/Libraries/LibWeb/Streams/ReadableStream.cpp@@ -209,12 +209,12 @@ GC::Ref<WebIDL::Promise> ReadableStreamDefaultReader::read_all_bytes_deprecated(auto promise = WebIDL::create_promise(realm);- auto success_steps = GC::create_function(GC::Heap::the(), [promise, &realm](ByteBuffer bytes) {+ auto success_steps = GC::create_function(GC::Heap::the(), GC::captures(promise, realm), [](auto& promise, auto& realm, ByteBuffer bytes) {auto buffer = JS::ArrayBuffer::create(realm, move(bytes));WebIDL::resolve_promise(promise, buffer);});- auto failure_steps = GC::create_function(GC::Heap::the(), [promise](JS::Value error) {+ auto failure_steps = GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, JS::Value error) {WebIDL::reject_promise(promise, error);});diff --git a/Libraries/LibWeb/Translation/DocumentTranslator.cpp b/Libraries/LibWeb/Translation/DocumentTranslator.cppindex 890579891f7..a1c490b0a06 100644--- a/Libraries/LibWeb/Translation/DocumentTranslator.cpp+++ b/Libraries/LibWeb/Translation/DocumentTranslator.cpp@@ -1148,7 +1148,7 @@ void DocumentTranslator::schedule_rescan()if (m_rescan_scheduled)return;m_rescan_scheduled = true;- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), [document = GC::Weak<DOM::Document> { m_document }] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, HTML::relevant_global_object(m_document), GC::create_function(m_document->heap(), GC::captures(GC::Weak<DOM::Document> { m_document }), [](auto& document) {auto strong_document = document.ptr();if (!strong_document)return;diff --git a/Libraries/LibWeb/ViewTransition/ViewTransition.cpp b/Libraries/LibWeb/ViewTransition/ViewTransition.cppindex 6af7dbf8ae3..e174e3b5977 100644--- a/Libraries/LibWeb/ViewTransition/ViewTransition.cpp+++ b/Libraries/LibWeb/ViewTransition/ViewTransition.cpp@@ -149,14 +149,14 @@ void ViewTransition::setup_view_transition()// 5. Queue a global task on the DOM manipulation task source, given transition’s relevant global object, to// perform the following steps:- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function(GC::Heap::the(), [&] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, realm, document), [](ViewTransition& self, auto& realm, auto& document) {HTML::TemporaryExecutionContext context(realm);// 1. If transition’s phase is "done", then abort these steps.- if (m_phase == Phase::Done)+ if (self.m_phase == Phase::Done)return;// 2. schedule the update callback for transition.- schedule_the_update_callback();+ self.schedule_the_update_callback();// 3. Flush the update callback queue.// AD-HOC: Spec doesn't say what document to flush it for.@@ -663,35 +663,35 @@ void ViewTransition::call_the_update_callback()}// 6. Let fulfillSteps be to following steps:- auto fulfill_steps = GC::create_function(GC::Heap::the(), [this, &realm](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ auto fulfill_steps = GC::create_function<WebIDL::ExceptionOr<JS::Value>(JS::Value)>(GC::Heap::the(), GC::captures(*this, realm), [](ViewTransition& self, auto& realm, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context(realm);// 1. Resolve transition’s update callback done promise with undefined.- WebIDL::resolve_promise(m_update_callback_done_promise);+ WebIDL::resolve_promise(self.m_update_callback_done_promise);// 2. Activate transition.- activate_view_transition();+ self.activate_view_transition();return JS::js_undefined();});// 7. Let rejectSteps be the following steps given reason:- auto reject_steps = GC::create_function(GC::Heap::the(), [this, &realm](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ auto reject_steps = GC::create_function<WebIDL::ExceptionOr<JS::Value>(JS::Value)>(GC::Heap::the(), GC::captures(*this, realm), [](ViewTransition& self, auto& realm, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext context(realm);// 1. Reject transition’s update callback done promise with reason.- WebIDL::reject_promise(m_update_callback_done_promise, reason);+ WebIDL::reject_promise(self.m_update_callback_done_promise, reason);// 2. If transition’s phase is "done", then return.// NOTE: This happens if transition was skipped before this point.- if (m_phase == Phase::Done)+ if (self.m_phase == Phase::Done)return JS::js_undefined();// 3. Mark as handled transition’s ready promise.// NOTE: transition’s update callback done promise will provide the unhandledrejection. This// step avoids a duplicate.- WebIDL::mark_promise_as_handled(m_update_callback_done_promise);+ WebIDL::mark_promise_as_handled(self.m_update_callback_done_promise);// 4. Skip the view transition transition with reason.- skip_the_view_transition(reason);+ self.skip_the_view_transition(reason);return JS::js_undefined();});@@ -716,11 +716,11 @@ void ViewTransition::schedule_the_update_callback()// 2. Queue a global task on the DOM manipulation task source, given transition’s relevant global object, to flush// the update callback queue.- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, document().relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), [&] {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, document().relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(*this), [](ViewTransition& self) {// AD-HOC: Spec doesn't say what document to flush it for.// Lets just use the one we use elsewhere.// (see https://github.com/w3c/csswg-drafts/issues/11986 )- document().flush_the_update_callback_queue();+ self.document().flush_the_update_callback_queue();}));}diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cppindex 3bf39d0f6eb..98c41243508 100644--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp@@ -75,10 +75,10 @@ void web_audio_worklet_queue_processor_error(AudioWorkletNode* node, DOM::EventTHTML::ErrorEventInit event_init;event_init.message = JS::HostABI::value_from_abi(error).to_utf16_string_without_side_effects();HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global_object,- GC::create_function(GC::Heap::the(), [node = GC::make_root(*node), target, global, event_init = move(event_init)] {- auto& global_object = HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*global));+ GC::create_function(GC::Heap::the(), GC::captures(*node, *target, *global, move(event_init)), [](AudioWorkletNode&, DOM::EventTarget& target, DOM::EventTarget& global, HTML::ErrorEventInit const& event_init) {+ auto& global_object = HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(global));auto event = HTML::ErrorEvent::create(HTML::EventNames::processorerror, event_init, HighResolutionTime::current_high_resolution_time(global_object));- target->dispatch_event(event);+ target.dispatch_event(event);}));}diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Libraries/LibWeb/WebAudio/BaseAudioContext.cppindex 60f6c98a79a..e5d9a8da8f2 100644--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp@@ -62,8 +62,8 @@ void web_audio_context_destroy_task_source(HTML::UniqueTaskSource* source) { delvoid web_audio_context_queue_task(HTML::UniqueTaskSource* source, DOM::EventTarget* global, GC::Cell* cell, void (*invoke)(void*, void*)){auto& settings = HTML::relevant_settings_object(HTML::relevant_window_or_worker_global_scope(*global));- auto task = HTML::Task::create(source->source, settings.responsible_document(), GC::create_function(GC::Heap::the(), [cell = GC::make_root(*cell), invoke] {- invoke(JS::HostABI::vm_to_abi(JS::VM::the()), cell.ptr());+ auto task = HTML::Task::create(source->source, settings.responsible_document(), GC::create_function(GC::Heap::the(), GC::captures(*cell, invoke), [](GC::Cell& cell, void (*invoke)(void*, void*)) {+ invoke(JS::HostABI::vm_to_abi(JS::VM::the()), &cell);}));(void)HTML::main_thread_event_loop().task_queue().add(task);}@@ -74,7 +74,7 @@ DOM::DocumentObserver* web_audio_context_observe_document(DOM::EventTarget* globreturn nullptr;// FIXME: Also handle the document becoming active again, e.g. when restored from the back/forward cache.auto observer = DOM::DocumentObserver::create(window->associated_document());- observer->set_document_became_inactive([context] { web_rust_audio_context_document_inactive(context); });+ observer->set_document_became_inactive(GC::create_function(GC::Heap::the(), GC::captures(*context), [](Bindings::RustInterfaceCell& context) { web_rust_audio_context_document_inactive(&context); }));return observer.ptr();}JS::Realm* web_audio_context_global_realm(DOM::EventTarget* global) { return &HTML::relevant_settings_object(HTML::relevant_window_or_worker_global_scope(*global)).realm(); }diff --git a/Libraries/LibWeb/WebDriver/Actions.cpp b/Libraries/LibWeb/WebDriver/Actions.cppindex d2d52f1f0c7..28ff536f456 100644--- a/Libraries/LibWeb/WebDriver/Actions.cpp+++ b/Libraries/LibWeb/WebDriver/Actions.cpp@@ -1490,9 +1490,9 @@ public:m_tick_duration_has_passed = false;DispatchMouseEvent dispatch_mouse_event = [this](Web::MouseEvent event) {++m_pending_mouse_event_count;- m_browsing_context->page().client().page_did_request_webdriver_mouse_event(local_root(m_browsing_context)->id(), move(event), GC::create_function(heap(), [this]() {- --m_pending_mouse_event_count;- process_next_tick_once_the_tick_is_over();+ m_browsing_context->page().client().page_did_request_webdriver_mouse_event(local_root(m_browsing_context)->id(), move(event), GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ --self.m_pending_mouse_event_count;+ self.process_next_tick_once_the_tick_is_over();}));};@@ -1525,17 +1525,17 @@ public:return;m_tick_duration_has_passed = false;- auto queue_next_tick = [this] {- HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this]() {- process_next_tick();+ auto queue_next_tick = GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {+ self.process_next_tick();}));- };+ });// NB: Wheel input scrolls smoothly, so the scrolls that the tick's scroll actions started are pending asynchronous// waits too.auto document = m_browsing_context->active_document();if (!m_tick_dispatches_scroll_actions || !document) {- queue_next_tick();+ queue_next_tick->function()();return;}auto& realm = HTML::relevant_realm(*document);@@ -1546,10 +1546,13 @@ public:navigable->wait_for_wheel_scrolls(scroll_promises);}if (scroll_promises.is_empty()) {- queue_next_tick();+ queue_next_tick->function()();return;}- WebIDL::wait_for_all(realm, scroll_promises, [queue_next_tick](auto const&) { queue_next_tick(); }, [queue_next_tick](auto) { queue_next_tick(); });+ WebIDL::wait_for_all(+ realm, scroll_promises,+ GC::create_function(GC::Heap::the(), GC::captures(queue_next_tick), [](auto& queue_next_tick, Vector<JS::Value> const&) { queue_next_tick->function()(); }),+ GC::create_function(GC::Heap::the(), GC::captures(queue_next_tick), [](auto& queue_next_tick, JS::Value) { queue_next_tick->function()(); }));}private:@@ -1848,7 +1851,7 @@ GC::Ref<JS::Cell> dispatch_actions_for_a_string(Web::WebDriver::InputState& inpu// 5. Dispatch the events for a typeable string with input state, input id and source, current typeable text, and// browsing context.- return dispatch_the_events_for_a_typeable_string(input_state, input_id, source, text, browsing_context, GC::create_function(GC::Heap::the(), [on_complete](Web::WebDriver::Response result) {+ return dispatch_the_events_for_a_typeable_string(input_state, input_id, source, text, browsing_context, GC::create_function(GC::Heap::the(), GC::captures(on_complete), [](auto& on_complete, Web::WebDriver::Response result) {// FIXME: 6. Try to clear the modifier key state with input state, input id, source, undo actions, and browsing context.on_complete->function()(move(result));diff --git a/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.h b/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.hindex 523d7ae62c1..bafaa57a2fd 100644--- a/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.h+++ b/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.h@@ -54,9 +54,9 @@ inline GC::Ref<JS::Object> create_object(HTML::EnvironmentSettingsObject& settinreturn JS::Object::create(realm, realm.intrinsics().object_prototype());}-inline GC::Ref<JS::NativeFunction> create_channel_function(HTML::EnvironmentSettingsObject& settings, Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> steps)+inline GC::Ref<JS::NativeFunction> create_channel_function(HTML::EnvironmentSettingsObject& settings, GC::Ref<GC::Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>> steps){- return JS::NativeFunction::create(settings.realm(), move(steps), 1);+ return JS::NativeFunction::create(settings.realm(), steps, 1);}inline GC::Ref<JS::TypeError> create_preload_type_error(HTML::EnvironmentSettingsObject& settings)diff --git a/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cpp b/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cppindex d9ad5159766..cd51b0a9539 100644--- a/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/BrowsingContext.cpp@@ -865,17 +865,17 @@ void capture_screenshot(HTML::Navigable& navigable, JsonObject const& params, Onauto state = adopt_ref(*new State);state->on_complete = move(on_complete);state->observer = DOM::DocumentObserver::create(document);- state->observer->set_document_became_inactive([weak_state = state->make_weak_ptr()] {+ state->observer->set_document_became_inactive(GC::create_function(GC::Heap::the(), GC::captures(state->make_weak_ptr()), [](auto& weak_state) {if (weak_state)weak_state->fail();- });- state->observer->set_document_visibility_state_observer([weak_state = state->make_weak_ptr()](HTML::VisibilityState visibility) {+ }));+ state->observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(state->make_weak_ptr()), [](auto& weak_state, HTML::VisibilityState visibility) {if (visibility == HTML::VisibilityState::Hidden && weak_state)weak_state->fail();- });+ }));// 5. Immediately after the next invocation of the run the animation frame callbacks algorithm for document:- state->callback_id = window->animation_frame_callback_driver().add_after_callbacks(GC::create_function(GC::Heap::the(), [state, document, navigable = GC::Ref { *local_navigable }, origin = move(origin), clip = move(clip), max_width, max_height, format_type = move(format_type), format_quality](double) mutable {+ state->callback_id = window->animation_frame_callback_driver().add_after_callbacks(GC::create_function(GC::Heap::the(), GC::captures(state, document, GC::Ref { *local_navigable }, move(origin), move(clip), max_width, max_height, move(format_type), format_quality), [](auto& state, auto& document, auto& navigable, auto& origin, auto& clip, auto& max_width, auto& max_height, auto& format_type, auto& format_quality, double) {if (!state->on_complete)return;state->stop_waiting_for_frame();@@ -1041,7 +1041,7 @@ void capture_screenshot(HTML::Navigable& navigable, JsonObject const& params, On// 14. Complete implementation specific steps equivalent to painting the region of document's framebuffer// specified by source rectangle on the region of canvas context's output bitmap specified by destination// rectangle.- auto viewport_device_rect = document->page().enclosing_device_rect(navigable->viewport_rect()).to_type<int>();+ auto viewport_device_rect = document->page().enclosing_device_rect(navigable->viewport_rect()).template to_type<int>();if (viewport_device_rect.is_empty())return state->complete(Error::from_code(ErrorCode::UnableToCaptureScreen, "The viewport is empty"sv));diff --git a/Libraries/LibWeb/WebDriver/BiDi/Input.cpp b/Libraries/LibWeb/WebDriver/BiDi/Input.cppindex 193e5053037..1b111a2d024 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Input.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/Input.cpp@@ -90,6 +90,7 @@ struct ActionsInFlight : RefCounted<ActionsInFlight> {AK_ALLOC_WITH_KMALLOC;Optional<GC::Root<JS::Cell>> executor;+ OnCommandComplete on_complete;bool completed { false };};@@ -161,10 +162,11 @@ static void perform_actions_steps(HTML::Navigable& navigable, JsonObject const&// 6. Try to dispatch actions with input state, actions by tick, navigable, and actions options.// 7. Return success with data null.auto in_flight = adopt_ref(*new ActionsInFlight);- auto on_actions_complete = GC::create_function(GC::Heap::the(), [in_flight, on_complete = move(on_complete)](Response result) {+ in_flight->on_complete = move(on_complete);+ auto on_actions_complete = GC::create_function(GC::Heap::the(), GC::captures(in_flight), [](auto& in_flight, Response result) {in_flight->completed = true;in_flight->executor.clear();- on_complete(move(result));+ in_flight->on_complete(move(result));});auto executor = dispatch_actions(input_state, actions_by_tick.release_value(), *local_navigable->active_browsing_context(), options, on_actions_complete);@@ -211,7 +213,8 @@ static void release_actions_steps(HTML::Navigable& navigable, OnCommandCompleteinput_state.actions_queue.take_first();auto in_flight = adopt_ref(*new ActionsInFlight);- auto on_actions_complete = GC::create_function(GC::Heap::the(), [in_flight, top_level_traversable, on_complete = move(on_complete)](Response result) {+ in_flight->on_complete = move(on_complete);+ auto on_actions_complete = GC::create_function(GC::Heap::the(), GC::captures(in_flight, top_level_traversable), [](auto& in_flight, auto& top_level_traversable, Response result) {in_flight->completed = true;in_flight->executor.clear();@@ -219,7 +222,7 @@ static void release_actions_steps(HTML::Navigable& navigable, OnCommandCompletereset_input_state(top_level_traversable);// 9. Return success with data null.- on_complete(move(result));+ in_flight->on_complete(move(result));});auto executor = dispatch_actions(input_state, { move(undo_actions) }, *local_navigable->active_browsing_context(), options, on_actions_complete);diff --git a/Libraries/LibWeb/WebDriver/BiDi/Script.cpp b/Libraries/LibWeb/WebDriver/BiDi/Script.cppindex 0636efae84e..783f6983a20 100644--- a/Libraries/LibWeb/WebDriver/BiDi/Script.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/Script.cpp@@ -135,7 +135,7 @@ JS::Value create_a_channel(HTML::EnvironmentSettingsObject& settings, JsonObjectauto channel_properties = protocol_value.get_object("value"sv).value_or({});// 2. Let steps be the following steps given the argument message:- auto steps = [channel_properties = move(channel_properties)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto steps = GC::create_function(GC::Heap::the(), GC::captures(move(channel_properties)), [](JsonObject& channel_properties, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {auto message = vm.argument(0);// 1. Let current realm be the current Realm Record.@@ -194,10 +194,10 @@ JS::Value create_a_channel(HTML::EnvironmentSettingsObject& settings, JsonObject// 7. Emit an event with session and body.emit_event(*navigable, "script.message"_string, move(params));return JS::js_undefined();- };+ });// 3. Return CreateBuiltinFunction(steps, 1, "", « », realm).- return BindingsGlue::create_channel_function(settings, move(steps));+ return BindingsGlue::create_channel_function(settings, steps);}// https://w3c.github.io/webdriver-bidi/#get-a-realm-from-a-target@@ -422,14 +422,14 @@ static void complete_evaluation(HTML::EnvironmentSettingsObject& settings, JS::Cpending_evaluations().ensure(state->environment_id).append(state);WebIDL::react_to_promise(promise,- GC::create_function(GC::Heap::the(), [settings = GC::Ref { settings }, state](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { settings }, state), [](auto& settings, auto& state, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {if (!state->on_complete)return JS::js_undefined();HTML::TemporaryExecutionContext execution_context { *settings, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };state->complete(JsonValue { evaluation_result_success(*settings, value, state->serialization_options, state->result_ownership) });return JS::js_undefined();}),- GC::create_function(GC::Heap::the(), [settings = GC::Ref { settings }, state](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { settings }, state), [](auto& settings, auto& state, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {if (!state->on_complete)return JS::js_undefined();HTML::TemporaryExecutionContext execution_context { *settings, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };diff --git a/Libraries/LibWeb/WebDriver/ExecuteScript.cpp b/Libraries/LibWeb/WebDriver/ExecuteScript.cppindex 5b01923a7a4..43b27a4a78c 100644--- a/Libraries/LibWeb/WebDriver/ExecuteScript.cpp+++ b/Libraries/LibWeb/WebDriver/ExecuteScript.cpp@@ -94,7 +94,7 @@ static JS::ThrowCompletionOr<JS::Value> execute_a_function_body(HTML::BrowsingCostatic void fire_completion_when_resolved(GC::Ref<WebIDL::Promise> promise, GC::Ref<GC::Timer> timer, GC::Ref<OnScriptComplete> on_complete){- auto reaction_steps = GC::create_function(GC::Heap::the(), [promise, timer, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ auto reaction_steps = GC::create_function(GC::Heap::the(), GC::captures(promise, timer, on_complete), [](auto& promise, auto& timer, auto& on_complete, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {if (timer->is_timed_out())return JS::js_undefined();timer->stop();@@ -119,7 +119,7 @@ GC::Ref<GC::Timer> execute_script(HTML::BrowsingContext const& browsing_context,// 6. If timeout is not null:if (timeout_ms.has_value()) {// 1. Start the timer with timer and timeout.- timer->start(timeout_ms.value(), GC::create_function(GC::Heap::the(), [on_complete]() {+ timer->start(timeout_ms.value(), GC::create_function(GC::Heap::the(), GC::captures(on_complete), [](auto& on_complete) {on_complete->function()({ .state = JS::Promise::State::Pending });}));}@@ -131,27 +131,22 @@ GC::Ref<GC::Timer> execute_script(HTML::BrowsingContext const& browsing_context,auto promise = WebIDL::create_promise(realm);// 8. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, &browsing_context, promise, body = move(body), captured_arguments = move(arguments)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, browsing_context, promise, move(body), move(arguments)), [](auto& realm, auto& browsing_context, auto& promise, auto& body, auto& arguments) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- // The roots of a function that died stay in place until a collection finalizes it, so take the arguments out of- // the function to have them released as soon as this task is done, rather than keeping everything they reach- // alive through one more collection.- auto arguments = move(captured_arguments);-// 1. Let scriptPromise be the result of promise-calling execute a function body, with arguments body and arguments.auto script_promise = promise_call(realm, execute_a_function_body(browsing_context, body, arguments));WebIDL::react_to_promise(script_promise,// 2. Upon fulfillment of scriptPromise with value v, resolve promise with value v.- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::resolve_promise(promise, value);return JS::js_undefined();}),// 3. Upon rejection of scriptPromise with value r, reject promise with value r.- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::reject_promise(promise, reason);return JS::js_undefined();@@ -169,7 +164,6 @@ GC::Ref<GC::Timer> execute_async_script(HTML::BrowsingContext const& browsing_co{auto const* document = browsing_context.active_document();auto& realm = document->relevant_settings_object().realm();- auto& vm = document->vm();// 5. Let timer be a new timer.auto timer = GC::Heap::the().allocate<GC::Timer>();@@ -177,7 +171,7 @@ GC::Ref<GC::Timer> execute_async_script(HTML::BrowsingContext const& browsing_co// 6. If timeout is not null:if (timeout_ms.has_value()) {// 1. Start the timer with timer and timeout.- timer->start(timeout_ms.value(), GC::create_function(GC::Heap::the(), [on_complete]() {+ timer->start(timeout_ms.value(), GC::create_function(GC::Heap::the(), GC::captures(on_complete), [](auto& on_complete) {on_complete->function()({ .state = JS::Promise::State::Pending });}));}@@ -189,14 +183,9 @@ GC::Ref<GC::Timer> execute_async_script(HTML::BrowsingContext const& browsing_coauto promise = WebIDL::create_promise(realm);// 8. Run the following substeps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&vm, &realm, &browsing_context, promise, body = move(body), captured_arguments = move(arguments)]() mutable {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, browsing_context, promise, move(body), move(arguments)), [](auto& realm, auto& browsing_context, auto& promise, auto& body, auto& arguments) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- // The roots of a function that died stay in place until a collection finalizes it, so take the arguments out of- // the function to have them released as soon as this task is done, rather than keeping everything they reach- // alive through one more collection.- auto arguments = move(captured_arguments);-// 1. Let resolvingFunctions be CreateResolvingFunctions(promise).auto resolving_functions = as<JS::Promise>(*promise->promise()).create_resolving_functions();@@ -204,7 +193,7 @@ GC::Ref<GC::Timer> execute_async_script(HTML::BrowsingContext const& browsing_coarguments.append(resolving_functions.resolve);// 3. Let scriptResult be the result of calling execute a function body, with arguments body and arguments.- auto script_result = execute_a_function_body(browsing_context, body, move(arguments));+ auto script_result = execute_a_function_body(browsing_context, body, arguments);// 4. If scriptResult.[[Type]] is not normal, then reject promise with value scriptResult.[[Value]], and abort these steps.// NOTE: Prior revisions of this specification did not recognize the return value of the provided script.@@ -220,7 +209,7 @@ GC::Ref<GC::Timer> execute_async_script(HTML::BrowsingContext const& browsing_coreturn;// 6. Let then be Get(scriptResult.[[Value]], "then").- auto then = script_result.value().as_object().get(vm.names.then);+ auto then = script_result.value().as_object().get(realm.vm().names.then);// 7. If then.[[Type]] is not normal, then reject promise with value then.[[Value]], and abort these steps.if (then.is_throw_completion()) {@@ -237,14 +226,14 @@ GC::Ref<GC::Timer> execute_async_script(HTML::BrowsingContext const& browsing_coWebIDL::react_to_promise(script_promise,// 10. Upon fulfillment of scriptPromise with value v, resolve promise with value v.- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::resolve_promise(promise, value);return JS::js_undefined();}),// 11. Upon rejection of scriptPromise with value r, reject promise with value r.- GC::create_function(GC::Heap::the(), [&realm, promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {+ GC::create_function(GC::Heap::the(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };WebIDL::reject_promise(promise, reason);return JS::js_undefined();diff --git a/Libraries/LibWeb/WebDriver/UserPrompt.cpp b/Libraries/LibWeb/WebDriver/UserPrompt.cppindex cce997a9407..d4d6ab23c2a 100644--- a/Libraries/LibWeb/WebDriver/UserPrompt.cpp+++ b/Libraries/LibWeb/WebDriver/UserPrompt.cpp@@ -45,7 +45,7 @@ void handle_any_user_prompts(Page& page, GC::Ref<GC::Function<void(Optional<Erro// 4. Let handler be get the prompt handler with type.auto handler = get_the_prompt_handler(type);- auto on_dialog_closed = GC::create_function(page.heap(), [notify = handler.notify, pending_dialog_text = page.pending_dialog_text(), on_complete]() {+ auto on_dialog_closed = GC::create_function(page.heap(), GC::captures(handler.notify, page.pending_dialog_text(), on_complete), [](auto& notify, auto& pending_dialog_text, auto& on_complete) {// 5. If handler's notify is true, return annotated unexpected alert open error.if (notify == PromptHandlerConfiguration::Notify::Yes) {on_complete->function()(create_annotated_unexpected_alert_open_error(pending_dialog_text));diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cppindex 2399ffd193d..933169585a6 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp@@ -311,10 +311,10 @@ void WebGLRenderingContextBase::lose_context_from_compositor_loss()if (!web_webgl_context_mark_lost(this))return;- HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {+ HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](WebGLRenderingContextBase& self) {// webglcontextlost is cancelable; preventDefault() means the page wants the context// restored once a compositor is available again.- web_webgl_context_set_restore_requested(this, !fire_webgl_context_event(canvas_host(), EventNames::webglcontextlost));+ web_webgl_context_set_restore_requested(&self, !fire_webgl_context_event(self.canvas_host(), EventNames::webglcontextlost));}));}@@ -335,8 +335,8 @@ void WebGLRenderingContextBase::restore_context_after_compositor_reconnect()auto supported_extensions = remote->supported_extension_spans();web_webgl_context_restore(this, &remote->transport.leak_ref(), supported_extensions.span());- HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {- fire_webgl_context_event(canvas_host(), EventNames::webglcontextrestored);+ HTML::queue_a_task(HTML::Task::Source::WebGL, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](WebGLRenderingContextBase& self) {+ fire_webgl_context_event(self.canvas_host(), EventNames::webglcontextrestored);}));}diff --git a/Libraries/LibWeb/WebIDL/AsyncIterator.cpp b/Libraries/LibWeb/WebIDL/AsyncIterator.cppindex 5c9a4521e2b..6028a599064 100644--- a/Libraries/LibWeb/WebIDL/AsyncIterator.cpp+++ b/Libraries/LibWeb/WebIDL/AsyncIterator.cpp@@ -34,14 +34,14 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_next_impl()auto& vm = this->vm();// 8. Let nextSteps be the following steps:- auto next_steps = [this](JS::VM& vm) {- auto& realm = this->promise_realm();+ auto next_steps = GC::create_function(heap(), GC::captures(*this), [](AsyncIterator& self, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto& realm = self.promise_realm();// 1. Let nextPromiseCapability be ! NewPromiseCapability(%Promise%).auto next_promise_capability = WebIDL::create_promise(realm);// 2. If object’s is finished is true, then:- if (m_is_finished) {+ if (self.m_is_finished) {// 1. Let result be CreateIteratorResultObject(undefined, true).auto result = JS::create_iterator_result_object(realm, JS::js_undefined(), true);@@ -55,20 +55,20 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_next_impl()// 3. Let kind be object’s kind.// 4. Let nextPromise be the result of getting the next iteration result with object’s target and object.- auto& next_promise = as<JS::Promise>(*next_iteration_result(realm)->promise());+ auto& next_promise = as<JS::Promise>(*self.next_iteration_result(realm)->promise());// 5. Let fulfillSteps be the following steps, given next:- auto fulfill_steps = [this](JS::VM& vm) {- auto& realm = this->promise_realm();+ auto fulfill_steps = GC::create_function(self.heap(), GC::captures(self), [](AsyncIterator& self, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto& realm = self.promise_realm();auto next = vm.argument(0);// 1. Set object’s ongoing promise to null.- m_ongoing_promise = nullptr;+ self.m_ongoing_promise = nullptr;// 2. If next is end of iteration, then:if (next.is_special_empty_value()) {// 1. Set object’s is finished to true.- m_is_finished = true;+ self.m_is_finished = true;// 2. Return CreateIteratorResultObject(undefined, true).return JS::create_iterator_result_object(realm, JS::js_undefined(), true);@@ -87,34 +87,34 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_next_impl()// 4. Return CreateIteratorResultObject(value, false).return JS::create_iterator_result_object(realm, next, false);}- };+ });// 6. Let onFulfilled be CreateBuiltinFunction(fulfillSteps, « »).- auto on_fulfilled = JS::NativeFunction::create(realm, move(fulfill_steps), 0);+ auto on_fulfilled = JS::NativeFunction::create(realm, fulfill_steps, 0);// 7. Let rejectSteps be the following steps, given reason:- auto reject_steps = [this](JS::VM& vm) {+ auto reject_steps = GC::create_function(self.heap(), GC::captures(self), [](AsyncIterator& self, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {auto reason = vm.argument(0);// 1. Set object’s ongoing promise to null.- m_ongoing_promise = nullptr;+ self.m_ongoing_promise = nullptr;// 2. Set object’s is finished to true.- m_is_finished = true;+ self.m_is_finished = true;// 3. Throw reason.return JS::throw_completion(reason);- };+ });// 8. Let onRejected be CreateBuiltinFunction(rejectSteps, « »).- auto on_rejected = JS::NativeFunction::create(realm, move(reject_steps), 0);+ auto on_rejected = JS::NativeFunction::create(realm, reject_steps, 0);// 9. Perform PerformPromiseThen(nextPromise, onFulfilled, onRejected, nextPromiseCapability).next_promise.perform_then(on_fulfilled, on_rejected, next_promise_capability);// 10. Return nextPromiseCapability.[[Promise]].return next_promise_capability->promise();- };+ });// 9. Let ongoingPromise be object’s ongoing promise.// 10. If ongoingPromise is not null, then:@@ -123,7 +123,7 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_next_impl()auto after_ongoing_promise_capability = WebIDL::create_promise(realm);// 2. Let onSettled be CreateBuiltinFunction(nextSteps, « »).- auto on_settled = JS::NativeFunction::create(realm, move(next_steps), 0);+ auto on_settled = JS::NativeFunction::create(realm, next_steps, 0);// 3. Perform PerformPromiseThen(ongoingPromise, onSettled, onSettled, afterOngoingPromiseCapability).m_ongoing_promise->perform_then(on_settled, on_settled, after_ongoing_promise_capability);@@ -134,7 +134,7 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_next_impl()// 11. Otherwise:else {// 1. Set object’s ongoing promise to the result of running nextSteps.- m_ongoing_promise = as<JS::Promise>(*next_steps(vm));+ m_ongoing_promise = as<JS::Promise>(MUST(next_steps->function()(vm)).as_object());}// 12. Return object’s ongoing promise.@@ -148,14 +148,14 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_return_impl(Gauto& vm = this->vm();// 8. Let returnSteps be the following steps:- auto return_steps = [this, value](JS::VM& vm) {- auto& realm = this->promise_realm();+ auto return_steps = GC::create_function(heap(), GC::captures(*this, value), [](AsyncIterator& self, JS::Value& value, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto& realm = self.promise_realm();// 1. Let returnPromiseCapability be ! NewPromiseCapability(%Promise%).auto return_promise_capability = WebIDL::create_promise(realm);// 2. If object’s is finished is true, then:- if (m_is_finished) {+ if (self.m_is_finished) {// 1. Let result be CreateIteratorResultObject(value, true).auto result = JS::create_iterator_result_object(realm, value, true);@@ -167,11 +167,11 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_return_impl(G}// 3. Set object’s is finished to true.- m_is_finished = true;+ self.m_is_finished = true;// 4. Return the result of running the asynchronous iterator return algorithm for interface, given object’s target, object, and value.- return iterator_return(realm, value)->promise();- };+ return self.iterator_return(realm, value)->promise();+ });// 9. Let ongoingPromise be object’s ongoing promise.// 10. If ongoingPromise is not null, then:@@ -180,7 +180,7 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_return_impl(Gauto after_ongoing_promise_capability = WebIDL::create_promise(realm);// 2. Let onSettled be CreateBuiltinFunction(returnSteps, « »).- auto on_settled = JS::NativeFunction::create(realm, move(return_steps), 0);+ auto on_settled = JS::NativeFunction::create(realm, return_steps, 0);// 3. Perform PerformPromiseThen(ongoingPromise, onSettled, onSettled, afterOngoingPromiseCapability).m_ongoing_promise->perform_then(on_settled, on_settled, after_ongoing_promise_capability);@@ -191,19 +191,19 @@ JS::ThrowCompletionOr<GC::Ptr<JS::Object>> AsyncIterator::iterator_return_impl(G// 11. Otherwise:else {// 1. Set object’s ongoing promise to the result of running returnSteps.- m_ongoing_promise = as<JS::Promise>(*return_steps(vm));+ m_ongoing_promise = as<JS::Promise>(MUST(return_steps->function()(vm)).as_object());}// 12. Let fulfillSteps be the following steps:- auto fulfill_steps = [this, value]([[maybe_unused]] JS::VM& vm) {- auto& realm = this->promise_realm();+ auto fulfill_steps = GC::create_function(heap(), GC::captures(*this, value), [](AsyncIterator& self, JS::Value& value, JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {+ auto& realm = self.promise_realm();// 1. Return CreateIteratorResultObject(value, true).return JS::create_iterator_result_object(realm, value, true);- };+ });// 13. Let onFulfilled be CreateBuiltinFunction(fulfillSteps, « »).- auto on_fulfilled = JS::NativeFunction::create(realm, move(fulfill_steps), 0);+ auto on_fulfilled = JS::NativeFunction::create(realm, fulfill_steps, 0);// 14. Perform PerformPromiseThen(object’s ongoing promise, onFulfilled, undefined, returnPromiseCapability).m_ongoing_promise->perform_then(on_fulfilled, JS::js_undefined(), return_promise_capability);diff --git a/Libraries/LibWeb/WebIDL/ExceptionOr.h b/Libraries/LibWeb/WebIDL/ExceptionOr.hindex 64b38aba041..b9c919d62e3 100644--- a/Libraries/LibWeb/WebIDL/ExceptionOr.h+++ b/Libraries/LibWeb/WebIDL/ExceptionOr.h@@ -11,6 +11,7 @@#include <AK/Optional.h>#include <AK/RefPtr.h>#include <AK/Utf16String.h>+#include <LibGC/CaptureTraits.h>#include <LibJS/Runtime/Completion.h>#include <LibWeb/WebIDL/DOMException.h>@@ -131,6 +132,15 @@ public:[[nodiscard]] bool is_error() const { return is_exception(); }Exception release_error() { return exception(); }+ // NB: This lets a GC::Function capture an ExceptionOr, tracing the value or exception it holds.+ void visit_edges(GC::Cell::Visitor& visitor) const+ {+ m_result_or_exception.visit(+ [](SimpleException const&) { },+ [&](JS::Completion const& completion) { visitor.visit(completion.value()); },+ [&](auto const& value) { GC::visit_capture_member(visitor, value); });+ }+private:// https://webidl.spec.whatwg.org/#idl-exceptionsVariant<ValueType, SimpleException, GC::Ref<DOMException>, JS::Completion> m_result_or_exception;diff --git a/Libraries/LibWeb/WebIDL/ObservableArray.cpp b/Libraries/LibWeb/WebIDL/ObservableArray.cppindex 58cec922afa..00fb4806b4e 100644--- a/Libraries/LibWeb/WebIDL/ObservableArray.cpp+++ b/Libraries/LibWeb/WebIDL/ObservableArray.cpp@@ -65,14 +65,14 @@ void ObservableArray::visit_edges(JS::Cell::Visitor& visitor)visitor.visit(m_on_delete_an_indexed_value);}-void ObservableArray::set_on_set_an_indexed_value_callback(SetAnIndexedValueCallbackFunction&& callback)+void ObservableArray::set_on_set_an_indexed_value_callback(GC::Ref<GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>> callback){- m_on_set_an_indexed_value = GC::create_function(GC::Heap::the(), move(callback));+ m_on_set_an_indexed_value = callback;}-void ObservableArray::set_on_delete_an_indexed_value_callback(DeleteAnIndexedValueCallbackFunction&& callback)+void ObservableArray::set_on_delete_an_indexed_value_callback(GC::Ref<GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>> callback){- m_on_delete_an_indexed_value = GC::create_function(GC::Heap::the(), move(callback));+ m_on_delete_an_indexed_value = callback;}u32 ObservableArray::length() constdiff --git a/Libraries/LibWeb/WebIDL/ObservableArray.h b/Libraries/LibWeb/WebIDL/ObservableArray.hindex 36b91705715..f063bd6d7cd 100644--- a/Libraries/LibWeb/WebIDL/ObservableArray.h+++ b/Libraries/LibWeb/WebIDL/ObservableArray.h@@ -33,8 +33,8 @@ public:using SetAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(u32 index, JS::Value&)>;using DeleteAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(JS::Value)>;- void set_on_set_an_indexed_value_callback(SetAnIndexedValueCallbackFunction&& callback);- void set_on_delete_an_indexed_value_callback(DeleteAnIndexedValueCallbackFunction&& callback);+ void set_on_set_an_indexed_value_callback(GC::Ref<GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>> callback);+ void set_on_delete_an_indexed_value_callback(GC::Ref<GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>> callback);GC::Ref<JS::Object> array_object() const { return m_array_object; }diff --git a/Libraries/LibWeb/WebIDL/Promise.cpp b/Libraries/LibWeb/WebIDL/Promise.cppindex 17f5a9dc92b..ae6c7cb43e4 100644--- a/Libraries/LibWeb/WebIDL/Promise.cpp+++ b/Libraries/LibWeb/WebIDL/Promise.cpp@@ -188,7 +188,7 @@ GC::Ref<Promise> react_to_promise(Promise const& promise, GC::Ptr<ReactionSteps>auto& vm = realm.vm();// 1. Let onFulfilledSteps be the following steps given argument V:- auto on_fulfilled_steps = [&realm, on_fulfilled_callback = move(on_fulfilled_callback)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto on_fulfilled_steps = GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(realm.heap(), GC::captures(realm, on_fulfilled_callback), [](auto& realm, GC::Ptr<ReactionSteps>& on_fulfilled_callback, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {// 1. Let value be the result of converting V to an IDL value of type T.auto value = vm.argument(0);@@ -199,13 +199,13 @@ GC::Ref<Promise> react_to_promise(Promise const& promise, GC::Ptr<ReactionSteps>// 3. Return result, converted to an ECMAScript value.return result;- };+ });// 2. Let onFulfilled be CreateBuiltinFunction(onFulfilledSteps, 1, "", « »):- auto on_fulfilled = JS::NativeFunction::create(realm, move(on_fulfilled_steps), 1);+ auto on_fulfilled = JS::NativeFunction::create(realm, on_fulfilled_steps, 1);// 3. Let onRejectedSteps be the following steps given argument R:- auto on_rejected_steps = [&realm, on_rejected_callback = move(on_rejected_callback)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto on_rejected_steps = GC::create_function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>(realm.heap(), GC::captures(realm, on_rejected_callback), [](auto& realm, GC::Ptr<ReactionSteps>& on_rejected_callback, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {// 1. Let reason be the result of converting R to an IDL value of type any.auto reason = vm.argument(0);@@ -216,10 +216,10 @@ GC::Ref<Promise> react_to_promise(Promise const& promise, GC::Ptr<ReactionSteps>// 3. Return result, converted to an ECMAScript value.return result;- };+ });// 4. Let onRejected be CreateBuiltinFunction(onRejectedSteps, 1, "", « »):- auto on_rejected = JS::NativeFunction::create(realm, move(on_rejected_steps), 1);+ auto on_rejected = JS::NativeFunction::create(realm, on_rejected_steps, 1);// 5. Let constructor be promise.[[Promise]].[[Realm]].[[Intrinsics]].[[%Promise%]].auto constructor = realm.intrinsics().promise_constructor();@@ -314,7 +314,7 @@ struct WaitForAllResults : JS::Cell {GC_DEFINE_ALLOCATOR(WaitForAllResults);// https://webidl.spec.whatwg.org/#wait-for-all-void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Function<void(Vector<JS::Value> const&)> success_steps, Function<void(JS::Value)> failure_steps)+void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, GC::Ref<GC::Function<void(Vector<JS::Value> const&)>> success_steps, GC::Ref<GC::Function<void(JS::Value)>> failure_steps){// FIXME: Fix spec typo, fullfilled --> fulfilled// 1. Let fullfilledCount be 0.@@ -324,7 +324,7 @@ void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Funauto rejected = false;// 3. Let rejectionHandlerSteps be the following steps given arg:- auto rejection_handler_steps = [rejected, failure_steps = GC::create_function(GC::Heap::the(), move(failure_steps))](JS::VM& vm) mutable -> JS::ThrowCompletionOr<JS::Value> {+ auto rejection_handler_steps = GC::create_function(realm.heap(), GC::captures(rejected, failure_steps), [](bool& rejected, GC::Ref<GC::Function<void(JS::Value)>>& failure_steps, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {// 1. If rejected is true, abort these steps.if (rejected)return JS::js_undefined();@@ -336,10 +336,10 @@ void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Funfailure_steps->function()(vm.argument(0));return JS::js_undefined();- };+ });// 4. Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, 1, "", « »):- auto rejection_handler = JS::NativeFunction::create(realm, move(rejection_handler_steps), 1);+ auto rejection_handler = JS::NativeFunction::create(realm, rejection_handler_steps, 1);// 5. Let total be promises’s size.auto total = promises.size();@@ -347,7 +347,7 @@ void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Fun// 6. If total is 0, then:if (total == 0) {// 1. Queue a microtask to perform successSteps given « ».- HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), [success_steps = GC::create_function(GC::Heap::the(), move(success_steps))] {+ HTML::queue_a_microtask(nullptr, GC::create_function(GC::Heap::the(), GC::captures(success_steps), [](auto& success_steps) {success_steps->function()({});}));@@ -361,7 +361,7 @@ void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Fun// 8. Let result be a list containing total null values.// Handled in WaitForAllResults- auto results = GC::Heap::the().allocate<WaitForAllResults>(GC::create_function(GC::Heap::the(), move(success_steps)), total);+ auto results = GC::Heap::the().allocate<WaitForAllResults>(success_steps, total);// 9. For each promise of promises:for (auto promise : promises) {@@ -370,7 +370,7 @@ void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Fun// FIXME: This should be fulfillmentHandlerSteps// 2. Let fulfillmentHandler be the following steps given arg:- auto fulfillment_handler_steps = [results, promise_index](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto fulfillment_handler_steps = GC::create_function(realm.heap(), GC::captures(results, promise_index), [](GC::Ref<WaitForAllResults>& results, int& promise_index, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {auto arg = vm.argument(0);// 1. Set result[promiseIndex] to arg.@@ -384,10 +384,10 @@ void wait_for_all(JS::Realm& realm, ReadonlySpan<GC::Ref<Promise>> promises, Funresults->success_steps->function()(results->result);return JS::js_undefined();- };+ });// 3. Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, 1, "", « »):- auto fulfillment_handler = JS::NativeFunction::create(realm, move(fulfillment_handler_steps), 1);+ auto fulfillment_handler = JS::NativeFunction::create(realm, fulfillment_handler_steps, 1);// 4. Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).static_cast<JS::Promise&>(*promise->promise()).perform_then(fulfillment_handler, rejection_handler, nullptr);@@ -404,24 +404,24 @@ GC::Ref<Promise> get_promise_for_wait_for_all(JS::Realm& realm, ReadonlySpan<GC:auto promise = create_promise(realm);// 2. Let successSteps be the following steps, given results:- auto success_steps = [&realm, promise](Vector<JS::Value> const& results) {+ auto success_steps = GC::create_function(realm.heap(), GC::captures(realm, promise), [](auto& realm, auto& promise, Vector<JS::Value> const& results) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Resolve promise with results.auto sequence = JS::Array::create_from(realm, results);resolve_promise(realm, promise, sequence);- };+ });// 3. Let failureSteps be the following steps, given reason:- auto failure_steps = [&realm, promise](JS::Value reason) {+ auto failure_steps = GC::create_function(realm.heap(), GC::captures(realm, promise), [](auto& realm, auto& promise, JS::Value reason) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };// 1. Reject promise with reason.reject_promise(realm, promise, reason);- };+ });// 4. Wait for all with promises, given successSteps and failureSteps.- wait_for_all(realm, promises, move(success_steps), move(failure_steps));+ wait_for_all(realm, promises, success_steps, failure_steps);// 5. Return promise.return promise;diff --git a/Libraries/LibWeb/WebIDL/Promise.h b/Libraries/LibWeb/WebIDL/Promise.hindex 2143f1020aa..761c7b3c6ef 100644--- a/Libraries/LibWeb/WebIDL/Promise.h+++ b/Libraries/LibWeb/WebIDL/Promise.h@@ -48,7 +48,7 @@ WEB_API GC::Ref<Promise> upon_fulfillment(Promise const&, GC::Ref<ReactionSteps>WEB_API GC::Ref<Promise> upon_rejection(Promise const&, GC::Ref<ReactionSteps>);WEB_API void mark_promise_as_handled(Promise const&);WEB_API bool is_promise_fulfilled(Promise const&);-WEB_API void wait_for_all(JS::Realm&, ReadonlySpan<GC::Ref<Promise>> promises, Function<void(Vector<JS::Value> const&)> success_steps, Function<void(JS::Value)> failure_steps);+WEB_API void wait_for_all(JS::Realm&, ReadonlySpan<GC::Ref<Promise>> promises, GC::Ref<GC::Function<void(Vector<JS::Value> const&)>> success_steps, GC::Ref<GC::Function<void(JS::Value)>> failure_steps);WEB_API GC::Ref<Promise> get_promise_for_wait_for_all(JS::Realm&, ReadonlySpan<GC::Ref<Promise>> promises);// Non-spec, convenience methods.diff --git a/Libraries/LibWeb/WebLocks/AbstractOperations.cpp b/Libraries/LibWeb/WebLocks/AbstractOperations.cppindex ac64dded6b8..4f0860245ff 100644--- a/Libraries/LibWeb/WebLocks/AbstractOperations.cpp+++ b/Libraries/LibWeb/WebLocks/AbstractOperations.cpp@@ -34,7 +34,7 @@ static HTML::ParallelQueue& lock_task_queue()void web_locks_queue_task(JS::Realm* realm, GC::Cell* cell, void (*steps)(JSVM*, void*)){- lock_task_queue().enqueue(GC::create_function(realm->heap(), [realm = GC::Ref { *realm }, cell = GC::Ref { *cell }, steps] {+ lock_task_queue().enqueue(GC::create_function(realm->heap(), GC::captures(GC::Ref { *realm }, GC::Ref { *cell }, steps), [](auto& realm, auto& cell, auto& steps) {HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };steps(JS::HostABI::vm_to_abi(realm->vm()), cell.ptr());}));@@ -43,7 +43,7 @@ void web_locks_queue_task(JS::Realm* realm, GC::Cell* cell, void (*steps)(JSVM*,void web_locks_queue_callback_task(WebIDL::CallbackType* callback, GC::Cell* cell, void (*steps)(JSVM*, void*)){auto& callback_context = callback->callback_context;- HTML::queue_global_task(HTML::Task::Source::WebLocks, callback_context->global_object(), GC::create_function(callback_context->realm().heap(), [callback = GC::Ref { *callback }, cell = GC::Ref { *cell }, steps] {+ HTML::queue_global_task(HTML::Task::Source::WebLocks, callback_context->global_object(), GC::create_function(callback_context->realm().heap(), GC::captures(GC::Ref { *callback }, GC::Ref { *cell }, steps), [](auto& callback, auto& cell, auto& steps) {HTML::TemporaryExecutionContext execution_context { callback->callback_context, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };steps(JS::HostABI::vm_to_abi(callback->callback_context->realm().vm()), cell.ptr());}));diff --git a/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp b/Libraries/LibWeb/WebRTC/RTCPeerConnection.cppindex 22454793a0e..cd72415ba04 100644--- a/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp+++ b/Libraries/LibWeb/WebRTC/RTCPeerConnection.cpp@@ -242,8 +242,8 @@ void RTCPeerConnection::close_the_connection_algorithm(bool disappear)// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createofferGC::Ref<WebIDL::Promise> RTCPeerConnection::create_offer(RTCOfferOptions const& options){- return chain_operation(GC::create_function(heap(), [this, options](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- return create_offer_impl(options)->promise();+ return chain_operation(GC::create_function(heap(), GC::captures(*this, options), [](auto& self, auto& options, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ return self.create_offer_impl(options)->promise();}));}@@ -289,8 +289,8 @@ GC::Ref<WebIDL::Promise> RTCPeerConnection::create_an_offer()// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createanswerGC::Ref<WebIDL::Promise> RTCPeerConnection::create_answer(RTCAnswerOptions const& options){- return chain_operation(GC::create_function(heap(), [this, options](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- return create_answer_impl(options)->promise();+ return chain_operation(GC::create_function(heap(), GC::captures(*this, options), [](auto& self, auto& options, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ return self.create_answer_impl(options)->promise();}));}@@ -335,8 +335,8 @@ GC::Ref<WebIDL::Promise> RTCPeerConnection::create_an_answer()// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setlocaldescriptionGC::Ref<WebIDL::Promise> RTCPeerConnection::set_local_description(RTCLocalSessionDescriptionInit const& description){- return chain_operation(GC::create_function(heap(), [this, description](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- return set_local_description_impl(description)->promise();+ return chain_operation(GC::create_function(heap(), GC::captures(*this, description), [](auto& self, auto& description, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ return self.set_local_description_impl(description)->promise();}));}@@ -375,12 +375,12 @@ GC::Ref<WebIDL::Promise> RTCPeerConnection::set_local_description_impl(RTCLocalS}if (sdp.is_empty() && type != Bindings::RTCSdpType::Rollback) {auto generated = type == Bindings::RTCSdpType::Offer ? create_an_offer() : create_an_answer();- return WebIDL::react_to_promise(generated, GC::create_function(heap(), [this, type](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {- if (m_is_closed)+ return WebIDL::react_to_promise(generated, GC::create_function(heap(), GC::captures(*this, type), [](auto& self, auto& type, JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {+ if (self.m_is_closed)return WebIDL::InvalidStateError::create("RTCPeerConnection is closed"_utf16);auto sdp_value = TRY(value.as_object().get("sdp"_utf16_fly_string));- auto generated_sdp = TRY(sdp_value.to_utf16_string(relevant_realm().vm()));- return set_a_local_description(type, generated_sdp)->promise();+ auto generated_sdp = TRY(sdp_value.to_utf16_string(self.relevant_realm().vm()));+ return self.set_a_local_description(type, generated_sdp)->promise();}),nullptr);}@@ -405,8 +405,8 @@ GC::Ref<WebIDL::Promise> RTCPeerConnection::set_a_local_description(Bindings::RT// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setremotedescriptionGC::Ref<WebIDL::Promise> RTCPeerConnection::set_remote_description(RTCSessionDescriptionInit const& description){- return chain_operation(GC::create_function(heap(), [this, description](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- return set_remote_description_impl(description)->promise();+ return chain_operation(GC::create_function(heap(), GC::captures(*this, description), [](auto& self, auto& description, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ return self.set_remote_description_impl(description)->promise();}));}@@ -476,8 +476,8 @@ GC::RootVector<GC::Ref<RTCRtpReceiver>> RTCPeerConnection::get_receivers() const// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addicecandidateGC::Ref<WebIDL::Promise> RTCPeerConnection::add_ice_candidate(RTCIceCandidateInit const& candidate){- return chain_operation(GC::create_function(heap(), [this, candidate](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {- return add_ice_candidate_impl(candidate)->promise();+ return chain_operation(GC::create_function(heap(), GC::captures(*this, candidate), [](auto& self, auto& candidate, JS::Value) -> WebIDL::ExceptionOr<JS::Value> {+ return self.add_ice_candidate_impl(candidate)->promise();}));}@@ -800,9 +800,9 @@ void RTCPeerConnection::restart_ice()void RTCPeerConnection::update_negotiation_needed_flag(){- HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), [this] {- if (!m_is_closed && m_signaling_state == Bindings::RTCSignalingState::Stable)- on_negotiation_needed_received();+ HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ if (!self.m_is_closed && self.m_signaling_state == Bindings::RTCSignalingState::Stable)+ self.on_negotiation_needed_received();}));}diff --git a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cpp b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cppindex e4ef964ad3a..82b135d7f63 100644--- a/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cpp+++ b/Libraries/LibWeb/WebRTC/RTCRtpScriptTransformer.cpp@@ -42,7 +42,7 @@ WebIDL::ExceptionOr<GC::Ref<RTCRtpScriptTransformer>> RTCRtpScriptTransformer::c// on the parent side), so the pull is a no-op.// NB: Streams only lets C++ set up a ReadableStream of arbitrary chunks as the readable side of a TransformStream,// so frames are enqueued into one whose writable side nothing writes to.- auto readable_transform = GC::create_function(realm.heap(), [transformer](JS::Value) -> GC::Ref<WebIDL::Promise> {+ auto readable_transform = GC::create_function(realm.heap(), GC::captures(transformer), [](auto& transformer, JS::Value) -> GC::Ref<WebIDL::Promise> {return WebIDL::create_resolved_promise(transformer->relevant_realm(), JS::js_undefined());});transformer->m_readable_source = Streams::TransformStream::create(realm);@@ -51,7 +51,7 @@ WebIDL::ExceptionOr<GC::Ref<RTCRtpScriptTransformer>> RTCRtpScriptTransformer::c// 3. Let writeAlgorithm be an action that runs writeEncodedData with this as// parameter and frame as input, given frame.- auto write_algorithm = GC::create_function(realm.heap(), [transformer](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {+ auto write_algorithm = GC::create_function(realm.heap(), GC::captures(transformer), [](auto& transformer, JS::Value chunk) -> GC::Ref<WebIDL::Promise> {// writeEncodedData step: hand the transformed frame to [[frameSource]] for// continued pipeline processing (decode, playback, or send-out for senders).if (transformer->m_write_encoded_data)diff --git a/Libraries/LibWeb/WebRTC/RTCRtpSender.cpp b/Libraries/LibWeb/WebRTC/RTCRtpSender.cppindex 59ecdb36baf..70638c1cb64 100644--- a/Libraries/LibWeb/WebRTC/RTCRtpSender.cpp+++ b/Libraries/LibWeb/WebRTC/RTCRtpSender.cpp@@ -156,16 +156,16 @@ GC::Ref<WebIDL::Promise> RTCRtpSender::set_parameters(RTCRtpSendParameters const// 8. In parallel, configure the media stack to use parameters to transmit sender.[[SenderTrack]].// FIXME: actually wire `parameters` into the media stack (bitrate caps, encoding rid, etc).- HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), [this, p, parameters] {+ HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), GC::captures(*this, p, parameters), [](auto& self, auto& p, auto& parameters) {// Promise resolution calls into JS and needs a running execution context on the VM stack; tasks don't// come with one by default.- auto& realm = relevant_realm();+ auto& realm = self.relevant_realm();HTML::TemporaryExecutionContext context(realm);// 8.1. If the media stack is successfully configured with parameters, queue a task to run the following steps:// 8.1.1. Set sender.[[LastReturnedParameters]] to null.- m_last_returned_parameters = {};+ self.m_last_returned_parameters = {};// 8.1.2. Set sender.[[SendEncodings]] to parameters.encodings.- m_send_encodings = parameters.encodings;+ self.m_send_encodings = parameters.encodings;// 8.1.3. Resolve p with undefined.WebIDL::resolve_promise(realm, p, JS::js_undefined());// 8.2. If any error occurred while configuring the media stack, queue a task to run the following steps:@@ -218,8 +218,8 @@ RTCRtpSendParameters RTCRtpSender::get_parameters()m_last_returned_parameters = result;// 5. Queue a task that sets sender.[[LastReturnedParameters]] to null.- HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), [this] {- m_last_returned_parameters = {};+ HTML::queue_a_task(HTML::Task::Source::Networking, nullptr, nullptr, GC::create_function(heap(), GC::captures(*this), [](auto& self) {+ self.m_last_returned_parameters = {};}));// 6. Return result.diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cppindex d094d66ba28..9935836549d 100644--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp@@ -115,7 +115,7 @@ WebIDL::ExceptionOr<GC::Ref<WebSocket>> WebSocket::create(HTML::WindowOrWorkerGl// 11. Let client be this’s relevant settings object.// 12. Run this step in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [web_socket, url_record, protocols_sequence = move(protocols_sequence), client = GC::Ref { relevant_settings_object }]() {+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(web_socket, url_record, move(protocols_sequence), GC::Ref { relevant_settings_object }), [](auto& web_socket, auto& url_record, auto& protocols_sequence, auto& client) {// 1. Establish a WebSocket connection given urlRecord, protocols, and client. [FETCH]// AD-HOC: We don't yet implement this method to spec, so it's possible for the connection to fail before we// make a Requests::WebSocket. If so, we need to manually error and close it.@@ -424,7 +424,7 @@ WebIDL::ExceptionOr<void> WebSocket::send(WebSocketSendData const& data)// NB: A sent message is handed to the network process right away, so it counts as transmitted to the network once// the event loop has moved on from the current task.if (is_open && message_size > 0) {- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), [self = GC::Ref { *this }, message_size] {+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }, message_size), [](auto& self, auto& message_size) {self->m_buffered_amount -= message_size;}));}@@ -436,18 +436,18 @@ WebIDL::ExceptionOr<void> WebSocket::send(WebSocketSendData const& data)void WebSocket::on_open(){// When the WebSocket connection is established, the user agent must queue a task to run these steps:- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// AD-HOC: Matching other engines, do not fire an open event if close() was called before this task ran.- if (m_ready_state != Requests::WebSocket::ReadyState::Connecting)+ if (self.m_ready_state != Requests::WebSocket::ReadyState::Connecting)return;// 1. Change the ready state to OPEN (1).- set_ready_state(Requests::WebSocket::ReadyState::Open);+ self.set_ready_state(Requests::WebSocket::ReadyState::Open);// 2. Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]// 3. Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]// 4. Fire an event named open at the WebSocket object.- dispatch_event(DOM::Event::create(HTML::EventNames::open, HighResolutionTime::current_high_resolution_time(relevant_global_object())));+ self.dispatch_event(DOM::Event::create(HTML::EventNames::open, HighResolutionTime::current_high_resolution_time(self.relevant_global_object())));}));}@@ -455,12 +455,12 @@ void WebSocket::on_open()void WebSocket::on_message(ByteBuffer message, bool is_text){// When a WebSocket message has been received with type type and data data, the user agent must queue a task to follow these steps:- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this, message = move(message), is_text] mutable {+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this, move(message), is_text), [](auto& self, auto& message, auto& is_text) {// 1. If ready state is not OPEN (1), then return.- if (m_ready_state != Requests::WebSocket::ReadyState::Open)+ if (self.m_ready_state != Requests::WebSocket::ReadyState::Open)return;- auto& realm = HTML::relevant_realm(relevant_global_object());+ auto& realm = HTML::relevant_realm(self.relevant_global_object());// 2. Let dataForEvent be determined by switching on type and binary type:auto data_for_event = [&]() -> JS::Value {@@ -470,12 +470,12 @@ void WebSocket::on_message(ByteBuffer message, bool is_text)return JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf8(message));}// -> type indicates that the data is Binary and binary type is "blob"- if (m_binary_type == Bindings::BinaryType::Blob) {+ if (self.m_binary_type == Bindings::BinaryType::Blob) {// a new Blob object, created in the relevant Realm of the WebSocket object, that represents data as its raw data [FILEAPI]return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, FileAPI::Blob::create(move(message), Utf16String {}));}// -> type indicates that the data is Binary and binary type is "arraybuffer"- if (m_binary_type == Bindings::BinaryType::Arraybuffer) {+ if (self.m_binary_type == Bindings::BinaryType::Arraybuffer) {// a new ArrayBuffer object, created in the relevant Realm of the WebSocket object, whose contents are datareturn JS::ArrayBuffer::create(realm, move(message));}@@ -489,7 +489,7 @@ void WebSocket::on_message(ByteBuffer message, bool is_text)HTML::MessageEventInit event_init;event_init.data = data_for_event;- dispatch_event(HTML::MessageEvent::create(realm.global_object(), HTML::EventNames::message, event_init, m_url.origin()));+ self.dispatch_event(HTML::MessageEvent::create(realm.global_object(), HTML::EventNames::message, event_init, self.m_url.origin()));}));}@@ -499,11 +499,11 @@ void WebSocket::on_closing_handshake_started()// When the WebSocket closing handshake is started, the user agent must queue a task to change the ready state to// CLOSING (2). (If the close() method was called, the ready state will already be set to CLOSING (2) when this task// runs.) [WSP]- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// AD-HOC: Matching other engines, a WebSocket that an error event has already closed stays CLOSED.- if (m_ready_state == Requests::WebSocket::ReadyState::Closed)+ if (self.m_ready_state == Requests::WebSocket::ReadyState::Closed)return;- set_ready_state(Requests::WebSocket::ReadyState::Closing);+ self.set_ready_state(Requests::WebSocket::ReadyState::Closing);}));}@@ -511,13 +511,13 @@ void WebSocket::on_closing_handshake_started()void WebSocket::on_error(){// When the WebSocket connection is closed, possibly cleanly, the user agent must queue a task to run the following substeps:- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this] {+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {// 1. Change the ready state to CLOSED (3).- set_ready_state(Requests::WebSocket::ReadyState::Closed);+ self.set_ready_state(Requests::WebSocket::ReadyState::Closed);// 2. If the user agent was required to fail the WebSocket connection, or if the WebSocket connection was// closed after being flagged as full, fire an event named error at the WebSocket object. [WSP]- dispatch_event(DOM::Event::create(HTML::EventNames::error, HighResolutionTime::current_high_resolution_time(relevant_global_object())));+ self.dispatch_event(DOM::Event::create(HTML::EventNames::error, HighResolutionTime::current_high_resolution_time(self.relevant_global_object())));}));}@@ -525,16 +525,16 @@ void WebSocket::on_error()void WebSocket::on_close(u16 code, Utf16String reason, bool was_clean){// When the WebSocket connection is closed, possibly cleanly, the user agent must queue a task to run the following substeps:- HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this, code, reason = move(reason), was_clean] {+ HTML::queue_a_task(HTML::Task::Source::WebSocket, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this, code, move(reason), was_clean), [](auto& self, auto& code, auto& reason, auto& was_clean) {// 1. Change the ready state to CLOSED (3).- set_ready_state(Requests::WebSocket::ReadyState::Closed);+ self.set_ready_state(Requests::WebSocket::ReadyState::Closed);// 2. If [needed], fire an event named error at the WebSocket object. This is handled by the Protocol's WebSocketHTML::CloseEventInit event_init {};event_init.was_clean = was_clean;event_init.code = code;event_init.reason = reason;- dispatch_event(HTML::CloseEvent::create(HTML::EventNames::close, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object())));+ self.dispatch_event(HTML::CloseEvent::create(HTML::EventNames::close, event_init, HighResolutionTime::current_high_resolution_time(self.relevant_global_object())));}));}diff --git a/Libraries/LibWeb/WebVTT/Parser.h b/Libraries/LibWeb/WebVTT/Parser.hindex cd0c5f43265..d049b997827 100644--- a/Libraries/LibWeb/WebVTT/Parser.h+++ b/Libraries/LibWeb/WebVTT/Parser.h@@ -9,6 +9,7 @@#include <AK/Optional.h>#include <AK/Utf16String.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>namespace Web::WebVTT {@@ -23,3 +24,5 @@ struct ParsedCue {Optional<Vector<ParsedCue>> parse_webvtt_file(ReadonlyBytes);}++GC_UNTRACED_CAPTURE(Web::WebVTT::ParsedCue);diff --git a/Libraries/LibWeb/XHR/FormDataEntry.h b/Libraries/LibWeb/XHR/FormDataEntry.hindex 2f23880b6be..a500a8ec869 100644--- a/Libraries/LibWeb/XHR/FormDataEntry.h+++ b/Libraries/LibWeb/XHR/FormDataEntry.h@@ -23,6 +23,8 @@ struct FormDataEntry {Utf16String name;Value value;++ void visit_edges(auto& visitor) const { visitor.visit(value); }};struct FormDataEntryValueABI {diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cppindex d602ffbe18b..5f0fbe2d3d6 100644--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp@@ -153,16 +153,16 @@ void XMLHttpRequest::restart_timeout_timer()auto remaining = max(AK::Duration::zero(), AK::Duration::from_milliseconds(m_timeout) - elapsed);m_timeout_timer = Platform::Timer::create_single_shot(heap(), remaining, nullptr);auto request = NonnullRefPtr { *m_async_request };- m_timeout_timer->on_timeout = GC::create_function(heap(), [this, request, fetch_controller = m_fetch_controller] {- if (m_async_request.ptr() != request.ptr() || m_fetch_controller != fetch_controller)+ m_timeout_timer->on_timeout = GC::create_function(heap(), GC::captures(*this, request, m_fetch_controller), [](XMLHttpRequest& self, NonnullRefPtr<Fetch::Infrastructure::Request>& request, GC::Ref<Fetch::Infrastructure::FetchController>& fetch_controller) {+ if (self.m_async_request.ptr() != request.ptr() || self.m_fetch_controller != fetch_controller)return;- stop_timeout_timer();- m_async_request = nullptr;+ self.stop_timeout_timer();+ self.m_async_request = nullptr;if (!request->done()) {- m_timed_out = true;+ self.m_timed_out = true;fetch_controller->terminate();- MUST(handle_errors());+ MUST(self.handle_errors());}});m_timeout_timer->start();@@ -880,94 +880,94 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB// 7. Let processRequestBodyChunkLength, given a bytesLength, be these steps:// NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.// NOTE: `this` is kept alive by FetchAlgorithms using GC::HeapFunction.- auto process_request_body_chunk_length = [this, request_body_length](u64 bytes_length) {+ auto process_request_body_chunk_length = GC::create_function<void(u64)>(GC::Heap::the(), GC::captures(*this, request_body_length), [](XMLHttpRequest& self, auto& request_body_length, u64 bytes_length) {// AD-HOC: Fetch transmits the body again for each redirect, and runs process request end-of-body for a// null body, so ignore everything after the upload completed.// Spec issue: https://github.com/whatwg/xhr/issues/242- if (m_upload_complete)+ if (self.m_upload_complete)return;// 1. Increase requestBodyTransmitted by bytesLength.- m_request_body_transmitted += bytes_length;+ self.m_request_body_transmitted += bytes_length;// 2. If not roughly 50ms have passed since these steps were last invoked, then return.auto now = MonotonicTime::now();- bool enough_time_passed = !m_last_upload_progress_timestamp.has_value() || (now - m_last_upload_progress_timestamp.value()) >= AK::Duration::from_milliseconds(50);+ bool enough_time_passed = !self.m_last_upload_progress_timestamp.has_value() || (now - self.m_last_upload_progress_timestamp.value()) >= AK::Duration::from_milliseconds(50);if (!enough_time_passed)return;- m_last_upload_progress_timestamp = now;+ self.m_last_upload_progress_timestamp = now;// 3. If this’s upload listener flag is set, then fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.- if (m_upload_listener)- fire_progress_event(relevant_global_object(), m_upload_object, EventNames::progress,- m_request_body_transmitted, request_body_length);- };+ if (self.m_upload_listener)+ fire_progress_event(self.relevant_global_object(), self.m_upload_object, EventNames::progress,+ self.m_request_body_transmitted, request_body_length);+ });// 8. Let processRequestEndOfBody be these steps:// NOTE: request_body_length is captured by copy as to not UAF it when we leave `send()` and the callback gets called.// NOTE: `this` is kept alive by FetchAlgorithms using GC::HeapFunction.- auto process_request_end_of_body = [this, request_body_length]() {+ auto process_request_end_of_body = GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, request_body_length), [](XMLHttpRequest& self, auto& request_body_length) {// AD-HOC: Fetch transmits the body again for each redirect, and runs process request end-of-body for a// null body, so ignore everything after the upload completed.// Spec issue: https://github.com/whatwg/xhr/issues/242- if (m_upload_complete)+ if (self.m_upload_complete)return;// 1. Set this’s upload complete flag.- m_upload_complete = true;+ self.m_upload_complete = true;// 2. If this’s upload listener flag is unset, then return.- if (!m_upload_listener)+ if (!self.m_upload_listener)return;// 3. Fire a progress event named progress at this’s upload object with requestBodyTransmitted and requestBodyLength.- auto& associated_realm = HTML::relevant_realm(relevant_global_object());- fire_progress_event(associated_realm.global_object(), m_upload_object, EventNames::progress,- m_request_body_transmitted, request_body_length);+ auto& associated_realm = HTML::relevant_realm(self.relevant_global_object());+ fire_progress_event(associated_realm.global_object(), self.m_upload_object, EventNames::progress,+ self.m_request_body_transmitted, request_body_length);// 4. Fire a progress event named load at this’s upload object with requestBodyTransmitted and requestBodyLength.- fire_progress_event(associated_realm.global_object(), m_upload_object, EventNames::load,- m_request_body_transmitted, request_body_length);+ fire_progress_event(associated_realm.global_object(), self.m_upload_object, EventNames::load,+ self.m_request_body_transmitted, request_body_length);// 5. Fire a progress event named loadend at this’s upload object with requestBodyTransmitted and requestBodyLength.- fire_progress_event(associated_realm.global_object(), m_upload_object, EventNames::loadend,- m_request_body_transmitted, request_body_length);- };+ fire_progress_event(associated_realm.global_object(), self.m_upload_object, EventNames::loadend,+ self.m_request_body_transmitted, request_body_length);+ });// 9. Let processResponse, given a response, be these steps:// NOTE: `this` is kept alive by FetchAlgorithms using GC::HeapFunction.- auto process_response = [this](GC::Ref<Fetch::Infrastructure::ResponseView> response) {+ auto process_response = GC::create_function(GC::Heap::the(), GC::captures(*this), [](XMLHttpRequest& self, GC::Ref<Fetch::Infrastructure::ResponseView> response) {// 1. Set this’s response to response.- m_response = response;+ self.m_response = response;// 2. Handle errors for this.// NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.- MUST(handle_errors());+ MUST(self.handle_errors());// 3. If this’s response is a network error, then return.- if (m_response->is_network_error())+ if (self.m_response->is_network_error())return;// 4. Set this’s state to headers received.- m_state = State::HeadersReceived;- update_pending_activity();+ self.m_state = State::HeadersReceived;+ self.update_pending_activity();// 5. Fire an event named readystatechange at this.- dispatch_event(create_associated_event(EventNames::readystatechange));+ self.dispatch_event(self.create_associated_event(EventNames::readystatechange));// 6. If this’s state is not headers received, then return.- if (m_state != State::HeadersReceived)+ if (self.m_state != State::HeadersReceived)return;// 7. If this’s response’s body is null, then run handle response end-of-body for this and return.- if (!m_response->body()) {+ if (!self.m_response->body()) {// NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.- MUST(handle_response_end_of_body());+ MUST(self.handle_response_end_of_body());return;}// 8. Let length be the result of extracting a length from this’s response’s header list.- auto length = m_response->header_list()->extract_length();+ auto length = self.m_response->header_list()->extract_length();// 9. If length is not an integer, then set it to 0.if (!length.has<u64>())@@ -975,70 +975,70 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB// Pre-allocate received bytes buffer if Content-Length is known.if (length.get<u64>() > 0)- m_received_bytes.ensure_capacity(length.get<u64>());+ self.m_received_bytes.ensure_capacity(length.get<u64>());// 10. Let processBodyChunk given bytes be these steps:- auto process_body_chunks = GC::create_function(GC::Heap::the(), [this, length](ByteBuffer byte_buffer) {+ auto process_body_chunks = GC::create_function(GC::Heap::the(), GC::captures(self, length.get<u64>()), [](XMLHttpRequest& self, u64& length, ByteBuffer byte_buffer) {// 1. Append bytes to this’s received bytes.- m_received_bytes.append(byte_buffer);+ self.m_received_bytes.append(byte_buffer);// 2. If not roughly 50ms have passed since these steps were last invoked, then return.auto now = MonotonicTime::now();- bool enough_time_passed = !m_last_download_progress_timestamp.has_value() || (now - m_last_download_progress_timestamp.value()) >= AK::Duration::from_milliseconds(50);+ bool enough_time_passed = !self.m_last_download_progress_timestamp.has_value() || (now - self.m_last_download_progress_timestamp.value()) >= AK::Duration::from_milliseconds(50);if (!enough_time_passed)return;- m_last_download_progress_timestamp = now;+ self.m_last_download_progress_timestamp = now;// 3. If this’s state is headers received, then set this’s state to loading.- if (m_state == State::HeadersReceived)- m_state = State::Loading;- update_pending_activity();+ if (self.m_state == State::HeadersReceived)+ self.m_state = State::Loading;+ self.update_pending_activity();// 4. Fire an event named readystatechange at this.// Spec Note: Web compatibility is the reason readystatechange fires more often than this’s state changes.- auto& associated_realm = HTML::relevant_realm(relevant_global_object());- dispatch_event(create_associated_event(EventNames::readystatechange));+ auto& associated_realm = HTML::relevant_realm(self.relevant_global_object());+ self.dispatch_event(self.create_associated_event(EventNames::readystatechange));// 5. Fire a progress event named progress at this with this’s received bytes’s length and length.- fire_progress_event(associated_realm.global_object(), *this, EventNames::progress,- m_received_bytes.size(), length.get<u64>());+ fire_progress_event(associated_realm.global_object(), self, EventNames::progress,+ self.m_received_bytes.size(), length);});// 11. Let processEndOfBody be this step: run handle response end-of-body for this.- auto process_end_of_body = GC::create_function(GC::Heap::the(), [this]() {+ auto process_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(self), [](XMLHttpRequest& self) {// NOTE: This cannot throw, as `handle_response_end_of_body` only throws in a synchronous context.- MUST(handle_response_end_of_body());+ MUST(self.handle_response_end_of_body());});// 12. Let processBodyError be these steps:- auto process_body_error = GC::create_function(GC::Heap::the(), [this](JS::Value) {+ auto process_body_error = GC::create_function(GC::Heap::the(), GC::captures(self), [](XMLHttpRequest& self, JS::Value) {// 1. Set this’s response to a network error.- m_response = Fetch::Infrastructure::ResponseView::network_error("A network error occurred processing body."_string);+ self.m_response = Fetch::Infrastructure::ResponseView::network_error("A network error occurred processing body."_string);// 2. Run handle errors for this.// NOTE: This cannot throw, as `handle_errors` only throws in a synchronous context.- MUST(handle_errors());+ MUST(self.handle_errors());});// 13. Incrementally read this’s response’s body, given processBodyChunk, processEndOfBody, processBodyError, and this’s relevant global object.- auto global_object = GC::Ref<JS::Object> { relevant_global_object() };- response->body()->incrementally_read(HTML::relevant_realm(relevant_global_object()), process_body_chunks, process_end_of_body, process_body_error, global_object);- };+ auto global_object = GC::Ref<JS::Object> { self.relevant_global_object() };+ response->body()->incrementally_read(HTML::relevant_realm(self.relevant_global_object()), process_body_chunks, process_end_of_body, process_body_error, global_object);+ });// 10. Set this’s fetch controller to the result of fetching req with processRequestBodyChunkLength set to processRequestBodyChunkLength, processRequestEndOfBody set to processRequestEndOfBody, and processResponse set to processResponse.Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_request_body_chunk_length = move(process_request_body_chunk_length);- fetch_algorithms_input.process_request_end_of_body = move(process_request_end_of_body);- fetch_algorithms_input.process_response = move(process_response);+ fetch_algorithms_input.process_request_body_chunk_length = process_request_body_chunk_length;+ fetch_algorithms_input.process_request_end_of_body = process_request_end_of_body;+ fetch_algorithms_input.process_response = process_response;m_fetch_controller = Fetch::Fetching::fetch(associated_realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));// AD-HOC: Stopping the fetch, as aborting the document does, discards it without a response. Hand this an// aborted network error instead, so that it fires abort as for a canceled fetch.- m_fetch_controller->set_stop_steps(GC::create_function(heap(), [this, fetch_controller = m_fetch_controller] {- HTML::queue_global_task(HTML::Task::Source::Networking, relevant_global_object(), GC::create_function(heap(), [this, fetch_controller] {- if (m_fetch_controller != fetch_controller)+ m_fetch_controller->set_stop_steps(GC::create_function(heap(), GC::captures(*this, m_fetch_controller), [](XMLHttpRequest& self, GC::Ref<Fetch::Infrastructure::FetchController>& fetch_controller) {+ HTML::queue_global_task(HTML::Task::Source::Networking, self.relevant_global_object(), GC::create_function(self.heap(), GC::captures(self, fetch_controller), [](XMLHttpRequest& self, GC::Ref<Fetch::Infrastructure::FetchController>& fetch_controller) {+ if (self.m_fetch_controller != fetch_controller)return;- m_response = Fetch::Infrastructure::ResponseView::aborted_network_error();- MUST(handle_errors());+ self.m_response = Fetch::Infrastructure::ResponseView::aborted_network_error();+ MUST(self.handle_errors());}));}));@@ -1060,28 +1060,28 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestBauto did_time_out = Fetch::Fetching::RefCountedFlag::create(false);// 2. Let processResponseConsumeBody, given a response and nullOrFailureOrBytes, be these steps:- auto process_response_consume_body = [this, processed_response, did_time_out](GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes null_or_failure_or_bytes) {+ auto process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(*this, processed_response, did_time_out), [](XMLHttpRequest& self, NonnullRefPtr<Fetch::Fetching::RefCountedFlag>& processed_response, NonnullRefPtr<Fetch::Fetching::RefCountedFlag>& did_time_out, GC::Ref<Fetch::Infrastructure::ResponseView> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes null_or_failure_or_bytes) {// AD-HOC: Leave this's response and received bytes alone once send() returned for a timeout.if (did_time_out->value())return;// 1. If nullOrFailureOrBytes is not failure, then set this’s response to response.if (!null_or_failure_or_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>())- m_response = response;+ self.m_response = response;// 2. If nullOrFailureOrBytes is a byte sequence, then append nullOrFailureOrBytes to this’s received bytes.if (null_or_failure_or_bytes.has<Core::ImmutableBytes>()) {// NOTE: We are not in a context where we can throw if this fails due to OOM.- m_received_bytes.append(null_or_failure_or_bytes.get<Core::ImmutableBytes>().bytes());+ self.m_received_bytes.append(null_or_failure_or_bytes.get<Core::ImmutableBytes>().bytes());}// 3. Set processedResponse to true.processed_response->set_value(true);- };+ });// 3. Set this’s fetch controller to the result of fetching req with processResponseConsumeBody set to processResponseConsumeBody and useParallelQueue set to true.Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::SyncAccumulate };- fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);+ fetch_algorithms_input.process_response_consume_body = process_response_consume_body;m_fetch_controller = Fetch::Fetching::fetch(associated_realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)), Fetch::Fetching::UseParallelQueue::Yes);// 4. Let now be the present time.@@ -1089,9 +1089,9 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestBif (m_timeout != 0) {stop_timeout_timer();m_timeout_timer = Platform::Timer::create_single_shot(heap(), AK::Duration::from_milliseconds(m_timeout), nullptr);- m_timeout_timer->on_timeout = GC::create_function(GC::Heap::the(), [this, did_time_out]() {+ m_timeout_timer->on_timeout = GC::create_function(GC::Heap::the(), GC::captures(*this, did_time_out), [](XMLHttpRequest& self, NonnullRefPtr<Fetch::Fetching::RefCountedFlag>& did_time_out) {did_time_out->set_value(true);- stop_timeout_timer();+ self.stop_timeout_timer();});m_timeout_timer->start();}@@ -1110,7 +1110,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB// AD-HOC: We don't update the rendering when pausing: That runs author callbacks (e.g., rAF callbacks),// which must not run inside a blocked send() — itself possibly invoked from within a microtask.auto pause_handle = HTML::current_event_loop().pause(HTML::EventLoop::UpdateTheRendering::No);- Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), [processed_response, did_time_out]() {+ Platform::EventLoopPlugin::the().spin_until(GC::create_function(GC::Heap::the(), GC::captures(processed_response, did_time_out), [](auto& processed_response, auto& did_time_out) {return processed_response->value() || did_time_out->value();}));}diff --git a/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp b/Libraries/LibWeb/XML/XMLDocumentBuilder.cppindex 35e43b1403d..3fc1a12be17 100644--- a/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp+++ b/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp@@ -218,8 +218,8 @@ void XMLDocumentBuilder::element_end(Utf16FlyString const& name)// 2. Spin the event loop until the parser's Document has no style sheet that is blocking scripts and the pending parsing-blocking script's "ready to be parser-executed" flag is set.if (m_document->has_a_style_sheet_that_is_blocking_scripts() || !pending_parsing_blocking_script->is_ready_to_be_parser_executed()) {- HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), [&] {- return !m_document->has_a_style_sheet_that_is_blocking_scripts() && pending_parsing_blocking_script->is_ready_to_be_parser_executed();+ HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *m_document }, pending_parsing_blocking_script->as_element()), [](GC::Ref<DOM::Document>& document, DOM::Element& script) {+ return !document->has_a_style_sheet_that_is_blocking_scripts() && as<HTML::HTMLOrSVGScriptElement>(script).is_ready_to_be_parser_executed();}));}diff --git a/Libraries/LibWebCommon/Clipboard/SystemClipboard.h b/Libraries/LibWebCommon/Clipboard/SystemClipboard.hindex 22a53a14164..c5e3e16cce5 100644--- a/Libraries/LibWebCommon/Clipboard/SystemClipboard.h+++ b/Libraries/LibWebCommon/Clipboard/SystemClipboard.h@@ -10,6 +10,7 @@#include <AK/String.h>#include <AK/Variant.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>#include <LibWebCommon/HTML/SelectedFile.h>@@ -51,3 +52,5 @@ template<>WEBCOMMON_API ErrorOr<Web::Clipboard::SystemClipboardItem> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::Clipboard::SystemClipboardItem);diff --git a/Libraries/LibWebCommon/Gamepad/GamepadSnapshot.h b/Libraries/LibWebCommon/Gamepad/GamepadSnapshot.hindex cabd9b72b55..f3bbafa2c5f 100644--- a/Libraries/LibWebCommon/Gamepad/GamepadSnapshot.h+++ b/Libraries/LibWebCommon/Gamepad/GamepadSnapshot.h@@ -10,6 +10,7 @@#include <AK/String.h>#include <AK/Variant.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>@@ -153,3 +154,6 @@ template<>WEBCOMMON_API ErrorOr<Web::Gamepad::VirtualGamepad> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::Gamepad::GamepadDescription);+GC_UNTRACED_CAPTURE(Web::Gamepad::GamepadState);diff --git a/Libraries/LibWebCommon/HTML/CrossProcessId.h b/Libraries/LibWebCommon/HTML/CrossProcessId.hindex e688110ba22..f1b18e2a291 100644--- a/Libraries/LibWebCommon/HTML/CrossProcessId.h+++ b/Libraries/LibWebCommon/HTML/CrossProcessId.h@@ -11,6 +11,7 @@#include <AK/HashFunctions.h>#include <AK/Traits.h>#include <AK/Types.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>@@ -71,3 +72,5 @@ struct AK::Formatter<Web::HTML::CrossProcessId> : Formatter<FormatString> {return Formatter<FormatString>::format(builder, "{}:{}"sv, id.namespace_id, id.local_id);}};++GC_UNTRACED_CAPTURE(Web::HTML::CrossProcessId);diff --git a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.hindex 94341e434ea..926f5d80807 100644--- a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h+++ b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h@@ -15,6 +15,7 @@#include <AK/Utf16String.h>#include <AK/Variant.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>#include <LibHTTP/Cache/CacheMode.h>#include <LibHTTP/Header.h>#include <LibIPC/Forward.h>@@ -224,3 +225,5 @@ template<>WEBCOMMON_API ErrorOr<Web::HTML::NavigationParamsDescriptor> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::HTML::NavigationParamsDescriptor);diff --git a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.hindex bfea08133cb..6ecba7e7d01 100644--- a/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h+++ b/Libraries/LibWebCommon/HTML/NavigationPopulationRequest.h@@ -9,6 +9,7 @@#include <AK/Optional.h>#include <AK/String.h>#include <AK/Utf16String.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Bindings/Navigation.h>#include <LibWebCommon/ContentSecurityPolicy/Directives/NavigationType.h>@@ -110,3 +111,5 @@ template<>WEBCOMMON_API ErrorOr<Web::HTML::HistoryNavigationPopulation> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::HTML::NavigationPopulationRequest);diff --git a/Libraries/LibWebCommon/HTML/POSTResource.h b/Libraries/LibWebCommon/HTML/POSTResource.hindex 3bcd6efa786..7db96b72a86 100644--- a/Libraries/LibWebCommon/HTML/POSTResource.h+++ b/Libraries/LibWebCommon/HTML/POSTResource.h@@ -11,6 +11,7 @@#include <AK/Utf16String.h>#include <AK/Variant.h>#include <AK/Vector.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>@@ -63,3 +64,5 @@ template<>WEBCOMMON_API ErrorOr<Web::HTML::POSTResource> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::HTML::POSTResource);diff --git a/Libraries/LibWebCommon/HTML/Scripting/EnvironmentId.h b/Libraries/LibWebCommon/HTML/Scripting/EnvironmentId.hindex faf6658bf61..6da12d942e9 100644--- a/Libraries/LibWebCommon/HTML/Scripting/EnvironmentId.h+++ b/Libraries/LibWebCommon/HTML/Scripting/EnvironmentId.h@@ -8,6 +8,7 @@#include <AK/Format.h>#include <AK/String.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>@@ -47,6 +48,8 @@ struct AK::Formatter<Web::HTML::EnvironmentId> : Formatter<StringView> {}};+GC_UNTRACED_CAPTURE(Web::HTML::EnvironmentId);+namespace IPC {template<>diff --git a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.hindex 63f53cfed52..7e1356dc7d1 100644--- a/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h+++ b/Libraries/LibWebCommon/HTML/Scripting/SerializedEnvironmentSettingsObject.h@@ -7,6 +7,7 @@#pragma once#include <AK/Utf16String.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibURL/Origin.h>#include <LibURL/URL.h>@@ -92,3 +93,5 @@ template<>WEBCOMMON_API ErrorOr<Web::HTML::SerializedEnvironmentSettingsObject> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::HTML::SerializedEnvironmentSettingsObject);diff --git a/Libraries/LibWebCommon/HTML/SerializationRecords.h b/Libraries/LibWebCommon/HTML/SerializationRecords.hindex 197e1b1b4bc..7719a0ebe31 100644--- a/Libraries/LibWebCommon/HTML/SerializationRecords.h+++ b/Libraries/LibWebCommon/HTML/SerializationRecords.h@@ -16,6 +16,7 @@#include <AK/RefPtr.h>#include <AK/Vector.h>#include <LibCore/AnonymousBuffer.h>+#include <LibGC/Forward.h>#include <LibIPC/Encoder.h>#include <LibIPC/File.h>#include <LibIPC/Forward.h>@@ -194,3 +195,5 @@ template<>WEBCOMMON_API ErrorOr<Web::HTML::SerializedTransferRecord> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::HTML::TransferDataEncoder);diff --git a/Libraries/LibWebCommon/MimeSniff/MimeType.h b/Libraries/LibWebCommon/MimeSniff/MimeType.hindex aa81dd292c6..5ce9ab705ed 100644--- a/Libraries/LibWebCommon/MimeSniff/MimeType.h+++ b/Libraries/LibWebCommon/MimeSniff/MimeType.h@@ -12,6 +12,7 @@#include <AK/String.h>#include <AK/Utf16String.h>#include <AK/Utf16View.h>+#include <LibGC/Forward.h>#include <LibWebCommon/Export.h>namespace Web::FFI {@@ -82,3 +83,5 @@ private:WEBCOMMON_API String minimise_a_supported_mime_type(MimeType const&);}++GC_UNTRACED_CAPTURE(Web::MimeSniff::MimeType);diff --git a/Libraries/LibWebCommon/StorageAPI/StorageKey.h b/Libraries/LibWebCommon/StorageAPI/StorageKey.hindex 631e91bcdea..cf4a288c0ab 100644--- a/Libraries/LibWebCommon/StorageAPI/StorageKey.h+++ b/Libraries/LibWebCommon/StorageAPI/StorageKey.h@@ -9,6 +9,7 @@#include <AK/Optional.h>#include <AK/String.h>#include <AK/Traits.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibURL/Origin.h>#include <LibWebCommon/Export.h>@@ -65,3 +66,5 @@ template<>WEBCOMMON_API ErrorOr<Web::StorageAPI::StorageKey> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::StorageAPI::StorageKey);diff --git a/Libraries/LibWebCommon/WebDriver/Response.h b/Libraries/LibWebCommon/WebDriver/Response.hindex 01a953eba88..d7c928961c3 100644--- a/Libraries/LibWebCommon/WebDriver/Response.h+++ b/Libraries/LibWebCommon/WebDriver/Response.h@@ -8,6 +8,7 @@#include <AK/JsonValue.h>#include <AK/Variant.h>+#include <LibGC/Forward.h>#include <LibIPC/Forward.h>#include <LibWebCommon/Export.h>#include <LibWebCommon/WebDriver/Error.h>@@ -54,3 +55,5 @@ template<>WEBCOMMON_API ErrorOr<Web::WebDriver::Response> decode(Decoder&);}++GC_UNTRACED_CAPTURE(Web::WebDriver::Response);diff --git a/Meta/ClangPlugins/LibJSGCPluginAction.cpp b/Meta/ClangPlugins/LibJSGCPluginAction.cppindex 08d82608856..b1f79352993 100644--- a/Meta/ClangPlugins/LibJSGCPluginAction.cpp+++ b/Meta/ClangPlugins/LibJSGCPluginAction.cpp@@ -1452,102 +1452,6 @@ bool LibJSGCVisitor::VisitLambdaExpr(clang::LambdaExpr* lambda)return true;}-static bool creates_gc_function(clang::FunctionDecl const& function)-{- if (function.getQualifiedNameAsString() == "GC::create_function")- return true;- auto const* method = llvm::dyn_cast<clang::CXXMethodDecl>(&function);- if (!method || !method->getDeclName().isIdentifier() || method->getName() != "create")- return false;- auto const* specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(method->getParent());- return specialization && specialization->getSpecializedTemplate()->getQualifiedNameAsString() == "GC::Function";-}--static bool is_call_to_move(clang::CallExpr const& call)-{- auto const* callee = call.getDirectCallee();- return callee && call.getNumArgs() == 1 && callee->getDeclName().isIdentifier() && callee->getName() == "move";-}--static clang::LambdaExpr const* lambda_passed_by(clang::Expr const* argument)-{- while (argument) {- argument = clang::IgnoreExprNodes(argument, clang::IgnoreImplicitSingleStep, clang::IgnoreParensSingleStep);- if (auto const* lambda = llvm::dyn_cast<clang::LambdaExpr>(argument))- return lambda;- if (auto const* cast = llvm::dyn_cast<clang::CXXFunctionalCastExpr>(argument)) {- argument = cast->getSubExpr();- } else if (auto const* construct = llvm::dyn_cast<clang::CXXConstructExpr>(argument); construct && construct->getNumArgs() == 1) {- argument = construct->getArg(0);- } else if (auto const* call = llvm::dyn_cast<clang::CallExpr>(argument); call && is_call_to_move(*call)) {- argument = call->getArg(0);- } else if (auto const* reference = llvm::dyn_cast<clang::DeclRefExpr>(argument)) {- auto const* variable = llvm::dyn_cast<clang::VarDecl>(reference->getDecl());- if (!variable || !variable->hasLocalStorage() || llvm::isa<clang::ParmVarDecl>(variable))- return nullptr;- argument = variable->getInit();- } else {- return nullptr;- }- }- return nullptr;-}--bool LibJSGCVisitor::VisitCallExpr(clang::CallExpr* call)-{- auto const* callee = call->getDirectCallee();- if (!callee || !creates_gc_function(*callee))- return true;- for (auto const* argument : call->arguments()) {- if (auto const* lambda = lambda_passed_by(argument))- m_lambdas_in_gc_functions.push_back(lambda);- }- return true;-}--void LibJSGCVisitor::validate_gc_function_captures()-{- auto& diag_engine = m_context.getDiagnostics();- auto diag_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Error, "Captured %0 keeps GC pointers in heap memory that GC::Function does not scan; hold them in a GC::Root, a GC::RootVector or a GC::Conservative container instead");- auto note_id = diag_engine.getCustomDiagID(clang::DiagnosticsEngine::Note, "Member %0 contains GC pointers");-- for (auto const* lambda : m_lambdas_in_gc_functions) {- for (auto const& capture : lambda->captures()) {- if (!capture.capturesVariable() || capture.getCaptureKind() != clang::LCK_ByCopy)- continue;- auto const* variable = capture.getCapturedVar();- auto type = variable->getType().getNonReferenceType().getUnqualifiedType();- // An init-capture of move(x) has the type typename std::remove_reference<T&>::type.- while (!llvm::isa<clang::TemplateSpecializationType>(type.getTypePtr())) {- auto desugared_type = type.getSingleStepDesugaredType(m_context);- if (desugared_type == type)- break;- type = desugared_type;- }-- // An init-capture is a variable of its own, whose containers the check of objects on the stack reports.- if (auto const* init_capture = llvm::dyn_cast<clang::VarDecl>(variable); init_capture && init_capture->isInitCapture()) {- std::set<clang::CXXRecordDecl const*> visited_on_stack;- if (find_container_with_unscanned_gc_pointers(type, visited_on_stack))- continue;- }-- std::set<clang::CXXRecordDecl const*> visited;- auto storage = find_container_with_unscanned_gc_pointers(type, visited, &m_polymorphic_subclasses);- if (!storage)- continue;- diag_engine.Report(capture.getLocation(), diag_id) << *storage;-- auto instance = template_instance_of_type(*storage);- if (!instance || !is_owning_pointer(instance->name) || instance->type_arguments.empty())- continue;- std::set<clang::CXXRecordDecl const*> visited_by_object;- if (auto const* member = find_owned_member_with_gc_pointers(instance->type_arguments[0], visited_by_object, m_polymorphic_subclasses))- diag_engine.Report(member->getLocation(), note_id) << member->getName();- }- }-}-LibJSGCASTConsumer::LibJSGCASTConsumer(clang::CompilerInstance& compiler, bool detect_invalid_function_members): m_compiler(compiler), m_detect_invalid_function_members(detect_invalid_function_members)@@ -1560,7 +1464,6 @@ void LibJSGCASTConsumer::HandleTranslationUnit(clang::ASTContext& context){LibJSGCVisitor visitor { context, m_macro_map, m_detect_invalid_function_members };visitor.TraverseDecl(context.getTranslationUnitDecl());- visitor.validate_gc_function_captures();}char const* LibJSCellMacro::type_name(Type type)diff --git a/Meta/ClangPlugins/LibJSGCPluginAction.h b/Meta/ClangPlugins/LibJSGCPluginAction.hindex e3b9db7fe85..ea8fbebc12c 100644--- a/Meta/ClangPlugins/LibJSGCPluginAction.h+++ b/Meta/ClangPlugins/LibJSGCPluginAction.h@@ -70,9 +70,6 @@ public:bool VisitCXXForRangeStmt(clang::CXXForRangeStmt*);bool VisitFunctionDecl(clang::FunctionDecl*);bool VisitLambdaExpr(clang::LambdaExpr*);- bool VisitCallExpr(clang::CallExpr*);-- void validate_gc_function_captures();private:struct CellMacroExpectation {@@ -92,7 +89,6 @@ private:LibJSCellMacroMap const& m_macro_map;bool m_detect_invalid_function_members;PolymorphicSubclasses m_polymorphic_subclasses;- std::vector<clang::LambdaExpr const*> m_lambdas_in_gc_functions;};class LibJSGCASTConsumer : public clang::ASTConsumer {diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex d569416a75a..cf8d4d9b9c7 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -612,8 +612,10 @@ void ConnectionFromClient::run_beforeunload_check(Web::PageId page_id, Web::HTMLreturn;}- page->page().history_executor().run_ui_beforeunload_check(move(navigable_ids), move(target_entry), user_involvement_for_navigate_event, unload_prompt_shown, GC::create_function(Web::HTML::main_thread_event_loop().heap(), [this, page_id, check_id](Web::HTML::CheckIfUnloadingIsCanceledResult result, Web::HTML::UnloadPromptShown unload_prompt_shown) {- async_beforeunload_check_result(page_id, check_id, result, unload_prompt_shown);+ page->page().history_executor().run_ui_beforeunload_check(move(navigable_ids), move(target_entry), user_involvement_for_navigate_event, unload_prompt_shown, GC::create_function(Web::HTML::main_thread_event_loop().heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, check_id), [](auto& connection, auto& page_id, auto& check_id, Web::HTML::CheckIfUnloadingIsCanceledResult result, Web::HTML::UnloadPromptShown unload_prompt_shown) {+ if (!connection)+ return;+ connection->async_beforeunload_check_result(page_id, check_id, result, unload_prompt_shown);}));}@@ -675,8 +677,10 @@ void ConnectionFromClient::populate_history_entry_document(Web::PageId page_id,return;}page->page().history_executor().populate_ui_history_entry_document(operation_id, move(target_entry), navigation_type, ongoing_navigation_is_traversal, move(population),- GC::create_function(Web::HTML::main_thread_event_loop().heap(), [this, page_id, operation_id, navigable_id](Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition, bool update_only) {- async_changing_navigable_history_job_ready(page_id, operation_id, navigable_id, disposition, update_only);+ GC::create_function(Web::HTML::main_thread_event_loop().heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, operation_id, navigable_id), [](auto& connection, auto& page_id, auto& operation_id, auto& navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition, bool update_only) {+ if (!connection)+ return;+ connection->async_changing_navigable_history_job_ready(page_id, operation_id, navigable_id, disposition, update_only);}));}@@ -688,8 +692,10 @@ void ConnectionFromClient::run_changing_navigable_history_job(Web::PageId page_ireturn;}- page->page().history_executor().run_ui_changing_navigable_history_job(operation_id, navigable_id, move(target_entry), user_involvement, navigation_type, move(finalized_navigation_id), ongoing_navigation_is_traversal, needs_population, GC::create_function(Web::HTML::main_thread_event_loop().heap(), [this, page_id, operation_id, navigable_id](Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition, bool update_only) {- async_changing_navigable_history_job_ready(page_id, operation_id, navigable_id, disposition, update_only);+ page->page().history_executor().run_ui_changing_navigable_history_job(operation_id, navigable_id, move(target_entry), user_involvement, navigation_type, move(finalized_navigation_id), ongoing_navigation_is_traversal, needs_population, GC::create_function(Web::HTML::main_thread_event_loop().heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, operation_id, navigable_id), [](auto& connection, auto& page_id, auto& operation_id, auto& navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition, bool update_only) {+ if (!connection)+ return;+ connection->async_changing_navigable_history_job_ready(page_id, operation_id, navigable_id, disposition, update_only);}));}@@ -715,8 +721,10 @@ void ConnectionFromClient::apply_changing_navigable_continuation(Web::PageId pagreturn;}- page->page().history_executor().apply_ui_changing_navigable_continuation(operation_id, navigable_id, target_entry, { script_history_length, script_history_index }, move(entries_for_navigation_api), clear_classic_history_api_state, clear_navigable_target_name, GC::create_function(Web::HTML::main_thread_event_loop().heap(), [this, page_id, operation_id, navigable_id](Optional<Web::HTML::HostedNavigableState> activated_navigable_state, Optional<Web::HTML::SessionHistoryEntryPersistedState> previous_entry_persisted_state) {- async_changing_navigable_continuation_applied(page_id, operation_id, navigable_id, move(activated_navigable_state), move(previous_entry_persisted_state));+ page->page().history_executor().apply_ui_changing_navigable_continuation(operation_id, navigable_id, target_entry, { script_history_length, script_history_index }, move(entries_for_navigation_api), clear_classic_history_api_state, clear_navigable_target_name, GC::create_function(Web::HTML::main_thread_event_loop().heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, operation_id, navigable_id), [](auto& connection, auto& page_id, auto& operation_id, auto& navigable_id, Optional<Web::HTML::HostedNavigableState> activated_navigable_state, Optional<Web::HTML::SessionHistoryEntryPersistedState> previous_entry_persisted_state) {+ if (!connection)+ return;+ connection->async_changing_navigable_continuation_applied(page_id, operation_id, navigable_id, move(activated_navigable_state), move(previous_entry_persisted_state));}));}@@ -728,8 +736,10 @@ void ConnectionFromClient::unload_displayed_document_and_apply_changing_navigablreturn;}- page->page().history_executor().unload_displayed_document_and_apply_ui_changing_navigable_continuation(operation_id, navigable_id, target_entry, { script_history_length, script_history_index }, move(entries_for_navigation_api), clear_classic_history_api_state, clear_navigable_target_name, GC::create_function(Web::HTML::main_thread_event_loop().heap(), [this, page_id, operation_id, navigable_id](Optional<Web::HTML::HostedNavigableState> activated_navigable_state, Optional<Web::HTML::SessionHistoryEntryPersistedState> previous_entry_persisted_state) {- async_changing_navigable_continuation_applied(page_id, operation_id, navigable_id, move(activated_navigable_state), move(previous_entry_persisted_state));+ page->page().history_executor().unload_displayed_document_and_apply_ui_changing_navigable_continuation(operation_id, navigable_id, target_entry, { script_history_length, script_history_index }, move(entries_for_navigation_api), clear_classic_history_api_state, clear_navigable_target_name, GC::create_function(Web::HTML::main_thread_event_loop().heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, operation_id, navigable_id), [](auto& connection, auto& page_id, auto& operation_id, auto& navigable_id, Optional<Web::HTML::HostedNavigableState> activated_navigable_state, Optional<Web::HTML::SessionHistoryEntryPersistedState> previous_entry_persisted_state) {+ if (!connection)+ return;+ connection->async_changing_navigable_continuation_applied(page_id, operation_id, navigable_id, move(activated_navigable_state), move(previous_entry_persisted_state));}));}@@ -743,8 +753,10 @@ void ConnectionFromClient::run_descendant_unload_task(Web::PageId page_id, Web::}VERIFY(&navigable->page() == &page->page());- navigable->run_ui_descendant_unload_task(child_navigable_destruction, stop_hosting_after_unload, GC::create_function(navigable->heap(), [this, page_id, unload_id, navigable_id] {- async_descendant_unload_task_complete(page_id, unload_id, navigable_id);+ navigable->run_ui_descendant_unload_task(child_navigable_destruction, stop_hosting_after_unload, GC::create_function(navigable->heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, unload_id, navigable_id), [](auto& connection, auto& page_id, auto& unload_id, auto& navigable_id) {+ if (!connection)+ return;+ connection->async_descendant_unload_task_complete(page_id, unload_id, navigable_id);}));}@@ -774,7 +786,7 @@ void ConnectionFromClient::abort_navigable_document(Web::PageId page_id, Web::HTreturn;// 3. For each descendantNavigable of descendantNavigables, queue a global task on the navigation and traversal task source given descendantNavigable's active window to perform the following steps:- Web::HTML::queue_global_task(Web::HTML::Task::Source::NavigationAndTraversal, Web::HTML::relevant_global_object(*navigable->active_window()), GC::create_function(GC::Heap::the(), [navigable = GC::Ref { *navigable }] {+ Web::HTML::queue_global_task(Web::HTML::Task::Source::NavigationAndTraversal, Web::HTML::relevant_global_object(*navigable->active_window()), GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *navigable }), [](auto& navigable) {auto document = navigable->active_document();if (!document)return;@@ -881,8 +893,10 @@ void ConnectionFromClient::update_nonchanging_navigable_history_state(Web::PageIreturn;}- navigable->update_nonchanging_navigable_history_step_state({ script_history_length, script_history_index }, GC::create_function(navigable->heap(), [this, page_id, operation_id, navigable_id] {- async_nonchanging_navigable_history_state_updated(page_id, operation_id, navigable_id);+ navigable->update_nonchanging_navigable_history_step_state({ script_history_length, script_history_index }, GC::create_function(navigable->heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, operation_id, navigable_id), [](auto& connection, auto& page_id, auto& operation_id, auto& navigable_id) {+ if (!connection)+ return;+ connection->async_nonchanging_navigable_history_state_updated(page_id, operation_id, navigable_id);}));}@@ -3527,7 +3541,7 @@ void ConnectionFromClient::update_visibility_state(Web::PageId page_id, Web::HTM// 2. Queue a global task on the user interaction task source given document's relevant global object// to update the visibility state of document with newState.- Web::HTML::queue_global_task(Web::HTML::Task::Source::UserInteraction, Web::HTML::relevant_global_object(*document), GC::create_function(GC::Heap::the(), [visibility_state, document] {+ Web::HTML::queue_global_task(Web::HTML::Task::Source::UserInteraction, Web::HTML::relevant_global_object(*document), GC::create_function(GC::Heap::the(), GC::captures(visibility_state, document), [](auto& visibility_state, auto& document) {document->update_the_visibility_state(visibility_state);}));}@@ -3892,8 +3906,10 @@ void ConnectionFromClient::request_close_preflight(Web::PageId page_id, u64 requreturn;}- traversable->request_close_preflight(GC::create_function(Web::Bindings::main_thread_vm().heap(), [this, page_id, request_id](bool approved) {- async_did_complete_close_preflight(page_id, request_id, approved);+ traversable->request_close_preflight(GC::create_function(Web::Bindings::main_thread_vm().heap(), GC::captures(make_weak_ptr<ConnectionFromClient>(), page_id, request_id), [](auto& connection, auto& page_id, auto& request_id, bool approved) {+ if (!connection)+ return;+ connection->async_did_complete_close_preflight(page_id, request_id, approved);}));}diff --git a/Services/WebContent/DevToolsDebugger.cpp b/Services/WebContent/DevToolsDebugger.cppindex bc9daaadb68..d2cc88dd405 100644--- a/Services/WebContent/DevToolsDebugger.cpp+++ b/Services/WebContent/DevToolsDebugger.cpp@@ -46,9 +46,11 @@ void DevToolsDebugger::attach(PageClient& page)auto& vm = Web::Bindings::main_thread_vm();vm.enable_debugging();if (!m_pause_callback_is_installed) {- vm.debugger()->set_pause_callback([this](auto const& pause) {- handle_pause(pause);- });+ vm.debugger()->set_pause_callback(GC::create_function(vm.heap(), GC::captures(make_weak_ptr<DevToolsDebugger>()), [](auto& debugger, JS::Debugger::PauseInfo const& pause) {+ if (!debugger)+ return;+ debugger->handle_pause(pause);+ }));m_pause_callback_is_installed = true;}update_exception_pause_mode();diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex a7bcc451a41..f6fc679b12b 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -409,14 +409,14 @@ void PageClient::run_navigation_unload_check(Web::HTML::CrossProcessId navigablereturn;}- navigable->run_navigation_unload_check(navigation_id, unload_prompt_shown, GC::create_function(navigable->heap(), [this, navigable = GC::Ref { *navigable }, navigable_id, navigation_id](bool should_continue) {+ navigable->run_navigation_unload_check(navigation_id, unload_prompt_shown, GC::create_function(navigable->heap(), GC::captures(*this, GC::Ref { *navigable }, navigable_id, navigation_id), [](auto& self, auto& navigable, auto& navigable_id, auto& navigation_id, bool should_continue) {// The UI process retained the pending entry at admission; a passed check only needs the signal.if (!should_continue) {navigable->resume_navigation_params_creation(navigation_id, {});- client().async_did_fail_navigation_population(m_id, navigable_id, navigation_id);+ self.client().async_did_fail_navigation_population(self.m_id, navigable_id, navigation_id);return;}- client().async_did_complete_navigation_unload_check(m_id, navigable_id, navigation_id);+ self.client().async_did_complete_navigation_unload_check(self.m_id, navigable_id, navigation_id);}));}@@ -803,7 +803,7 @@ void PageClient::frame_timer_fired()// Defer the fallback once so an arrived reply is handled first, while a genuinely lost reply still falls back// on the next event-loop dispatch.auto watchdog_deadline = m_compositor_watchdog_deadline;- Web::Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [page_client = GC::Ref { *this }, watchdog_deadline] {+ Web::Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *this }, watchdog_deadline), [](auto& page_client, auto& watchdog_deadline) {if (!page_client->m_compositor_rendering_opportunity_outstanding)return;if (page_client->m_compositor_watchdog_deadline != watchdog_deadline)@@ -1224,8 +1224,8 @@ void PageClient::page_did_set_browser_zoom(double factor)m_pending_browser_zoom = WebView::clamp_zoom_level(factor);client().async_did_set_browser_zoom(m_id, factor);auto& event_loop = Web::HTML::main_thread_event_loop();- event_loop.spin_until(GC::create_function(GC::Heap::the(), [this]() {- return !m_pending_browser_zoom.has_value() || !is_connection_open();+ event_loop.spin_until(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ return !self.m_pending_browser_zoom.has_value() || !self.is_connection_open();}));}@@ -1239,8 +1239,8 @@ void PageClient::page_did_set_device_pixel_ratio_for_testing(double ratio)return;m_pending_device_pixel_ratio_for_testing = ratio;client().async_did_set_device_pixel_ratio_for_testing(m_id, ratio);- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), [this]() {- return !m_pending_device_pixel_ratio_for_testing.has_value() || !is_connection_open();+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ return !self.m_pending_device_pixel_ratio_for_testing.has_value() || !self.is_connection_open();}));}@@ -2042,11 +2042,11 @@ String PageClient::page_did_request_session_store_tab_state_for_testing()void PageClient::run_webdriver_user_prompt_handling(u64 request_id){Web::WebDriver::handle_any_user_prompts(page(),- GC::create_function(heap(), [this, request_id](Optional<Web::WebDriver::Error> error) {+ GC::create_function(heap(), GC::captures(*this, request_id), [](auto& self, auto& request_id, Optional<Web::WebDriver::Error> error) {auto response = error.has_value()? Web::WebDriver::Response { error.release_value() }: Web::WebDriver::Response { JsonValue {} };- client().async_webdriver_user_prompt_handling_complete(m_id, request_id, move(response));+ self.client().async_webdriver_user_prompt_handling_complete(self.m_id, request_id, move(response));}));}diff --git a/Services/WebContent/WebDriverConnection.cpp b/Services/WebContent/WebDriverConnection.cppindex c0c7fb9dc33..bb757000a6e 100644--- a/Services/WebContent/WebDriverConnection.cpp+++ b/Services/WebContent/WebDriverConnection.cpp@@ -86,6 +86,7 @@namespace WebContent {+// NB: This is used in the callbacks of commands, which take the connection they run for as `connection`.#define WEBDRIVER_TRY(expression) \({ \/* Ignore -Wshadow to allow nesting the macro. */ \@@ -94,7 +95,7 @@ namespace WebContent {static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \"Do not return a reference from a fallible expression"); \if (_temporary_result.is_error()) [[unlikely]] { \- driver_execution_complete({ _temporary_result.release_error() }); \+ connection->driver_execution_complete({ _temporary_result.release_error() }); \return; \} \_temporary_result.release_value(); \@@ -227,9 +228,11 @@ NonnullRefPtr<WebDriverConnection> WebDriverConnection::create(PageClient& page_WebDriverConnection::WebDriverConnection(PageClient& page_client): m_page_client(page_client){- page_client.page().set_window_rect_observer(GC::create_function(GC::Heap::the(), [this](Web::DevicePixelRect rect, u64 request_id) {- if (m_pending_window_rect_requests.remove(request_id) && m_pending_window_rect_requests.is_empty())- driver_execution_complete(serialize_rect(rect.to_type<int>()));+ page_client.page().set_window_rect_observer(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection, Web::DevicePixelRect rect, u64 request_id) {+ if (!connection)+ return;+ if (connection->m_pending_window_rect_requests.remove(request_id) && connection->m_pending_window_rect_requests.is_empty())+ connection->driver_execution_complete(serialize_rect(rect.to_type<int>()));}));page_client.page().set_is_webdriver_active(true);}@@ -434,13 +437,15 @@ Web::WebDriver::Response WebDriverConnection::get_current_url()TRY(ensure_current_top_level_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Let url be the serialization of the current top-level browsing context’s active document’s document URL.- auto url = current_top_level_browsing_context()->active_document()->url();+ auto url = connection->current_top_level_browsing_context()->active_document()->url();// 4. Return success with data url.- driver_execution_complete({ url.to_string() });- });+ connection->driver_execution_complete({ url.to_string() });+ }));return JsonValue {};}@@ -459,13 +464,15 @@ Web::WebDriver::Response WebDriverConnection::get_title()TRY(ensure_current_top_level_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Let title be the initial value of the title IDL attribute of the current top-level browsing context's active document.- auto title = current_top_level_browsing_context()->active_document()->title().to_utf8();+ auto title = connection->current_top_level_browsing_context()->active_document()->title().to_utf8();// 4. Return success with data title.- driver_execution_complete({ move(title) });- });+ connection->driver_execution_complete({ move(title) });+ }));return JsonValue {};}@@ -477,22 +484,26 @@ Web::WebDriver::Response WebDriverConnection::close_window()TRY(ensure_current_top_level_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Close the current top-level browsing context.// FIXME: Spec issue: Closing browsing contexts is no longer a spec concept, we must instead close the top-level// traversable. We must also do so asynchronously, as the implementation will spin the event loop in some// steps. If a user dialog is open in another window within this agent, the event loop will be paused, and// those spins will hang. So we must return control to the client, who can deal with the dialog.- Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(current_top_level_browsing_context()->heap(), [this]() {+ Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(connection->current_top_level_browsing_context()->heap(), GC::captures(connection), [](auto& connection) {+ if (!connection)+ return;// The page can close this window on its own before this task runs, and a closed// context has no document or navigable left to reach its traversable through.- if (ensure_current_top_level_browsing_context_is_open().is_error())+ if (connection->ensure_current_top_level_browsing_context_is_open().is_error())return;- as<Web::HTML::LocalTraversableNavigable>(*m_page_client->page().top_level_traversable()).close_top_level_traversable(Web::HTML::LocalTraversableNavigable::PromptToUnload::No);+ as<Web::HTML::LocalTraversableNavigable>(*connection->m_page_client->page().top_level_traversable()).close_top_level_traversable(Web::HTML::LocalTraversableNavigable::PromptToUnload::No);}));- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));return JsonValue {};}@@ -506,17 +517,19 @@ Web::WebDriver::Response WebDriverConnection::new_window(JsonValue payload)TRY(ensure_current_top_level_browsing_context_is_open());// 3. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, payload = move(payload)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(payload)), [](auto& connection, auto& payload) {+ if (!connection)+ return;// 4. Let type hint be the result of getting the property "type" from the parameters argument.if (!payload.is_object()) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object"sv));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object"sv));return;}// FIXME: Actually use this value to decide between an OS window or tab.auto type_hint = payload.as_object().get("type"sv);if (type_hint.has_value() && !type_hint->is_null() && !type_hint->is_string()) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload property `type` is not null or a string"sv));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload property `type` is not null or a string"sv));return;}@@ -528,7 +541,7 @@ Web::WebDriver::Response WebDriverConnection::new_window(JsonValue payload)// is "window", and the implementation supports multiple browsing contexts in separate OS windows, the// created browsing context should be in a new OS window. In all other cases the details of how the browsing// context is presented to the user are implementation defined.- auto* active_window = current_browsing_context().active_window();+ auto* active_window = connection->current_browsing_context().active_window();VERIFY(active_window);Web::HTML::TemporaryExecutionContext execution_context { active_window->document()->relevant_settings_object() };@@ -546,8 +559,8 @@ Web::WebDriver::Response WebDriverConnection::new_window(JsonValue payload)result.set("type"sv, JsonValue { type });// 9. Return success with data result.- driver_execution_complete({ move(result) });- });+ connection->driver_execution_complete({ move(result) });+ }));return JsonValue {};}@@ -573,12 +586,14 @@ Web::WebDriver::Response WebDriverConnection::switch_to_frame(JsonValue payload)TRY(ensure_current_top_level_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Set the current browsing context with session and session's current top-level browsing context.- set_current_browsing_context(m_page_client->page().top_level_traversable());+ connection->set_current_browsing_context(connection->m_page_client->page().top_level_traversable());- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));}// -> id is a Number object@@ -593,17 +608,19 @@ Web::WebDriver::Response WebDriverConnection::switch_to_frame(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 3. Try to handle any user prompts with session.- handle_any_user_prompts([this, id = *id_value]() {- Web::HTML::TemporaryExecutionContext execution_context { current_browsing_context().active_document()->relevant_settings_object() };+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), *id_value), [](auto& connection, auto& id) {+ if (!connection)+ return;+ Web::HTML::TemporaryExecutionContext execution_context { connection->current_browsing_context().active_document()->relevant_settings_object() };// 4. Let window be the associated window of session's current browsing context's active document.- auto window = current_browsing_context().active_document()->window()->window();+ auto window = connection->current_browsing_context().active_document()->window()->window();// 5. If id is not a supported property index of window, return error with error code no such frame.auto property = window->object().get(id);if (property.is_error() || !property.value().is_object() || !Web::HTML::WindowProxy::from_object(property.value().as_object())) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, MUST(String::formatted("Frame ID {} not found", id))));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, MUST(String::formatted("Frame ID {} not found", id))));return;}@@ -613,13 +630,13 @@ Web::WebDriver::Response WebDriverConnection::switch_to_frame(JsonValue payload)// 7. Set the current browsing context with session and child window's browsing context.auto child_navigable = child_window.navigable();if (!child_navigable) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, MUST(String::formatted("Frame ID {} not found", id))));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, MUST(String::formatted("Frame ID {} not found", id))));return;}- set_current_browsing_context(*child_navigable);+ connection->set_current_browsing_context(*child_navigable);- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));}// -> id represents a web element@@ -630,13 +647,15 @@ Web::WebDriver::Response WebDriverConnection::switch_to_frame(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known element with session and id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. If element is not a frame or iframe element, return error with error code no such frame.if (!is<Web::HTML::HTMLFrameElement>(*element) && !is<Web::HTML::HTMLIFrameElement>(*element)) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "element is not a frame"sv));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "element is not a frame"sv));return;}@@ -644,13 +663,13 @@ Web::WebDriver::Response WebDriverConnection::switch_to_frame(JsonValue payload)auto& navigable_container = static_cast<Web::HTML::NavigableContainer&>(*element);auto content_navigable = navigable_container.content_navigable();if (!content_navigable) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "element has no content navigable"sv));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "element has no content navigable"sv));return;}- set_current_browsing_context(*content_navigable);+ connection->set_current_browsing_context(*content_navigable);- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));}// FIXME: 4. Update any implementation-specific state that would result from the user selecting session's current browsing context for interaction, without altering OS-level focus.@@ -666,11 +685,13 @@ Web::WebDriver::Response WebDriverConnection::get_window_rect()TRY(ensure_current_top_level_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Return success with data set to the WindowRect object for the current top-level browsing context.- auto serialized_rect = serialize_rect(compute_window_rect(current_top_level_browsing_context()->page()));- driver_execution_complete(move(serialized_rect));- });+ auto serialized_rect = serialize_rect(compute_window_rect(connection->current_top_level_browsing_context()->page()));+ connection->driver_execution_complete(move(serialized_rect));+ }));return JsonValue {};}@@ -724,33 +745,37 @@ Web::WebDriver::Response WebDriverConnection::set_window_rect(JsonValue payload)TRY(ensure_current_top_level_browsing_context_is_open());// 9. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, x, y, width, height]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), x, y, width, height), [](auto& connection, auto& x, auto& y, auto& width, auto& height) {+ if (!connection)+ return;// 10. Fully exit fullscreen.- current_top_level_browsing_context()->active_document()->fully_exit_fullscreen();+ connection->current_top_level_browsing_context()->active_document()->fully_exit_fullscreen();// 11. Restore the window.- restore_the_window(GC::create_function(current_top_level_browsing_context()->heap(), [this, x, y, width, height]() {- auto& page = current_top_level_browsing_context()->page();+ connection->restore_the_window(GC::create_function(connection->current_top_level_browsing_context()->heap(), GC::captures(connection, x, y, width, height), [](auto& connection, auto& x, auto& y, auto& width, auto& height) {+ if (!connection)+ return;+ auto& page = connection->current_top_level_browsing_context()->page();// 11. If width and height are not null:if (width.has_value() && height.has_value()) {// a. Set the width, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to width.// b. Set the height, in CSS pixels, of the operating system window containing the current top-level browsing context, including any browser chrome and externally drawn window decorations to a value that is as close as possible to height.- auto request_id = register_window_rect_request();+ auto request_id = connection->register_window_rect_request();page.client().page_did_request_resize_window({ *width, *height }, request_id);}// 12. If x and y are not null:if (x.has_value() && y.has_value()) {// a. Run the implementation-specific steps to set the position of the operating system level window containing the current top-level browsing context to the position given by the x and y coordinates.- auto request_id = register_window_rect_request();+ auto request_id = connection->register_window_rect_request();page.client().page_did_request_reposition_window({ *x, *y }, request_id);}- if (m_pending_window_rect_requests.is_empty())- driver_execution_complete(serialize_rect(compute_window_rect(page)));+ if (connection->m_pending_window_rect_requests.is_empty())+ connection->driver_execution_complete(serialize_rect(compute_window_rect(page)));}));- });+ }));// 14. Return success with data set to the WindowRect object for the current top-level browsing context.return JsonValue {};@@ -765,16 +790,20 @@ Web::WebDriver::Response WebDriverConnection::maximize_window()TRY(ensure_current_top_level_browsing_context_is_open());// 3. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 4. Fully exit fullscreen.- current_top_level_browsing_context()->active_document()->fully_exit_fullscreen();+ connection->current_top_level_browsing_context()->active_document()->fully_exit_fullscreen();// 5. Restore the window.- restore_the_window(GC::create_function(current_top_level_browsing_context()->heap(), [this]() {+ connection->restore_the_window(GC::create_function(connection->current_top_level_browsing_context()->heap(), GC::captures(connection), [](auto& connection) {+ if (!connection)+ return;// 6. Maximize the window of the current top-level browsing context.- maximize_the_window();+ connection->maximize_the_window();}));- });+ }));// 7. Return success with data set to the WindowRect object for the current top-level browsing context.return JsonValue {};@@ -789,16 +818,20 @@ Web::WebDriver::Response WebDriverConnection::minimize_window()TRY(ensure_current_top_level_browsing_context_is_open());// 3. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 4. Fully exit fullscreen.- current_top_level_browsing_context()->active_document()->fully_exit_fullscreen();+ connection->current_top_level_browsing_context()->active_document()->fully_exit_fullscreen();// 5. Iconify the window.- iconify_the_window(GC::create_function(current_top_level_browsing_context()->heap(), [this]() {- auto& page = current_top_level_browsing_context()->page();- driver_execution_complete(serialize_rect(compute_window_rect(page)));+ connection->iconify_the_window(GC::create_function(connection->current_top_level_browsing_context()->heap(), GC::captures(connection), [](auto& connection) {+ if (!connection)+ return;+ auto& page = connection->current_top_level_browsing_context()->page();+ connection->driver_execution_complete(serialize_rect(compute_window_rect(page)));}));- });+ }));// 6. Return success with data set to the WindowRect object for the current top-level browsing context.return JsonValue {};@@ -813,10 +846,14 @@ Web::WebDriver::Response WebDriverConnection::fullscreen_window()TRY(ensure_current_top_level_browsing_context_is_open());// 3. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 4. Restore the window.- restore_the_window(GC::create_function(current_top_level_browsing_context()->heap(), [this]() {- auto* document = current_top_level_browsing_context()->active_document();+ connection->restore_the_window(GC::create_function(connection->current_top_level_browsing_context()->heap(), GC::captures(connection), [](auto& connection) {+ if (!connection)+ return;+ auto* document = connection->current_top_level_browsing_context()->active_document();Web::HTML::TemporaryExecutionContext execution_context { document->relevant_settings_object(), Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };@@ -828,19 +865,23 @@ Web::WebDriver::Response WebDriverConnection::fullscreen_window()auto promise = Web::WebIDL::create_promise(realm);document->document_element()->request_fullscreen(promise, Web::DOM::Element::FullscreenRequester::WebDriver);- Web::WebIDL::upon_fulfillment(promise, GC::create_function(GC::Heap::the(), [this, document](JS::Value) -> Web::WebIDL::ExceptionOr<JS::Value> {- driver_execution_complete(serialize_rect(compute_window_rect(document->page())));+ Web::WebIDL::upon_fulfillment(promise, GC::create_function(GC::Heap::the(), GC::captures(connection, document), [](auto& connection, auto& document, JS::Value) -> Web::WebIDL::ExceptionOr<JS::Value> {+ if (!connection)+ return JS::js_undefined();+ connection->driver_execution_complete(serialize_rect(compute_window_rect(document->page())));return JS::js_undefined();}));- Web::WebIDL::upon_rejection(promise, GC::create_function(GC::Heap::the(), [this, document](JS::Value) -> Web::WebIDL::ExceptionOr<JS::Value> {- driver_execution_complete(serialize_rect(compute_window_rect(document->page())));+ Web::WebIDL::upon_rejection(promise, GC::create_function(GC::Heap::the(), GC::captures(connection, document), [](auto& connection, auto& document, JS::Value) -> Web::WebIDL::ExceptionOr<JS::Value> {+ if (!connection)+ return JS::js_undefined();+ connection->driver_execution_complete(serialize_rect(compute_window_rect(document->page())));return JS::js_undefined();}));}));- });+ }));// 6. Return success with data set to the WindowRect object for the current top-level browsing context.return JsonValue {};@@ -898,10 +939,14 @@ Web::WebDriver::Response WebDriverConnection::find_element(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 6. Try to handle any user prompts with session.- handle_any_user_prompts([this, location_strategy, selector = move(selector)]() mutable {- auto get_start_node = GC::create_function(GC::Heap::the(), [this]() -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), location_strategy, move(selector)), [](auto& connection, auto& location_strategy, auto& selector) {+ if (!connection)+ return;+ auto get_start_node = GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection) -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ if (!connection)+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "The WebDriver connection is gone"sv);// 7. Let start node be session's current browsing context's document element.- auto* start_node = current_browsing_context().active_document();+ auto* start_node = connection->current_browsing_context().active_document();// 8. If start node is null, return error with error code no such element.if (!start_node)@@ -911,11 +956,13 @@ Web::WebDriver::Response WebDriverConnection::find_element(JsonValue payload)});// 9. Let result be the result of trying to Find with session, start node, location strategy, and selector.- find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {+ connection->find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;// 10. If result is empty, return error with error code no such element. Otherwise, return the first element of result.- driver_execution_complete(extract_first_element(move(result)));+ connection->driver_execution_complete(extract_first_element(move(result)));}));- });+ }));return JsonValue {};}@@ -940,10 +987,14 @@ Web::WebDriver::Response WebDriverConnection::find_elements(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 6. Try to handle any user prompts with session.- handle_any_user_prompts([this, location_strategy, selector = move(selector)]() mutable {- auto get_start_node = GC::create_function(GC::Heap::the(), [this]() -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), location_strategy, move(selector)), [](auto& connection, auto& location_strategy, auto& selector) {+ if (!connection)+ return;+ auto get_start_node = GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection) -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ if (!connection)+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "The WebDriver connection is gone"sv);// 7. Let start node be session's current browsing context's document element.- auto* start_node = current_browsing_context().active_document();+ auto* start_node = connection->current_browsing_context().active_document();// 8. If start node is null, return error with error code no such element.if (!start_node)@@ -953,10 +1004,12 @@ Web::WebDriver::Response WebDriverConnection::find_elements(JsonValue payload)});// 9. Return the result of trying to Find with session, start node, location strategy, and selector.- find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {- driver_execution_complete(move(result));+ connection->find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;+ connection->driver_execution_complete(move(result));}));- });+ }));return JsonValue {};}@@ -980,18 +1033,24 @@ Web::WebDriver::Response WebDriverConnection::find_element_from_element(JsonValuTRY(ensure_current_browsing_context_is_open());// 6. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id, location_strategy, selector = move(selector)]() mutable {- auto get_start_node = GC::create_function(GC::Heap::the(), [this, element_id]() -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), element_id, location_strategy, move(selector)), [](auto& connection, auto& element_id, auto& location_strategy, auto& selector) {+ if (!connection)+ return;+ auto get_start_node = GC::create_function(GC::Heap::the(), GC::captures(connection, element_id), [](auto& connection, auto& element_id) -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ if (!connection)+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "The WebDriver connection is gone"sv);// 7. Let start node be the result of trying to get a known element with session and URL variables["element id"].- return Web::WebDriver::get_known_element(current_browsing_context(), element_id);+ return Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id);});// 8. Let result be the value of trying to Find with session, start node, location strategy, and selector.- find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {+ connection->find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;// 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.- driver_execution_complete(extract_first_element(move(result)));+ connection->driver_execution_complete(extract_first_element(move(result)));}));- });+ }));return JsonValue {};}@@ -1015,17 +1074,23 @@ Web::WebDriver::Response WebDriverConnection::find_elements_from_element(JsonValTRY(ensure_current_browsing_context_is_open());// 6. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id, location_strategy, selector = move(selector)]() mutable {- auto get_start_node = GC::create_function(GC::Heap::the(), [this, element_id]() -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), element_id, location_strategy, move(selector)), [](auto& connection, auto& element_id, auto& location_strategy, auto& selector) {+ if (!connection)+ return;+ auto get_start_node = GC::create_function(GC::Heap::the(), GC::captures(connection, element_id), [](auto& connection, auto& element_id) -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ if (!connection)+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "The WebDriver connection is gone"sv);// 7. Let start node be the result of trying to get a known element with session and URL variables["element id"].- return Web::WebDriver::get_known_element(current_browsing_context(), element_id);+ return Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id);});// 8. Return the result of trying to Find with session, start node, location strategy, and selector.- find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {- driver_execution_complete(move(result));+ connection->find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;+ connection->driver_execution_complete(move(result));}));- });+ }));return JsonValue {};}@@ -1049,18 +1114,24 @@ Web::WebDriver::Response WebDriverConnection::find_element_from_shadow_root(JsonTRY(ensure_current_browsing_context_is_open());// 6. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, shadow_id, location_strategy, selector = move(selector)]() mutable {- auto get_start_node = GC::create_function(GC::Heap::the(), [this, shadow_id]() -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), shadow_id, location_strategy, move(selector)), [](auto& connection, auto& shadow_id, auto& location_strategy, auto& selector) {+ if (!connection)+ return;+ auto get_start_node = GC::create_function(GC::Heap::the(), GC::captures(connection, shadow_id), [](auto& connection, auto& shadow_id) -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ if (!connection)+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "The WebDriver connection is gone"sv);// 7. Let start node be the result of trying to get a known shadow root with session and URL variables["shadow id"].- return Web::WebDriver::get_known_shadow_root(current_browsing_context(), shadow_id);+ return Web::WebDriver::get_known_shadow_root(connection->current_browsing_context(), shadow_id);});// 8. Let result be the value of trying to Find with session, start node, location strategy, and selector.- find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {+ connection->find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;// 9. If result is empty, return error with error code no such element. Otherwise, return the first element of result.- driver_execution_complete(extract_first_element(move(result)));+ connection->driver_execution_complete(extract_first_element(move(result)));}));- });+ }));return JsonValue {};}@@ -1084,17 +1155,23 @@ Web::WebDriver::Response WebDriverConnection::find_elements_from_shadow_root(JsoTRY(ensure_current_browsing_context_is_open());// 6. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, shadow_id, location_strategy, selector = move(selector)]() mutable {- auto get_start_node = GC::create_function(GC::Heap::the(), [this, shadow_id]() -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), shadow_id, location_strategy, move(selector)), [](auto& connection, auto& shadow_id, auto& location_strategy, auto& selector) {+ if (!connection)+ return;+ auto get_start_node = GC::create_function(GC::Heap::the(), GC::captures(connection, shadow_id), [](auto& connection, auto& shadow_id) -> ErrorOr<GC::Ref<Web::DOM::ParentNode>, Web::WebDriver::Error> {+ if (!connection)+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "The WebDriver connection is gone"sv);// 7. Let start node be the result of trying to get a known shadow root with session and URL variables["shadow id"].- return Web::WebDriver::get_known_shadow_root(current_browsing_context(), shadow_id);+ return Web::WebDriver::get_known_shadow_root(connection->current_browsing_context(), shadow_id);});// 8. Return the result of trying to Find with session, start node, location strategy, and selector.- find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {- driver_execution_complete(move(result));+ connection->find(*location_strategy, move(selector), get_start_node, GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;+ connection->driver_execution_complete(move(result));}));- });+ }));return JsonValue {};}@@ -1106,20 +1183,22 @@ Web::WebDriver::Response WebDriverConnection::get_active_element()TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Let active element be the active element of the current browsing context’s document element.- auto const* active_element = current_browsing_context().active_document()->active_element();+ auto const* active_element = connection->current_browsing_context().active_document()->active_element();// 4. If active element is a non-null element, return success with data set to web element reference object for active element.// Otherwise, return error with error code no such element.if (active_element) {- auto serialized = Web::WebDriver::web_element_reference_object(current_browsing_context(), *active_element);- driver_execution_complete({ move(serialized) });+ auto serialized = Web::WebDriver::web_element_reference_object(connection->current_browsing_context(), *active_element);+ connection->driver_execution_complete({ move(serialized) });return;}- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The current document does not have an active element"sv));- });+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchElement, "The current document does not have an active element"sv));+ }));return JsonValue {};}@@ -1131,25 +1210,27 @@ Web::WebDriver::Response WebDriverConnection::get_element_shadow_root(String eleTRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known element with session and URL variables[element id].- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let shadow root be element's shadow root.auto shadow_root = element->shadow_root();// 5. If shadow root is null, return error with error code no such shadow root.if (!shadow_root) {- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchShadowRoot, MUST(String::formatted("Element with ID '{}' does not have a shadow root", element_id))));+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchShadowRoot, MUST(String::formatted("Element with ID '{}' does not have a shadow root", element_id))));return;}// 6. Let serialized be the shadow root reference object for session and shadow root.- auto serialized = Web::WebDriver::shadow_root_reference_object(current_browsing_context(), *shadow_root);+ auto serialized = Web::WebDriver::shadow_root_reference_object(connection->current_browsing_context(), *shadow_root);// 7. Return success with data serialized.- driver_execution_complete({ move(serialized) });- });+ connection->driver_execution_complete({ move(serialized) });+ }));return JsonValue {};}@@ -1161,9 +1242,11 @@ Web::WebDriver::Response WebDriverConnection::is_element_selected(String elementTRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known connected element with url variable element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let selected be the value corresponding to the first matching statement:bool selected = false;@@ -1186,8 +1269,8 @@ Web::WebDriver::Response WebDriverConnection::is_element_selected(String element// -> False.// 5. Return success with data selected.- driver_execution_complete({ selected });- });+ connection->driver_execution_complete({ selected });+ }));return JsonValue {};}@@ -1199,9 +1282,11 @@ Web::WebDriver::Response WebDriverConnection::get_element_attribute(String elemeTRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id), name]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id), name), [](auto& connection, auto& element_id, auto& name) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known element with session and URL variables' element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let name be URL variables["name"].// 5. Let result be the result of the first matching condition:@@ -1223,8 +1308,8 @@ Web::WebDriver::Response WebDriverConnection::get_element_attribute(String eleme}// 5. Return success with data result.- driver_execution_complete({ move(result) });- });+ connection->driver_execution_complete({ move(result) });+ }));return JsonValue {};}@@ -1236,29 +1321,31 @@ Web::WebDriver::Response WebDriverConnection::get_element_property(String elemenTRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id), name]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id), name), [](auto& connection, auto& element_id, auto& name) {+ if (!connection)+ return;Web::WebDriver::Response result { JsonValue {} };// 3. Let element be the result of trying to get a known element with session and URL variables' element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let name URL variables["name"].// 5. Let property be the result of calling the Object.[[GetProperty]](name) on element.- Web::HTML::TemporaryExecutionContext execution_context { current_browsing_context().active_document()->relevant_settings_object() };+ Web::HTML::TemporaryExecutionContext execution_context { connection->current_browsing_context().active_document()->relevant_settings_object() };- auto& realm = Web::HTML::relevant_realm(*current_browsing_context().active_document());+ auto& realm = Web::HTML::relevant_realm(*connection->current_browsing_context().active_document());auto wrapped_element = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, element);if (auto property_or_error = wrapped_element->get(Utf16FlyString::from_utf8(name)); !property_or_error.is_throw_completion()) {auto property = property_or_error.release_value();// 6. Let result be the value of property if not undefined, or null.if (!property.is_undefined())- result = Web::WebDriver::json_clone(current_browsing_context(), property);+ result = Web::WebDriver::json_clone(connection->current_browsing_context(), property);}// 7. Return success with data result.- driver_execution_complete(move(result));- });+ connection->driver_execution_complete(move(result));+ }));return JsonValue {};}@@ -1270,15 +1357,17 @@ Web::WebDriver::Response WebDriverConnection::get_element_css_value(String elemeTRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id), name]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id), name), [](auto& connection, auto& element_id, auto& name) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known element with URL variables["element id"].- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let computed value be the result of the first matching condition:String computed_value;// -> session's current browsing context's active document's type is not "xml"- if (auto* document = current_browsing_context().active_document(); !document->is_xml_document()) {+ if (auto* document = connection->current_browsing_context().active_document(); !document->is_xml_document()) {document->update_style();// computed value of parameter URL variables["property name"] from element's style declarations.@@ -1297,8 +1386,8 @@ Web::WebDriver::Response WebDriverConnection::get_element_css_value(String eleme// "" (empty string)// 5. Return success with data computed value.- driver_execution_complete({ move(computed_value) });- });+ connection->driver_execution_complete({ move(computed_value) });+ }));return JsonValue {};}@@ -1310,17 +1399,19 @@ Web::WebDriver::Response WebDriverConnection::get_element_text(String element_idTRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known connected element with url variable element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let rendered text be the result of performing implementation-specific steps whose result is exactly the// same as the result of a Function.[[Call]](null, element) with bot.dom.getVisibleText as the this value.auto rendered_text = Web::WebDriver::element_rendered_text(element);// 5. Return success with data rendered text.- driver_execution_complete({ move(rendered_text) });- });+ connection->driver_execution_complete({ move(rendered_text) });+ }));return JsonValue {};}@@ -1332,9 +1423,11 @@ Web::WebDriver::Response WebDriverConnection::get_element_tag_name(String elemenTRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known element with URL variables["element id"].- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let qualified name be the result of getting element's tagName IDL attribute.// FIXME: Spec-issue: The tagName attribute is uppercase, but lowercase is used in other engines.@@ -1342,8 +1435,8 @@ Web::WebDriver::Response WebDriverConnection::get_element_tag_name(String elemenauto qualified_name = element->local_name();// 5. Return success with data qualified name.- driver_execution_complete({ qualified_name.view().to_utf8_but_should_be_ported_to_utf16() });- });+ connection->driver_execution_complete({ qualified_name.view().to_utf8_but_should_be_ported_to_utf16() });+ }));return JsonValue {};}@@ -1355,13 +1448,15 @@ Web::WebDriver::Response WebDriverConnection::get_element_rect(String element_idTRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known connected element with url variable element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Calculate the absolute position of element and let it be coordinates.// 5. Let rect be element’s bounding rectangle.- auto rect = calculate_absolute_rect_of_element(*element);+ auto rect = connection->calculate_absolute_rect_of_element(*element);// 6. Let body be a new JSON Object initialized with:// "x"@@ -1375,8 +1470,8 @@ Web::WebDriver::Response WebDriverConnection::get_element_rect(String element_idauto body = serialize_rect(rect);// 7. Return success with data body.- driver_execution_complete(move(body));- });+ connection->driver_execution_complete(move(body));+ }));return JsonValue {};}@@ -1388,13 +1483,15 @@ Web::WebDriver::Response WebDriverConnection::is_element_enabled(String element_TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known connected element with url variable element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let enabled be a boolean initially set to true if the current browsing context’s active document’s type is not "xml".// 5. Otherwise, let enabled to false and jump to the last step of this algorithm.- bool enabled = !current_browsing_context().active_document()->is_xml_document();+ bool enabled = !connection->current_browsing_context().active_document()->is_xml_document();// 6. Set enabled to false if a form control is disabled.if (auto* form_associated_element = as_if<Web::HTML::FormAssociatedElement>(*element); form_associated_element && enabled) {@@ -1402,8 +1499,8 @@ Web::WebDriver::Response WebDriverConnection::is_element_enabled(String element_}// 7. Return success with data enabled.- driver_execution_complete({ enabled });- });+ connection->driver_execution_complete({ enabled });+ }));return JsonValue {};}@@ -1415,20 +1512,22 @@ Web::WebDriver::Response WebDriverConnection::get_computed_role(String element_iTRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known connected element with url variable element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let role be the result of computing the WAI-ARIA role of element.auto role = element->role_or_default();// 5. Return success with data role.if (role.has_value()) {- driver_execution_complete({ Web::ARIA::role_name(*role).to_utf8() });+ connection->driver_execution_complete({ Web::ARIA::role_name(*role).to_utf8() });return;}- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));return JsonValue {};}@@ -1440,16 +1539,18 @@ Web::WebDriver::Response WebDriverConnection::get_computed_label(String element_TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;// 3. Let element be the result of trying to get a known element with url variable element id.- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Let label be the result of a Accessible Name and Description Computation for the Accessible Name of the element.auto label = element->accessible_name(element->document()).release_value_but_fixme_should_propagate_errors();// 5. Return success with data label.- driver_execution_complete({ label.to_utf8() });- });+ connection->driver_execution_complete({ label.to_utf8() });+ }));return JsonValue {};}@@ -1461,9 +1562,11 @@ Web::WebDriver::Response WebDriverConnection::element_click(String element_id)TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts and return its value if it is an error.- handle_any_user_prompts([this, element_id = move(element_id)]() {- WEBDRIVER_TRY(element_click_impl(element_id));- });+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;+ WEBDRIVER_TRY(connection->element_click_impl(element_id));+ }));return JsonValue {};}@@ -1497,20 +1600,24 @@ Web::WebDriver::Response WebDriverConnection::element_click_impl(StringView elemif (Web::WebDriver::is_element_obscured(paint_tree, *element_container))return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ElementClickIntercepted, "Element is obscured by another element"sv);- auto on_complete = GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;// 9. Wait until the user agent event loop has spun enough times to process the DOM events generated by the// previous step.- m_action_executor = nullptr;+ connection->m_action_executor = nullptr;// FIXME: 10. Perform implementation-defined steps to allow any navigations triggered by the click to start.// 11. Try to wait for navigation to complete.- wait_for_navigation_to_complete(GC::create_function(GC::Heap::the(), [this, result = move(result)](Web::WebDriver::Response navigation_result) mutable {+ connection->wait_for_navigation_to_complete(GC::create_function(GC::Heap::the(), GC::captures(connection, move(result)), [](auto& connection, auto& result, Web::WebDriver::Response navigation_result) {+ if (!connection)+ return;WEBDRIVER_TRY(navigation_result);// FIXME: 12. Try to run the post-navigation checks.- driver_execution_complete(move(result));+ connection->driver_execution_complete(move(result));}));});@@ -1564,7 +1671,7 @@ Web::WebDriver::Response WebDriverConnection::element_click_impl(StringView elem// 8. Fire a click event at parent node.fire_an_event<Web::UIEvents::MouseEvent>(Web::UIEvents::EventNames::click, parent_node);- Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), [on_complete]() {+ Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(on_complete), [](auto& on_complete) {on_complete->function()(JsonValue {});}));}@@ -1622,9 +1729,9 @@ Web::WebDriver::Response WebDriverConnection::element_click_impl(StringView elemVector actions { move(pointer_move_action), move(pointer_down_action), move(pointer_up_action) };// 16. Dispatch a list of actions with input state, actions, current browsing context, and actions options.- m_action_executor = Web::WebDriver::dispatch_list_of_actions(input_state, move(actions), current_browsing_context(), move(actions_options), GC::create_function(GC::Heap::the(), [on_complete, &input_state, input_id = move(input_id)](Web::WebDriver::Response result) {+ m_action_executor = Web::WebDriver::dispatch_list_of_actions(input_state, move(actions), current_browsing_context(), move(actions_options), GC::create_function(GC::Heap::the(), GC::captures(on_complete, GC::Ref<Web::HTML::Navigable> { *m_page_client->page().top_level_traversable() }, move(input_id)), [](auto& on_complete, auto& top_level_traversable, auto& input_id, Web::WebDriver::Response result) {// 17. Remove an input source with input state and input id.- Web::WebDriver::remove_input_source(input_state, input_id);+ Web::WebDriver::remove_input_source(Web::WebDriver::get_input_state(top_level_traversable), input_id);on_complete->function()(move(result));}));@@ -1641,9 +1748,11 @@ Web::WebDriver::Response WebDriverConnection::element_clear(String element_id)TRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id)]() {- driver_execution_complete(element_clear_impl(element_id));- });+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id)), [](auto& connection, auto& element_id) {+ if (!connection)+ return;+ connection->driver_execution_complete(connection->element_clear_impl(element_id));+ }));return JsonValue {};}@@ -1756,9 +1865,11 @@ Web::WebDriver::Response WebDriverConnection::element_send_keys(String element_iTRY(ensure_current_browsing_context_is_open());// 4. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id = move(element_id), text = move(text)]() {- WEBDRIVER_TRY(element_send_keys_impl(element_id, text));- });+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(element_id), move(text)), [](auto& connection, auto& element_id, auto& text) {+ if (!connection)+ return;+ WEBDRIVER_TRY(connection->element_send_keys_impl(element_id, text));+ }));return JsonValue {};}@@ -1919,13 +2030,15 @@ Web::WebDriver::Response WebDriverConnection::element_send_keys_impl(StringViewWeb::WebDriver::add_input_source(input_state, input_id, move(source));// 13. Dispatch actions for a string with arguments input state, input id, and source, text, and session's current browsing context.- m_action_executor = Web::WebDriver::dispatch_actions_for_a_string(input_state, input_id, source, text, current_browsing_context(), GC::create_function(GC::Heap::the(), [this, &input_state, input_id](Web::WebDriver::Response result) {- m_action_executor = nullptr;+ m_action_executor = Web::WebDriver::dispatch_actions_for_a_string(input_state, input_id, source, text, current_browsing_context(), GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), GC::Ref<Web::HTML::Navigable> { *m_page_client->page().top_level_traversable() }, input_id), [](auto& connection, auto& top_level_traversable, auto& input_id, Web::WebDriver::Response result) {+ if (!connection)+ return;+ connection->m_action_executor = nullptr;// 14. Remove an input source with input state and input id.- Web::WebDriver::remove_input_source(input_state, input_id);+ Web::WebDriver::remove_input_source(Web::WebDriver::get_input_state(top_level_traversable), input_id);- driver_execution_complete(move(result));+ connection->driver_execution_complete(move(result));}));// 15. Return success with data null.@@ -1939,8 +2052,10 @@ Web::WebDriver::Response WebDriverConnection::get_source()TRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this]() {- auto* document = current_browsing_context().active_document();+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;+ auto* document = connection->current_browsing_context().active_document();Optional<Utf16String> source;// 3. Let source be the result of invoking the fragment serializing algorithm on a fictional node whose only@@ -1955,8 +2070,8 @@ Web::WebDriver::Response WebDriverConnection::get_source()source = MUST(document->serialize_fragment(Web::HTML::RequireWellFormed::No));// 5. Return success with data source.- driver_execution_complete({ source.release_value().to_utf8_but_should_be_ported_to_utf16() });- });+ connection->driver_execution_complete({ source.release_value().to_utf8_but_should_be_ported_to_utf16() });+ }));return JsonValue {};}@@ -1971,19 +2086,23 @@ Web::WebDriver::Response WebDriverConnection::execute_script(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 3. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this, body = move(body), arguments = move(arguments)]() mutable {- auto script_execution_id = m_script_execution_id_counter++;- m_current_script_execution_id = script_execution_id;+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(body), move(arguments)), [](auto& connection, auto& body, auto& arguments) {+ if (!connection)+ return;+ auto script_execution_id = connection->m_script_execution_id_counter++;+ connection->m_current_script_execution_id = script_execution_id;// 4. Let timeout be session's session timeouts' script timeout.- auto timeout_ms = m_timeouts_configuration.script_timeout;+ auto timeout_ms = connection->m_timeouts_configuration.script_timeout;// This handles steps 5 to 9 and produces the appropriate result type for the following steps.- m_script_timer = Web::WebDriver::execute_script(current_browsing_context(), move(body), move(arguments), timeout_ms, GC::create_function(GC::Heap::the(), [this, script_execution_id](Web::WebDriver::ExecutionResult result) {+ connection->m_script_timer = Web::WebDriver::execute_script(connection->current_browsing_context(), move(body), move(arguments), timeout_ms, GC::create_function(GC::Heap::the(), GC::captures(connection, script_execution_id), [](auto& connection, auto& script_execution_id, Web::WebDriver::ExecutionResult result) {+ if (!connection)+ return;dbgln_if(WEBDRIVER_DEBUG, "Executing script returned: {}", result.value);- handle_script_response(result, script_execution_id);+ connection->handle_script_response(result, script_execution_id);}));- });+ }));return JsonValue {};}@@ -1998,19 +2117,23 @@ Web::WebDriver::Response WebDriverConnection::execute_async_script(JsonValue payTRY(ensure_current_browsing_context_is_open());// 3. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this, body = move(body), arguments = move(arguments)]() mutable {- auto script_execution_id = m_script_execution_id_counter++;- m_current_script_execution_id = script_execution_id;+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(body), move(arguments)), [](auto& connection, auto& body, auto& arguments) {+ if (!connection)+ return;+ auto script_execution_id = connection->m_script_execution_id_counter++;+ connection->m_current_script_execution_id = script_execution_id;// 4. Let timeout be session's session timeouts' script timeout.- auto timeout_ms = m_timeouts_configuration.script_timeout;+ auto timeout_ms = connection->m_timeouts_configuration.script_timeout;// This handles steps 5 to 9 and produces the appropriate result type for the following steps.- m_script_timer = Web::WebDriver::execute_async_script(current_browsing_context(), move(body), move(arguments), timeout_ms, GC::create_function(GC::Heap::the(), [this, script_execution_id](Web::WebDriver::ExecutionResult result) {+ connection->m_script_timer = Web::WebDriver::execute_async_script(connection->current_browsing_context(), move(body), move(arguments), timeout_ms, GC::create_function(GC::Heap::the(), GC::captures(connection, script_execution_id), [](auto& connection, auto& script_execution_id, Web::WebDriver::ExecutionResult result) {+ if (!connection)+ return;dbgln_if(WEBDRIVER_DEBUG, "Executing async script returned: {}", result.value);- handle_script_response(result, script_execution_id);+ connection->handle_script_response(result, script_execution_id);}));- });+ }));return JsonValue {};}@@ -2055,14 +2178,16 @@ Web::WebDriver::Response WebDriverConnection::get_all_cookies()TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Let cookies be a new JSON List.JsonArray cookies;// 4. For each cookie in all associated cookies of the current browsing context’s active document:- auto* document = current_browsing_context().active_document();+ auto* document = connection->current_browsing_context().active_document();- for (auto const& cookie : current_browsing_context().page().client().page_did_request_all_cookies_webdriver(document->url())) {+ for (auto const& cookie : connection->current_browsing_context().page().client().page_did_request_all_cookies_webdriver(document->url())) {// 1. Let serialized cookie be the result of serializing cookie.auto serialized_cookie = serialize_cookie(cookie);@@ -2071,8 +2196,8 @@ Web::WebDriver::Response WebDriverConnection::get_all_cookies()}// 5. Return success with data cookies.- driver_execution_complete({ move(cookies) });- });+ connection->driver_execution_complete({ move(cookies) });+ }));return JsonValue {};}@@ -2084,19 +2209,21 @@ Web::WebDriver::Response WebDriverConnection::get_named_cookie(String name)TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this, name]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), name), [](auto& connection, auto& name) {+ if (!connection)+ return;// 3. If the url variable name is equal to a cookie’s cookie name amongst all associated cookies of the current browsing context’s active document, return success with the serialized cookie as data.- auto* document = current_browsing_context().active_document();+ auto* document = connection->current_browsing_context().active_document();- if (auto cookie = current_browsing_context().page().client().page_did_request_named_cookie(document->url(), name); cookie.has_value()) {+ if (auto cookie = connection->current_browsing_context().page().client().page_did_request_named_cookie(document->url(), name); cookie.has_value()) {auto serialized_cookie = serialize_cookie(*cookie);- driver_execution_complete(move(serialized_cookie));+ connection->driver_execution_complete(move(serialized_cookie));return;}// 4. Otherwise, return error with error code no such cookie.- driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchCookie, MUST(String::formatted("Cookie '{}' not found", name))));- });+ connection->driver_execution_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchCookie, MUST(String::formatted("Cookie '{}' not found", name))));+ }));return JsonValue {};}@@ -2114,9 +2241,11 @@ Web::WebDriver::Response WebDriverConnection::add_cookie(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 4. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this, data = move(const_cast<JsonObject&>(data))]() {- driver_execution_complete(add_cookie_impl(data));- });+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(const_cast<JsonObject&>(data))), [](auto& connection, auto& data) {+ if (!connection)+ return;+ connection->driver_execution_complete(connection->add_cookie_impl(data));+ }));return JsonValue {};}@@ -2211,13 +2340,15 @@ Web::WebDriver::Response WebDriverConnection::delete_cookie(String name)TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this, name]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), name), [](auto& connection, auto& name) {+ if (!connection)+ return;// 3. Delete cookies using the url variable name parameter as the filter argument.- delete_cookies(name);+ connection->delete_cookies(name);// 4. Return success with data null.- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));return JsonValue {};}@@ -2229,13 +2360,15 @@ Web::WebDriver::Response WebDriverConnection::delete_all_cookies()TRY(ensure_current_browsing_context_is_open());// 2. Handle any user prompts, and return its value if it is an error.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Delete cookies, giving no filtering argument.- delete_cookies();+ connection->delete_cookies();// 4. Return success with data null.- driver_execution_complete(JsonValue {});- });+ connection->driver_execution_complete(JsonValue {});+ }));return JsonValue {};}@@ -2247,9 +2380,11 @@ Web::WebDriver::Response WebDriverConnection::perform_actions(JsonValue payload)TRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, payload = move(payload)]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), move(payload)), [](auto& connection, auto& payload) {+ if (!connection)+ return;// 3. Let input state be the result of get the input state with session and session's current top-level browsing context.- auto& input_state = Web::WebDriver::get_input_state(m_page_client->page().top_level_traversable());+ auto& input_state = Web::WebDriver::get_input_state(connection->m_page_client->page().top_level_traversable());// 4. Let actions options be a new actions options with the is element origin steps set to represents a web element,// and the get element origin steps set to get a WebElement origin.@@ -2264,13 +2399,15 @@ Web::WebDriver::Response WebDriverConnection::perform_actions(JsonValue payload)// 6. Dispatch actions with input state, actions by tick, current browsing context, and actions options. If this// results in an error return that error.- auto on_complete = GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {- m_action_executor = nullptr;- driver_execution_complete(move(result));+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;+ connection->m_action_executor = nullptr;+ connection->driver_execution_complete(move(result));});- m_action_executor = Web::WebDriver::dispatch_actions(input_state, move(actions_by_tick), current_browsing_context(), move(actions_options), on_complete);- });+ connection->m_action_executor = Web::WebDriver::dispatch_actions(input_state, move(actions_by_tick), connection->current_browsing_context(), move(actions_options), on_complete);+ }));// 7. Return success with data null.return JsonValue {};@@ -2283,9 +2420,11 @@ Web::WebDriver::Response WebDriverConnection::release_actions()TRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this]() {+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;// 3. Let input state be the result of get the input state with session and current top-level browsing context.- auto& input_state = Web::WebDriver::get_input_state(m_page_client->page().top_level_traversable());+ auto& input_state = Web::WebDriver::get_input_state(connection->m_page_client->page().top_level_traversable());// 4. Let actions options be a new actions options with the is element origin steps set to represents a web element,// and the get element origin steps set to get a WebElement origin.@@ -2307,17 +2446,19 @@ Web::WebDriver::Response WebDriverConnection::release_actions()undo_actions.reverse();// 7. Try to dispatch actions with input state, undo actions, current browsing context, and actions options.- auto on_complete = GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response result) {- m_action_executor = nullptr;+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(connection), [](auto& connection, Web::WebDriver::Response result) {+ if (!connection)+ return;+ connection->m_action_executor = nullptr;// 8. Reset the input state with session and session's current top-level browsing context.- Web::WebDriver::reset_input_state(m_page_client->page().top_level_traversable());+ Web::WebDriver::reset_input_state(connection->m_page_client->page().top_level_traversable());- driver_execution_complete(move(result));+ connection->driver_execution_complete(move(result));});- m_action_executor = Web::WebDriver::dispatch_actions(input_state, { move(undo_actions) }, current_browsing_context(), move(actions_options), on_complete);- });+ connection->m_action_executor = Web::WebDriver::dispatch_actions(input_state, { move(undo_actions) }, connection->current_browsing_context(), move(actions_options), on_complete);+ }));// 9. Return success with data null.return JsonValue {};@@ -2334,8 +2475,10 @@ Web::WebDriver::Response WebDriverConnection::dismiss_alert()return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchAlert, "No user dialog is currently open"sv);// 3. Dismiss the current user prompt.- current_browsing_context().page().dismiss_dialog(GC::create_function(GC::Heap::the(), [this]() {- driver_execution_complete(JsonValue {});+ current_browsing_context().page().dismiss_dialog(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;+ connection->driver_execution_complete(JsonValue {});}));// 4. Return success with data null.@@ -2353,8 +2496,10 @@ Web::WebDriver::Response WebDriverConnection::accept_alert()return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchAlert, "No user dialog is currently open"sv);// 3. Accept the current user prompt.- current_browsing_context().page().accept_dialog(GC::create_function(GC::Heap::the(), [this]() {- driver_execution_complete(JsonValue {});+ current_browsing_context().page().accept_dialog(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;+ connection->driver_execution_complete(JsonValue {});}));// 4. Return success with data null.@@ -2430,19 +2575,25 @@ Web::WebDriver::Response WebDriverConnection::take_screenshot()// FIXME: Spec issue: We must handle user prompts in this endpoint, just like we do in Take Element Screenshot.// https://github.com/w3c/webdriver/issues/1678- handle_any_user_prompts([this]() {- auto* document = current_top_level_browsing_context()->active_document();+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection) {+ if (!connection)+ return;+ auto* document = connection->current_top_level_browsing_context()->active_document();auto window = document->window();// 2. When the user agent is next to run the animation frame callbacks:- (void)window->animation_frame_callback_driver().add(GC::create_function(GC::Heap::the(), [this, document](double) mutable {+ (void)window->animation_frame_callback_driver().add(GC::create_function(GC::Heap::the(), GC::captures(connection, document), [](auto& connection, auto& document, double) {+ if (!connection)+ return;// a. Let root rect be session's current top-level browsing context's document element's rectangle.- auto root_rect = calculate_absolute_rect_of_element(*document->document_element());+ auto root_rect = connection->calculate_absolute_rect_of_element(*document->document_element());// b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given root rect as an argument.- Web::WebDriver::draw_bounding_box_from_the_framebuffer(*current_top_level_browsing_context(), *document->document_element(), root_rect, [this](auto canvas_or_error) mutable {+ Web::WebDriver::draw_bounding_box_from_the_framebuffer(*connection->current_top_level_browsing_context(), *document->document_element(), root_rect, [connection](auto canvas_or_error) mutable {+ if (!connection)+ return;if (canvas_or_error.is_error()) {- driver_execution_complete(canvas_or_error.release_error());+ connection->driver_execution_complete(canvas_or_error.release_error());return;}@@ -2454,11 +2605,11 @@ Web::WebDriver::Response WebDriverConnection::take_screenshot()auto encoded_string = Web::WebDriver::encode_canvas_element(*canvas);// 3. Return success with data encoded string.- driver_execution_complete(move(encoded_string));+ connection->driver_execution_complete(move(encoded_string));});}));document->page().client().request_frame();- });+ }));return JsonValue {};}@@ -2470,25 +2621,31 @@ Web::WebDriver::Response WebDriverConnection::take_element_screenshot(String eleTRY(ensure_current_browsing_context_is_open());// 2. Try to handle any user prompts with session.- handle_any_user_prompts([this, element_id]() {- auto* document = current_browsing_context().active_document();+ handle_any_user_prompts(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), element_id), [](auto& connection, auto& element_id) {+ if (!connection)+ return;+ auto* document = connection->current_browsing_context().active_document();auto window = document->window();// 3. Let element be the result of trying to get a known element with session and URL variables["element id"].- auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(current_browsing_context(), element_id));+ auto element = WEBDRIVER_TRY(Web::WebDriver::get_known_element(connection->current_browsing_context(), element_id));// 4. Scroll into view the element.scroll_element_into_view(element);// 5. When the user agent is next to run the animation frame callbacks:- (void)window->animation_frame_callback_driver().add(GC::create_function(GC::Heap::the(), [this, element](double) {+ (void)window->animation_frame_callback_driver().add(GC::create_function(GC::Heap::the(), GC::captures(connection, element), [](auto& connection, auto& element, double) {+ if (!connection)+ return;// a. Let element rect be element's rectangle.- auto element_rect = calculate_absolute_rect_of_element(element);+ auto element_rect = connection->calculate_absolute_rect_of_element(element);// b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given element rect as an argument.- Web::WebDriver::draw_bounding_box_from_the_framebuffer(current_browsing_context(), element, element_rect, [this](auto canvas_or_error) mutable {+ Web::WebDriver::draw_bounding_box_from_the_framebuffer(connection->current_browsing_context(), element, element_rect, [connection](auto canvas_or_error) mutable {+ if (!connection)+ return;if (canvas_or_error.is_error()) {- driver_execution_complete(canvas_or_error.release_error());+ connection->driver_execution_complete(canvas_or_error.release_error());return;}@@ -2500,11 +2657,11 @@ Web::WebDriver::Response WebDriverConnection::take_element_screenshot(String eleauto encoded_string = Web::WebDriver::encode_canvas_element(*canvas);// 6. Return success with data encoded string.- driver_execution_complete(move(encoded_string));+ connection->driver_execution_complete(move(encoded_string));});}));document->page().client().request_frame();- });+ }));return JsonValue {};}@@ -2548,12 +2705,14 @@ ErrorOr<void, Web::WebDriver::Error> WebDriverConnection::ensure_current_top_lev}// https://w3c.github.io/webdriver/#dfn-handle-any-user-prompts-void WebDriverConnection::handle_any_user_prompts(Function<void()> on_dialog_closed)+void WebDriverConnection::handle_any_user_prompts(GC::Ref<GC::Function<void()>> on_dialog_closed){Web::WebDriver::handle_any_user_prompts(m_page_client->page(),- GC::create_function(GC::Heap::the(), [this, on_dialog_closed = GC::create_function(GC::Heap::the(), move(on_dialog_closed))](Optional<Web::WebDriver::Error> error) {+ GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), on_dialog_closed), [](auto& connection, auto& on_dialog_closed, Optional<Web::WebDriver::Error> error) {+ if (!connection)+ return;if (error.has_value()) {- driver_execution_complete(error.release_value());+ connection->driver_execution_complete(error.release_value());return;}@@ -2564,8 +2723,10 @@ void WebDriverConnection::handle_any_user_prompts(Function<void()> on_dialog_clo// The step left of a command whose page was taken away by the navigation it started.Web::WebDriver::Response WebDriverConnection::wait_for_navigation(){- wait_for_navigation_to_complete(GC::create_function(GC::Heap::the(), [this](Web::WebDriver::Response response) {- driver_execution_complete(move(response));+ wait_for_navigation_to_complete(GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr()), [](auto& connection, Web::WebDriver::Response response) {+ if (!connection)+ return;+ connection->driver_execution_complete(move(response));}));return JsonValue {};@@ -2594,7 +2755,7 @@ void WebDriverConnection::wait_for_navigation_to_complete(OnNavigationComplete oreturn;}- auto reset_observers = [](auto& self) {+ static constexpr auto reset_observers = [](auto& self) {if (self.m_navigation_observer) {self.m_navigation_observer->set_navigation_complete({});self.m_navigation_observer = nullptr;@@ -2620,36 +2781,42 @@ void WebDriverConnection::wait_for_navigation_to_complete(OnNavigationComplete o// 6. Wait for the current browsing context’s document readiness state to reach readiness target,// or for the session page load timeout to pass, whichever occurs sooner.- auto wait_for_document_readiness = [this, readiness_target, reset_observers]() {- reset_observers(*this);+ auto wait_for_document_readiness = GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), readiness_target), [](auto& connection, auto& readiness_target) {+ if (!connection)+ return;+ reset_observers(*connection);- auto* document = current_browsing_context().active_document();+ auto* document = connection->current_browsing_context().active_document();if (!document || document->readiness() == readiness_target) {- m_navigation_timer->stop_and_fire_timeout_handler();+ connection->m_navigation_timer->stop_and_fire_timeout_handler();return;}- m_document_observer = Web::DOM::DocumentObserver::create(*document);- m_document_observer->set_document_readiness_observer([this, readiness_target](Web::HTML::DocumentReadyState readiness) {+ connection->m_document_observer = Web::DOM::DocumentObserver::create(*document);+ connection->m_document_observer->set_document_readiness_observer(GC::create_function(GC::Heap::the(), GC::captures(connection, readiness_target), [](auto& connection, auto& readiness_target, Web::HTML::DocumentReadyState readiness) {+ if (!connection)+ return;if (readiness == readiness_target)- m_navigation_timer->stop_and_fire_timeout_handler();- });- };+ connection->m_navigation_timer->stop_and_fire_timeout_handler();+ }));+ });// 3. Start a timer. If this algorithm has not completed before timer reaches the session’s session page load timeout// in milliseconds, return an error with error code timeout.// NB: The waits below complete by firing this timer's handler early, so it is started before either is armed.m_navigation_timer = GC::Heap::the().allocate<GC::Timer>();- m_navigation_timer->start(m_timeouts_configuration.page_load_timeout.value_or(300'000), GC::create_function(GC::Heap::the(), [this, on_complete, reset_observers]() {- reset_observers(*this);+ m_navigation_timer->start(m_timeouts_configuration.page_load_timeout.value_or(300'000), GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), on_complete), [](auto& connection, auto& on_complete) {+ if (!connection)+ return;+ reset_observers(*connection);- auto did_time_out = m_navigation_timer->is_timed_out();- m_navigation_timer = nullptr;+ auto did_time_out = connection->m_navigation_timer->is_timed_out();+ connection->m_navigation_timer = nullptr;// 7. If the previous step completed by the session page load timeout being reached and the browser does// not have an active user prompt, return error with error code timeout.- if (did_time_out && !current_browsing_context().active_document()->page().has_pending_dialog()) {+ if (did_time_out && !connection->current_browsing_context().active_document()->page().has_pending_dialog()) {on_complete->function()(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::Timeout, "Navigation timed out"sv));return;}@@ -2663,14 +2830,12 @@ void WebDriverConnection::wait_for_navigation_to_complete(OnNavigationComplete o// NB: A navigation matures when its document is activated, which is before that document is ready, so step 6// stands on its own once there is nothing left to mature.if (navigable->ongoing_navigation().has<Empty>()) {- wait_for_document_readiness();+ wait_for_document_readiness->function()();return;}m_navigation_observer = Web::HTML::NavigationObserver::create(*navigable);- m_navigation_observer->set_navigation_complete([wait_for_document_readiness]() {- wait_for_document_readiness();- });+ m_navigation_observer->set_navigation_complete(wait_for_document_readiness);}void WebDriverConnection::page_did_open_dialog(Badge<PageClient>)@@ -2747,14 +2912,16 @@ void WebDriverConnection::wait_for_visibility_state(GC::Ref<GC::Function<void()>auto timer = GC::Heap::the().allocate<GC::Timer>();m_document_observer = Web::DOM::DocumentObserver::create(*document);- m_document_observer->set_document_visibility_state_observer([timer, target_visibility_state](Web::HTML::VisibilityState visibility_state) {+ m_document_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(timer, target_visibility_state), [](auto& timer, auto& target_visibility_state, Web::HTML::VisibilityState visibility_state) {if (visibility_state == target_visibility_state)timer->stop_and_fire_timeout_handler();- });+ }));- timer->start(VISIBILITY_STATE_TIMEOUT_MS, GC::create_function(GC::Heap::the(), [this, on_complete]() {- m_document_observer->set_document_visibility_state_observer({});- m_document_observer = nullptr;+ timer->start(VISIBILITY_STATE_TIMEOUT_MS, GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), on_complete), [](auto& connection, auto& on_complete) {+ if (!connection)+ return;+ connection->m_document_observer->set_document_visibility_state_observer(nullptr);+ connection->m_document_observer = nullptr;on_complete->function()();}));@@ -2804,8 +2971,8 @@ public:return;}- Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this]() {- search_for_element();+ Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {+ self.search_for_element();}));}@@ -2873,8 +3040,9 @@ void WebDriverConnection::find(Web::WebDriver::LocationStrategy location_strateg// 4. Let timer be a new timer.auto timer = GC::Heap::the().allocate<GC::Timer>();- auto wrapped_on_complete = GC::create_function(GC::Heap::the(), [this, on_complete](Web::WebDriver::Response result) {- m_element_locator = nullptr;+ auto wrapped_on_complete = GC::create_function(GC::Heap::the(), GC::captures(make_weak_ptr(), on_complete), [](auto& connection, auto& on_complete, Web::WebDriver::Response result) {+ if (connection)+ connection->m_element_locator = nullptr;on_complete->function()(move(result));});@@ -2885,7 +3053,7 @@ void WebDriverConnection::find(Web::WebDriver::LocationStrategy location_strateg// 5. If timeout is not null:if (timeout.has_value()) {// 1. Start the timer with timer and timeout.- timer->start(*timeout, GC::create_function(GC::Heap::the(), [locator]() {+ timer->start(*timeout, GC::create_function(GC::Heap::the(), GC::captures(locator), [](auto& locator) {locator->complete(JsonValue { JsonArray {} });}));}diff --git a/Services/WebContent/WebDriverConnection.h b/Services/WebContent/WebDriverConnection.hindex c7436710a49..0868783b14f 100644--- a/Services/WebContent/WebDriverConnection.h+++ b/Services/WebContent/WebDriverConnection.h@@ -11,6 +11,7 @@#include <AK/HashTable.h>#include <AK/RefCounted.h>#include <AK/String.h>+#include <AK/Weakable.h>#include <LibGC/RootVector.h>#include <LibGfx/Rect.h>#include <LibJS/Forward.h>@@ -28,7 +29,9 @@ namespace WebContent {class ElementLocator;-class WebDriverConnection final : public RefCounted<WebDriverConnection> {+class WebDriverConnection final+ : public RefCounted<WebDriverConnection>+ , public Weakable<WebDriverConnection> {public:static NonnullRefPtr<WebDriverConnection> create(PageClient&);~WebDriverConnection() = default;@@ -109,7 +112,7 @@ private:Web::WebDriver::Response element_send_keys_impl(StringView element_id, String const& text);Web::WebDriver::Response add_cookie_impl(JsonObject const&);- void handle_any_user_prompts(Function<void()> on_dialog_closed);+ void handle_any_user_prompts(GC::Ref<GC::Function<void()>> on_dialog_closed);void maximize_the_window();void iconify_the_window(GC::Ref<GC::Function<void()>>);diff --git a/Services/WebContent/WebUIConnection.cpp b/Services/WebContent/WebUIConnection.cppindex aff9f4902a5..2b85f8df740 100644--- a/Services/WebContent/WebUIConnection.cpp+++ b/Services/WebContent/WebUIConnection.cpp@@ -54,7 +54,7 @@ WebUIConnection::WebUIConnection(NonnullOwnPtr<IPC::Transport> transport, Web::Dauto& window = Web::HTML::relevant_window(realm.global_object());realm.global_object().define_direct_property(ladybird_property(), Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, Web::Internals::WebUI::create(window)), JS::default_attributes);- Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, m_document, GC::create_function(GC::Heap::the(), [&document = *m_document]() {+ Web::HTML::queue_a_task(Web::HTML::Task::Source::Unspecified, nullptr, m_document, GC::create_function(GC::Heap::the(), GC::captures(*m_document), [](auto& document) {document.dispatch_event(Web::DOM::Event::create(Web::HTML::relevant_global_object(document), web_ui_loaded_event()));}));}diff --git a/Services/WebContent/Worker/ConnectionFromClient.cpp b/Services/WebContent/Worker/ConnectionFromClient.cppindex 8ad6fdcc623..d947c304173 100644--- a/Services/WebContent/Worker/ConnectionFromClient.cpp+++ b/Services/WebContent/Worker/ConnectionFromClient.cpp@@ -393,7 +393,7 @@ void ConnectionFromClient::run_transform_init(u64 transform_id, Web::HTML::Seriaauto transformer = transformer_or_err.release_value();m_transformers.set(transform_id, GC::make_root(transformer));- auto write_encoded_data = GC::create_function(realm.heap(), [link = NonnullRefPtr { *m_dedicated_worker_thread_link }, transform_id](JS::Value chunk) {+ auto write_encoded_data = GC::create_function(realm.heap(), GC::captures(NonnullRefPtr { *m_dedicated_worker_thread_link }, transform_id), [](auto& link, auto& transform_id, JS::Value chunk) {auto* frame = chunk.is_object() ? Web::Bindings::impl_from<Web::WebRTC::RTCEncodedAudioFrame>(&chunk.as_object()) : nullptr;if (!frame) {dbgln_if(WEBRTC_DEBUG, "worker: write algorithm got non-frame value (chunk_is_object={}, class={}) for id={}",@@ -420,7 +420,7 @@ void ConnectionFromClient::run_transform_init(u64 transform_id, Web::HTML::Seria// event fires on the worker's own event loop, after any pending script setup// (e.g. `self.onrtctransform = ...`) has had a chance to run.Web::HTML::queue_global_task(Web::HTML::Task::Source::DOMManipulation, Web::HTML::relevant_global_object(*global_scope),- GC::create_function(realm.heap(), [global_scope, transformer, &realm] {+ GC::create_function(realm.heap(), GC::captures(global_scope, transformer, realm), [](auto& global_scope, auto& transformer, auto& realm) {Web::HTML::TemporaryExecutionContext context(realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);auto event = Web::WebRTC::RTCTransformEvent::create(Web::HTML::EventNames::rtctransform, transformer,Web::HighResolutionTime::current_high_resolution_time(Web::HTML::relevant_global_object(*global_scope)));diff --git a/Services/WebContent/Worker/WorkerHost.cpp b/Services/WebContent/Worker/WorkerHost.cppindex 67b26b69d26..f55bd2fa199 100644--- a/Services/WebContent/Worker/WorkerHost.cpp+++ b/Services/WebContent/Worker/WorkerHost.cpp@@ -194,7 +194,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes: Web::Fetch::Infrastructure::Request::Destination::Worker;// In both cases, let performFetch be the following perform the fetch hook given request, isTopLevel, and processCustomFetchResponse:- auto perform_fetch_function = [inside_settings, outside_settings, worker_global_scope, is_shared, has_process_to_itself](NonnullRefPtr<Web::Fetch::Infrastructure::Request> request, Web::HTML::TopLevelModule is_top_level, Web::Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction process_custom_fetch_response) -> Web::WebIDL::ExceptionOr<void> {+ Web::HTML::PerformTheFetchHook perform_fetch = GC::create_function(inside_settings->heap(), GC::captures(inside_settings, outside_settings, worker_global_scope, is_shared, has_process_to_itself), [](auto& inside_settings, auto& outside_settings, auto& worker_global_scope, auto& is_shared, auto& has_process_to_itself, NonnullRefPtr<Web::Fetch::Infrastructure::Request> request, Web::HTML::TopLevelModule is_top_level, Web::HTML::ProcessCustomFetchResponse process_custom_fetch_response) -> Web::WebIDL::ExceptionOr<void> {auto& realm = inside_settings->realm();Web::Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };@@ -202,7 +202,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes// 1. If isTopLevel is false, fetch request with processResponseConsumeBody set to processCustomFetchResponse,// and abort these steps.if (is_top_level == Web::HTML::TopLevelModule::No) {- fetch_algorithms_input.process_response_consume_body = move(process_custom_fetch_response);+ fetch_algorithms_input.process_response_consume_body = process_custom_fetch_response;Web::Fetch::Fetching::fetch(realm, request, Web::Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));return {};}@@ -210,13 +210,9 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes// 2. Set request's reserved client to inside settings.request->set_reserved_client_snapshot(Web::Fetch::Fetching::snapshot_reserved_client_context(*inside_settings));- // NB: We need to store the process custom fetch response function on the heap here, because we're storing it- // in another heap function- auto process_custom_fetch_response_function = GC::create_function(GC::Heap::the(), move(process_custom_fetch_response));-// 3. Fetch request with processResponseConsumeBody set to the following steps given response response and// null, failure, or a byte sequence bodyBytes:- fetch_algorithms_input.process_response_consume_body = [worker_global_scope, process_custom_fetch_response_function, inside_settings, outside_settings, is_shared, has_process_to_itself](auto response, auto body_bytes) {+ fetch_algorithms_input.process_response_consume_body = GC::create_function(GC::Heap::the(), GC::captures(worker_global_scope, process_custom_fetch_response, inside_settings, outside_settings, is_shared, has_process_to_itself), [](auto& worker_global_scope, auto& process_custom_fetch_response, auto& inside_settings, auto& outside_settings, auto& is_shared, auto& has_process_to_itself, GC::Ref<Web::Fetch::Infrastructure::ResponseView> response, Web::Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {// 1. Set worker global scope's url to response's URL.worker_global_scope->set_url(response->url().value_or({}));@@ -267,16 +263,15 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes}// 10. Run processCustomFetchResponse with response and bodyBytes.- process_custom_fetch_response_function->function()(response, body_bytes);- };+ process_custom_fetch_response->function()(response, body_bytes);+ });Web::Fetch::Fetching::fetch(realm, request, Web::Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));return {};- };- auto perform_fetch = Web::HTML::create_perform_the_fetch_hook(inside_settings->heap(), move(perform_fetch_function));+ });// In both cases, let onComplete given script be the following steps:RefPtr<WorkerHost> protected_this { *this };- auto on_complete_function = [protected_this, page, inside_settings, worker_global_scope, message_port_data = move(message_port_data), outside_settings_snapshot, url = m_url, is_shared](GC::Ptr<Web::HTML::Script> script) mutable {+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(protected_this, page, inside_settings, worker_global_scope, move(message_port_data), outside_settings_snapshot, m_url, is_shared), [](auto& protected_this, auto& page, auto& inside_settings, auto& worker_global_scope, auto& message_port_data, auto& outside_settings_snapshot, auto& url, auto& is_shared, GC::Ptr<Web::HTML::Script> script) {// NB: A worker that was told to close while it fetched its script never runs it.if (worker_global_scope->is_closing())return;@@ -366,8 +361,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes// 15. Event loop: Run the responsible event loop specified by inside settings until it is destroyed.// NB: The event loop runs on from here, and the steps after it are in run_closing_steps().inside_settings->responsible_event_loop().schedule();- };- auto on_complete = Web::HTML::create_on_fetch_script_complete(GC::Heap::the(), move(on_complete_function));+ });// 12. Obtain script by switching on the value of options's type member:if (m_type == Web::HTML::WorkerType::Classic) {@@ -419,7 +413,7 @@ void WorkerHost::connect_shared_worker_impl(Web::HTML::TransferDataEncoder messa// attribute initialized to the empty string, the ports attribute initialized to a new// frozen array containing only insidePort, and the source attribute initialized to// insidePort.- Web::HTML::queue_global_task(Web::HTML::Task::Source::DOMManipulation, Web::HTML::relevant_global_object(*m_worker_global_scope), GC::create_function(GC::Heap::the(), [worker_global_scope = GC::Root { *m_worker_global_scope }, inside_port] {+ Web::HTML::queue_global_task(Web::HTML::Task::Source::DOMManipulation, Web::HTML::relevant_global_object(*m_worker_global_scope), GC::create_function(GC::Heap::the(), GC::captures(GC::Root { *m_worker_global_scope }, inside_port), [](auto& worker_global_scope, auto& inside_port) {auto& realm = worker_global_scope->realm();auto& vm = realm.vm();Web::HTML::TemporaryExecutionContext const context(realm);diff --git a/Tests/ClangPlugins/LibJSGCTests/gc_function_capture_unscanned_gc_pointers.cpp b/Tests/ClangPlugins/LibJSGCTests/gc_function_capture_unscanned_gc_pointers.cppdeleted file mode 100644index db361d7bb15..00000000000--- a/Tests/ClangPlugins/LibJSGCTests/gc_function_capture_unscanned_gc_pointers.cpp+++ /dev/null@@ -1,118 +0,0 @@-/*- * Copyright (c) 2026, Tim Ledbetter <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--// RUN: %clang++ -Xclang -verify %plugin_opts% -c %s -o %t 2>&1--#include <AK/NonnullOwnPtr.h>-#include <AK/OwnPtr.h>-#include <AK/RefCounted.h>-#include <AK/RefPtr.h>-#include <AK/Vector.h>-#include <LibGC/Cell.h>-#include <LibGC/Function.h>-#include <LibGC/Ptr.h>-#include <LibGC/Root.h>-#include <LibGC/RootVector.h>--struct Entry {- // expected-note@+1 5 {{Member cell contains GC pointers}}- GC::Ref<GC::Cell> cell;-};--struct RootedEntry {- GC::Root<GC::Cell> cell;-};--struct SharedEntry : RefCounted<SharedEntry> {- // expected-note@+1 {{Member cell contains GC pointers}}- GC::Ref<GC::Cell> cell;-};--struct State {- NonnullOwnPtr<Entry> entry;-};--struct Params {- virtual ~Params() = default;- virtual void visit_edges(GC::Cell::Visitor&) { }-};--struct ParamsWithCell : Params {- virtual void visit_edges(GC::Cell::Visitor& visitor) override- {- Params::visit_edges(visitor);- visitor.visit(cell);- }-- // expected-note@+1 {{Member cell contains GC pointers}}- GC::Ref<GC::Cell> cell;-};--struct TemplateParamsBase {- virtual ~TemplateParamsBase() = default;- virtual void visit_edges(GC::Cell::Visitor&) { }-};--template<typename T>-struct TemplateParams : TemplateParamsBase {- virtual void visit_edges(GC::Cell::Visitor& visitor) override- {- TemplateParamsBase::visit_edges(visitor);- visitor.visit(cell);- }-- // expected-note@+1 {{Member cell contains GC pointers}}- T cell;-};--static_assert(sizeof(TemplateParams<GC::Ref<GC::Cell>>) > 0);--void unscanned_captures(GC::Heap& heap, Vector<GC::Ref<GC::Cell>> const& cells, NonnullOwnPtr<Entry> entry, NonnullOwnPtr<Entry> other_entry, NonnullOwnPtr<Entry> third_entry, State state, NonnullOwnPtr<Params> params, NonnullOwnPtr<Vector<NonnullOwnPtr<Entry>>> nested_entries, NonnullOwnPtr<TemplateParamsBase> template_params, NonnullOwnPtr<Entry> parenthesized_entry, NonnullRefPtr<SharedEntry> shared_entry)-{- // expected-error@+1 {{Captured 'Vector<GC::Ref<GC::Cell>>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [cells] { (void)cells; });-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<Entry>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [entry = move(entry)] { (void)entry; });-- // expected-error@+1 {{Captured 'NonnullOwnPtr<Entry>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [state = move(state)] { (void)state; });-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<Params>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [params = move(params)] { (void)params; });-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<AK::Vector<AK::NonnullOwnPtr<Entry>>>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [nested_entries = move(nested_entries)] { (void)nested_entries; });-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<TemplateParamsBase>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [template_params = move(template_params)] { (void)template_params; });-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<Entry>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, ([parenthesized_entry = move(parenthesized_entry)] { (void)parenthesized_entry; }));-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<Entry>' keeps GC pointers in heap memory that GC::Function does not scan}}- auto lambda = [other_entry = move(other_entry)] { (void)other_entry; };- (void)GC::create_function(heap, move(lambda));-- // expected-error@+1 {{Captured 'AK::NonnullOwnPtr<Entry>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::Function<void()>::create(heap, [third_entry = move(third_entry)] { (void)third_entry; });-- // expected-error@+1 {{'Vector<GC::Ref<GC::Cell>>' keeps GC pointers in heap memory that is not scanned for roots}}- (void)GC::create_function(heap, [copy = cells] { (void)copy; });-- // expected-error@+1 {{Captured 'NonnullRefPtr<SharedEntry>' keeps GC pointers in heap memory that GC::Function does not scan}}- (void)GC::create_function(heap, [shared_entry] { (void)shared_entry; });-}--void scanned_captures(GC::Heap& heap, GC::Ref<GC::Cell> cell, GC::RootVector<GC::Ref<GC::Cell>> const& rooted_cells, NonnullOwnPtr<RootedEntry> rooted_entry, Entry const& entry)-{- (void)GC::create_function(heap, [cell, rooted_cells, rooted_entry = move(rooted_entry), entry] {- (void)cell;- (void)rooted_cells;- (void)rooted_entry;- (void)entry;- });-}diff --git a/Tests/LibGC/TestGCFunction.cpp b/Tests/LibGC/TestGCFunction.cppindex ae15112dfce..085dde399d7 100644--- a/Tests/LibGC/TestGCFunction.cpp+++ b/Tests/LibGC/TestGCFunction.cpp@@ -73,20 +73,6 @@ struct Holders {GC::Weak<TestCell> cell;};-NEVER_INLINE Holders make_lambda_function_capturing_cell(GC::Heap& heap)-{- auto cell = heap.allocate<TestCell>();- cell->value = 7;- auto function = GC::create_function(heap, [cell] { return static_cast<int>(cell->value); });- return { GC::make_root(function), cell.ptr() };-}--NEVER_INLINE GC::Weak<GC::Function<void()>> make_unrooted_lambda_function_owning(GC::Heap& heap, bool& destroyed)-{- auto function = GC::create_function(heap, [flag = make<DestructionFlag>(destroyed)] { });- return function.ptr();-}-NEVER_INLINE Holders make_function_capturing_cell(GC::Heap& heap){auto cell = heap.allocate<TestCell>();@@ -122,51 +108,6 @@ NEVER_INLINE GC::Weak<GC::Function<void()>> make_unrooted_function_owning(GC::He}-TEST_CASE(lambda_captures_are_scanned_conservatively)-{- GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);- heap.set_incremental_sweep_enabled(false);-- auto holders = make_lambda_function_capturing_cell(heap);- GC::scrub_stack_for_testing();- heap.collect_garbage();-- EXPECT(holders.cell);- EXPECT_EQ(holders.function->function()(), 7);-}--TEST_CASE(lambda_captures_are_destroyed_with_the_function)-{- GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);- heap.set_incremental_sweep_enabled(false);-- bool destroyed = false;- auto function = make_unrooted_lambda_function_owning(heap, destroyed);- GC::scrub_stack_for_testing();- heap.collect_garbage();-- EXPECT(!function);- EXPECT(destroyed);-}--TEST_CASE(function_stays_alive_while_it_runs)-{- GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);- heap.set_incremental_sweep_enabled(false);-- auto state = adopt_ref(*new RunState);- auto holder = GC::make_root(heap.allocate<CellWithFunction>());- holder->function = GC::create_function(heap, [holder = GC::Ref { *holder }, state] {- holder->function = nullptr;- holder->heap().collect_garbage();- state->survived_collection = static_cast<bool>(state->function);- });- state->function = holder->function;-- holder->function->function()();- EXPECT(state->survived_collection);-}-TEST_CASE(captured_cell_is_traced){GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);diff --git a/Tests/LibGC/TestMember.cpp b/Tests/LibGC/TestMember.cppindex 9bb8dc643b0..cb7df807cbc 100644--- a/Tests/LibGC/TestMember.cpp+++ b/Tests/LibGC/TestMember.cpp@@ -243,11 +243,45 @@ private:GC_DEFINE_ALLOCATOR(FinalizationTrackingCell);// Keeps nothing on the stack that points at the cell the function captures, other than the root of the function.+static NEVER_INLINE GC::Root<GC::Function<size_t()>> make_function_capturing_a_member(bool& finalized)+{+ GC::Member<FinalizationTrackingCell> member = test_heap().allocate<FinalizationTrackingCell>(finalized);+ return GC::make_root(GC::create_function(test_heap(), GC::captures(member), [](GC::Ptr<FinalizationTrackingCell>& cell) {+ return reinterpret_cast<size_t>(cell.ptr());+ }));+}++// Scans the captures of an AK::Function for cell pointers, as a timer does for its callback.+class CallbackScanningCell final : public GC::Cell {+ GC_CELL(CallbackScanningCell, GC::Cell);+ GC_DECLARE_ALLOCATOR(CallbackScanningCell);++public:+ explicit CallbackScanningCell(AK::Function<size_t()> callback)+ : m_callback(move(callback))+ {+ }++ size_t call() const { return m_callback(); }++private:+ virtual void visit_edges(Visitor& visitor) override+ {+ Base::visit_edges(visitor);+ visitor.visit_possible_values(m_callback.raw_capture_range());+ }++ AK::Function<size_t()> m_callback;+};++GC_DEFINE_ALLOCATOR(CallbackScanningCell);++// Keeps nothing on the stack that points at the cell the callback captures, other than the root of the scanning cell.template<typename MakeCallable>-static NEVER_INLINE GC::Root<GC::Function<size_t()>> make_function_capturing_a_member(bool& finalized, MakeCallable make_callable)+static NEVER_INLINE GC::Root<CallbackScanningCell> make_callback_capturing_a_member(bool& finalized, MakeCallable make_callable){GC::Member<FinalizationTrackingCell> member = test_heap().allocate<FinalizationTrackingCell>(finalized);- return GC::make_root(GC::create_function(test_heap(), make_callable(member)));+ return GC::make_root(test_heap().allocate<CallbackScanningCell>(make_callable(member)));}static NEVER_INLINE void clobber_the_stack()@@ -257,12 +291,26 @@ static NEVER_INLINE void clobber_the_stack()byte = 0;}-TEST_CASE(function_whose_only_capture_is_a_member_keeps_its_cell_alive)+TEST_CASE(function_capturing_a_member_keeps_its_cell_alive)+{+ // NB: Static, since the cell outlives the test once nothing holds it anymore.+ static bool finalized;+ finalized = false;+ auto function = make_function_capturing_a_member(finalized);+ clobber_the_stack();++ test_heap().collect_garbage(GC::Heap::CollectionType::CollectGarbage);++ EXPECT(!finalized);+ EXPECT_NE(function->function()(), 0u);+}++TEST_CASE(callback_whose_only_capture_is_a_member_keeps_its_cell_alive){// NB: Static, since the cell outlives the test once nothing holds it anymore.static bool finalized;finalized = false;- auto function = make_function_capturing_a_member(finalized, [](GC::Member<FinalizationTrackingCell> member) {+ auto cell = make_callback_capturing_a_member(finalized, [](GC::Member<FinalizationTrackingCell> member) {auto callable = [member] { return reinterpret_cast<size_t>(member.ptr()); };static_assert(sizeof(callable) == sizeof(u32));return callable;@@ -272,15 +320,15 @@ TEST_CASE(function_whose_only_capture_is_a_member_keeps_its_cell_alive)test_heap().collect_garbage(GC::Heap::CollectionType::CollectGarbage);EXPECT(!finalized);- EXPECT_NE(function->function()(), 0u);+ EXPECT_NE(cell->call(), 0u);}-TEST_CASE(function_whose_captures_end_in_a_member_keeps_its_cell_alive)+TEST_CASE(callback_whose_captures_end_in_a_member_keeps_its_cell_alive){// NB: Static, since the cell outlives the test once nothing holds it anymore.static bool finalized;finalized = false;- auto function = make_function_capturing_a_member(finalized, [](GC::Member<FinalizationTrackingCell> member) {+ auto cell = make_callback_capturing_a_member(finalized, [](GC::Member<FinalizationTrackingCell> member) {auto callable = [first = static_cast<u32>(1), second = static_cast<u32>(2), member] {return reinterpret_cast<size_t>(member.ptr()) + first + second;};@@ -293,7 +341,7 @@ TEST_CASE(function_whose_captures_end_in_a_member_keeps_its_cell_alive)test_heap().collect_garbage(GC::Heap::CollectionType::CollectGarbage);EXPECT(!finalized);- EXPECT_NE(function->function()(), 0u);+ EXPECT_NE(cell->call(), 0u);}// Walks a list of cells through compressed pointers, decoding them against the base copy or against the base exporteddiff --git a/Tests/LibJS/TestVMThreads.cpp b/Tests/LibJS/TestVMThreads.cppindex de16ab476df..af2e00cb14f 100644--- a/Tests/LibJS/TestVMThreads.cpp+++ b/Tests/LibJS/TestVMThreads.cpp@@ -6,6 +6,7 @@#include <AK/Array.h>#include <AK/Atomic.h>+#include <AK/AtomicRefCounted.h>#include <AK/ByteString.h>#include <AK/HashMap.h>#include <AK/HashTable.h>@@ -313,13 +314,18 @@ static constexpr StringView NEVER_ENDING_PROMISE_JOBS[] = {"function again() { Promise.resolve().then(() => { throw 1; }).catch(() => { jobRan(); again(); }); } again();"sv,};+// NB: The native function the script calls sets this, so it is shared with the function's captures.+struct JobRanFlag : AtomicRefCounted<JobRanFlag> {+ Atomic<bool> value { false };+};+struct InterruptedScript {AK_ALLOC_WITH_KMALLOC;StringView source;bool is_promise_job { false };Atomic<JS::VM*> vm { nullptr };- Atomic<bool> job_ran { false };+ NonnullRefPtr<JobRanFlag> job_ran { make_ref_counted<JobRanFlag>() };bool did_throw { false };bool reached { false };MonotonicTime interrupted_at { MonotonicTime::now() };@@ -333,9 +339,9 @@ static void run_script_until_it_is_interrupted(InterruptedScript& interrupted)auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);auto& realm = *root_execution_context->realm;- auto job_ran = JS::NativeFunction::create(realm, [&interrupted](JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {- interrupted.job_ran = true;- return JS::js_undefined(); }, 0, JS::PropertyKey { "jobRan"_utf16_fly_string });+ auto job_ran = JS::NativeFunction::create(realm, GC::create_function(vm->heap(), GC::captures(interrupted.job_ran), [](NonnullRefPtr<JobRanFlag>& job_ran, JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {+ job_ran->value = true;+ return JS::js_undefined(); }), 0, JS::PropertyKey { "jobRan"_utf16_fly_string });realm.global_object().define_direct_property(JS::PropertyKey { "jobRan"_utf16_fly_string }, job_ran, JS::default_attributes);auto source_text = Utf16String::from_utf8_without_validation(interrupted.source.bytes());auto script = JS::Script::parse(source_text.utf16_view(), realm);@@ -389,7 +395,7 @@ static void interrupt_every_never_ending_script(StringView jit_options)MUST(Core::System::sleep_ms(50));for (auto& script : scripts) {- while (!script->vm || (script->is_promise_job && !script->job_ran))+ while (!script->vm || (script->is_promise_job && !script->job_ran->value))MUST(Core::System::sleep_ms(1));script->interrupted_at = MonotonicTime::now();script->vm.load()->request_interrupt();diff --git a/Tests/LibWeb/TestAgentThreads.cpp b/Tests/LibWeb/TestAgentThreads.cppindex 2f249d8d675..f28ded1812a 100644--- a/Tests/LibWeb/TestAgentThreads.cpp+++ b/Tests/LibWeb/TestAgentThreads.cpp@@ -431,8 +431,8 @@ public:(void)script->run();auto& global_object = m_settings->realm().global_object();- IGNORE_USE_IN_ESCAPING_LAMBDA JS::PropertyKey result_key { "testResult"_utf16_fly_string };- Web::HTML::current_event_loop().spin_until(GC::create_function(GC::Heap::the(), [&] {+ JS::PropertyKey result_key { "testResult"_utf16_fly_string };+ Web::HTML::current_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(global_object, result_key), [](JS::Object& global_object, JS::PropertyKey const& result_key) {return !global_object.get_without_side_effects(result_key).is_undefined();}));diff --git a/Tests/LibWeb/TestFaviconDecoding.cpp b/Tests/LibWeb/TestFaviconDecoding.cppindex fb4d415018f..e0c73935c99 100644--- a/Tests/LibWeb/TestFaviconDecoding.cpp+++ b/Tests/LibWeb/TestFaviconDecoding.cpp@@ -65,7 +65,7 @@ TEST_CASE(each_favicon_is_decoded_once)link.set_rel("icon"_utf16);link.set_href(source);MUST(document->head()->append_child(element));- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(document->heap(), [link = GC::Ref { link }] {+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(document->heap(), GC::captures(GC::Ref { link }), [](auto& link) {return link->has_loaded_icon();}));++expected_decode_count;diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppindex 785f90784a6..b70efbe49c9 100644--- a/Tests/LibWeb/TestFetchAlgorithms.cpp+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -5,9 +5,11 @@*/#include "FetchTestDocument.h"+#include <AK/RefCounted.h>#include <LibCore/EventLoop.h>#include <LibCore/Timer.h>-#include <LibGC/RootVector.h>+#include <LibGC/Function.h>+#include <LibGC/Root.h>#include <LibGC/Testing.h>#include <LibTest/TestCase.h>#include <LibURL/Parser.h>@@ -26,6 +28,15 @@ using Web::Fetch::Infrastructure::ResponseView;namespace {+// What the algorithms of a fetch saw, which the test reads once they have run.+struct AlgorithmCalls : RefCounted<AlgorithmCalls> {+ Vector<StringView> calls;+ Vector<GC::Root<ResponseView>> responses;+ Optional<ByteBuffer> consumed_bytes;+ size_t call_count { 0 };+ bool consumed_body { false };+};+struct FetchHarness {FetchHarness(): document(create_test_document())@@ -62,12 +73,12 @@ struct FetchHarness {}// Runs the fetch's steps and the tasks they queue until the condition holds, or for ten seconds.- void run_tasks_until(ESCAPING Function<bool()> condition) const+ void run_tasks_until(GC::Ref<GC::Function<bool()>> condition) const{auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(10), [] { });deadline->start();- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(realm->heap(), [condition = move(condition), deadline] {- return condition() || !deadline->is_active();+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(realm->heap(), GC::captures(condition, deadline), [](auto& condition, auto& deadline) {+ return condition->function()() || !deadline->is_active();}));}@@ -83,27 +94,29 @@ TEST_CASE(each_algorithm_gets_the_same_response_in_order)install_font_plugin();FetchHarness harness;- IGNORE_USE_IN_ESCAPING_LAMBDA Vector<StringView> calls;- GC::RootVector<GC::Ref<ResponseView>> responses;+ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<AlgorithmCalls>();FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };- input.process_response = [&](GC::Ref<ResponseView> response) {- calls.append("process response"sv);- responses.append(response);- };- input.process_response_end_of_body = [&](GC::Ref<ResponseView> response) {- calls.append("process response end-of-body"sv);- responses.append(response);- };- input.process_response_consume_body = [&](GC::Ref<ResponseView> response, FetchAlgorithms::BodyBytes body) {- calls.append("process response consume body"sv);- responses.append(response);+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append("process response"sv);+ record->responses.append(GC::make_root(response));+ });+ input.process_response_end_of_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append("process response end-of-body"sv);+ record->responses.append(GC::make_root(response));+ });+ input.process_response_consume_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response, FetchAlgorithms::BodyBytes body) {+ record->calls.append("process response consume body"sv);+ record->responses.append(GC::make_root(response));EXPECT(body.has<Empty>());- };+ });auto request = harness.create_request();(void)harness.fetch(request, move(input));- harness.run_tasks_until([&] { return calls.size() == 3; });+ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 3; }));+ auto const& calls = record->calls;+ auto const& responses = record->responses;EXPECT_EQ(calls, (Vector<StringView> { "process response"sv, "process response end-of-body"sv, "process response consume body"sv }));VERIFY(responses.size() == 3);EXPECT(responses[0]->is_network_error());@@ -117,29 +130,31 @@ TEST_CASE(each_algorithm_gets_the_same_response_with_a_body_in_order)install_font_plugin();FetchHarness harness;- IGNORE_USE_IN_ESCAPING_LAMBDA Vector<StringView> calls;- GC::RootVector<GC::Ref<ResponseView>> responses;- Optional<ByteBuffer> consumed_bytes;+ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<AlgorithmCalls>();FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };- input.process_response = [&](GC::Ref<ResponseView> response) {- calls.append("process response"sv);- responses.append(response);- };- input.process_response_end_of_body = [&](GC::Ref<ResponseView> response) {- calls.append("process response end-of-body"sv);- responses.append(response);- };- input.process_response_consume_body = [&](GC::Ref<ResponseView> response, FetchAlgorithms::BodyBytes body) {- calls.append("process response consume body"sv);- responses.append(response);+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append("process response"sv);+ record->responses.append(GC::make_root(response));+ });+ input.process_response_end_of_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ record->calls.append("process response end-of-body"sv);+ record->responses.append(GC::make_root(response));+ });+ input.process_response_consume_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response, FetchAlgorithms::BodyBytes body) {+ record->calls.append("process response consume body"sv);+ record->responses.append(GC::make_root(response));if (auto const* bytes = body.get_pointer<Core::ImmutableBytes>())- consumed_bytes = MUST(ByteBuffer::copy(bytes->bytes()));- };+ record->consumed_bytes = MUST(ByteBuffer::copy(bytes->bytes()));+ });auto request = harness.create_request_for("data:text/plain,hello"sv);(void)harness.fetch(request, move(input));- harness.run_tasks_until([&] { return calls.size() == 3; });+ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 3; }));+ auto const& calls = record->calls;+ auto const& responses = record->responses;+ auto const& consumed_bytes = record->consumed_bytes;EXPECT_EQ(calls, (Vector<StringView> { "process response"sv, "process response end-of-body"sv, "process response consume body"sv }));VERIFY(responses.size() == 3);EXPECT(!responses[0]->is_network_error());@@ -155,18 +170,19 @@ TEST_CASE(a_fetch_stopped_before_its_response_runs_no_algorithm_but_its_request_install_font_plugin();FetchHarness harness;- size_t call_count = 0;+ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<AlgorithmCalls>();FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };- input.process_response = [&](GC::Ref<ResponseView>) { ++call_count; };- input.process_response_end_of_body = [&](GC::Ref<ResponseView>) { ++call_count; };- input.process_response_consume_body = [&](GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { ++call_count; };+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>) { ++record->call_count; });+ input.process_response_end_of_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>) { ++record->call_count; });+ input.process_response_consume_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { ++record->call_count; });- IGNORE_USE_IN_ESCAPING_LAMBDA auto request = harness.create_request();+ auto request = harness.create_request();auto controller = harness.fetch(request, move(input));controller->stop_fetch();- harness.run_tasks_until([&] { return request->done(); });+ harness.run_tasks_until(GC::create_function(heap, GC::captures(request), [](auto& request) { return request->done(); }));- EXPECT_EQ(call_count, 0u);+ EXPECT_EQ(record->call_count, 0u);EXPECT(request->done());}@@ -176,23 +192,24 @@ TEST_CASE(a_stop_leaves_the_algorithms_for_the_next_fetch)install_font_plugin();FetchHarness harness;- IGNORE_USE_IN_ESCAPING_LAMBDA size_t call_count = 0;+ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<AlgorithmCalls>();FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };- input.process_response = [&](GC::Ref<ResponseView>) { ++call_count; };- input.process_response_end_of_body = [&](GC::Ref<ResponseView>) { ++call_count; };- input.process_response_consume_body = [&](GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { ++call_count; };+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>) { ++record->call_count; });+ input.process_response_end_of_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>) { ++record->call_count; });+ input.process_response_consume_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { ++record->call_count; });auto algorithms = FetchAlgorithms::create(move(input));- IGNORE_USE_IN_ESCAPING_LAMBDA auto stopped_request = harness.create_request();+ auto stopped_request = harness.create_request();harness.fetch_with(stopped_request, algorithms)->stop_fetch();- harness.run_tasks_until([&] { return stopped_request->done(); });- EXPECT_EQ(call_count, 0u);+ harness.run_tasks_until(GC::create_function(heap, GC::captures(stopped_request), [](auto& stopped_request) { return stopped_request->done(); }));+ EXPECT_EQ(record->call_count, 0u);// A stop empties the stopped fetch's algorithms, not the caller's.auto request = harness.create_request();(void)harness.fetch_with(request, algorithms);- harness.run_tasks_until([&] { return call_count == 3; });- EXPECT_EQ(call_count, 3u);+ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->call_count == 3; }));+ EXPECT_EQ(record->call_count, 3u);}static NEVER_INLINE void start_fetch_without_holding_its_controller(FetchHarness const& harness, Request& request, FetchAlgorithms::Input input)@@ -204,23 +221,24 @@ static NEVER_INLINE void run_a_fetch_whose_controller_nothing_holds(){Core::EventLoop event_loop;install_font_plugin();- IGNORE_USE_IN_ESCAPING_LAMBDA FetchHarness harness;+ FetchHarness harness;- IGNORE_USE_IN_ESCAPING_LAMBDA bool consumed_body = false;+ auto& heap = harness.realm->heap();+ auto record = make_ref_counted<AlgorithmCalls>();FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::ConsumeForCallback };- input.process_response_consume_body = [&](GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { consumed_body = true; };+ input.process_response_consume_body = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView>, FetchAlgorithms::BodyBytes) { record->consumed_body = true; });// A worker's script fetch has no fetch record, so only its own steps hold its controller.auto request = harness.create_request();request->set_destination(Request::Destination::Worker);start_fetch_without_holding_its_controller(harness, request, move(input));GC::scrub_stack_for_testing();- harness.run_tasks_until([&] {- harness.realm->heap().collect_garbage();- return consumed_body;- });+ harness.run_tasks_until(GC::create_function(heap, GC::captures(harness.realm, record), [](auto& realm, auto& record) {+ realm->heap().collect_garbage();+ return record->consumed_body;+ }));- EXPECT(consumed_body);+ EXPECT(record->consumed_body);}TEST_CASE(a_fetch_whose_controller_nothing_holds_still_runs_its_algorithms)diff --git a/Tests/LibWeb/TestFetchBodyStream.cpp b/Tests/LibWeb/TestFetchBodyStream.cppindex 18d59ae5c0c..c83510e3b4f 100644--- a/Tests/LibWeb/TestFetchBodyStream.cpp+++ b/Tests/LibWeb/TestFetchBodyStream.cpp@@ -5,6 +5,7 @@*/#include "FetchTestDocument.h"+#include <AK/RefCounted.h>#include <AK/Time.h>#include <LibCore/EventLoop.h>#include <LibCore/Timer.h>@@ -108,7 +109,7 @@ struct BodyStreamHarness {if (!request->settled()) {auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(10), [] { });deadline->start();- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(realm->heap(), [request, deadline] {+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(realm->heap(), GC::captures(request, deadline), [](auto& request, auto& deadline) {return request->settled() || !deadline->is_active();}));}@@ -132,21 +133,27 @@ struct BodyStreamHarness {GC::Ptr<Web::Streams::ReadableStreamDefaultReader> reader;};-struct SniffWaiter {+struct SniffWaiter : RefCounted<SniffWaiter> {size_t wake_count { 0 };ByteBuffer bytes;Optional<Body::SniffOutcome> outcome;Body::SniffBytesCallback callback(GC::Heap& heap){- return GC::create_function(heap, [this](Body::SniffBytes sniff_bytes) {- ++wake_count;- bytes = MUST(ByteBuffer::copy(sniff_bytes.bytes));- outcome = sniff_bytes.outcome;+ return GC::create_function(heap, GC::captures(NonnullRefPtr { *this }), [](auto& waiter, Body::SniffBytes sniff_bytes) {+ ++waiter->wake_count;+ waiter->bytes = MUST(ByteBuffer::copy(sniff_bytes.bytes));+ waiter->outcome = sniff_bytes.outcome;});}};+// A value that the callbacks of a test change, and the test reads afterwards.+template<typename T>+struct SharedValue : RefCounted<SharedValue<T>> {+ T value {};+};+Core::ImmutableBytes make_bytes(size_t size, u8 first_value){auto bytes = MUST(ByteBuffer::create_uninitialized(size));@@ -156,12 +163,12 @@ Core::ImmutableBytes make_bytes(size_t size, u8 first_value)}// Runs channel wakes and networking tasks until the waiter has woken, or for ten seconds.-void wait_for_wake(GC::Heap& heap, SniffWaiter const& waiter)+void wait_for_wake(GC::Heap& heap, NonnullRefPtr<SniffWaiter> const& waiter){auto deadline = Core::Timer::create_single_shot(AK::Duration::from_seconds(10), [] { });deadline->start();- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(heap, [&waiter, deadline] {- return waiter.wake_count > 0 || !deadline->is_active();+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(heap, GC::captures(waiter, deadline), [](auto& waiter, auto& deadline) {+ return waiter->wake_count > 0 || !deadline->is_active();}));}@@ -169,11 +176,11 @@ void wait_for_wake(GC::Heap& heap, SniffWaiter const& waiter)void run_wakes_and_tasks(GC::Heap& heap){BodyStreamHarness::run_wakes();- IGNORE_USE_IN_ESCAPING_LAMBDA bool reached = false;- Web::HTML::queue_a_task(Web::HTML::Task::Source::Networking, Web::HTML::main_thread_event_loop(), nullptr, GC::create_function(heap, [&reached] {- reached = true;+ auto reached = make_ref_counted<SharedValue<bool>>();+ Web::HTML::queue_a_task(Web::HTML::Task::Source::Networking, Web::HTML::main_thread_event_loop(), nullptr, GC::create_function(heap, GC::captures(reached), [](auto& reached) {+ reached->value = true;}));- Web::HTML::main_thread_event_loop().spin_until(GC::create_function(heap, [&reached] { return reached; }));+ Web::HTML::main_thread_event_loop().spin_until(GC::create_function(heap, GC::captures(reached), [](auto& reached) { return reached->value; }));}}@@ -257,20 +264,20 @@ TEST_CASE(sniffing_waits_for_the_resource_header_and_leaves_it_in_the_channel)harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });auto& heap = harness.realm->heap();- SniffWaiter waiter;- harness.body->wait_for_sniff_bytes(waiter.callback(heap));+ auto waiter = make_ref_counted<SniffWaiter>();+ harness.body->wait_for_sniff_bytes(waiter->callback(heap));auto whole_body = make_bytes(2000, 0);EXPECT_EQ(harness.channel->write(whole_body.slice(0, 500)), FetchByteChannel::WriteResult::Accepted);run_wakes_and_tasks(heap);- EXPECT_EQ(waiter.wake_count, 0u);+ EXPECT_EQ(waiter->wake_count, 0u);EXPECT_EQ(harness.channel->write(whole_body.slice(500, 1500)), FetchByteChannel::WriteResult::Accepted);- EXPECT_EQ(waiter.wake_count, 0u);+ EXPECT_EQ(waiter->wake_count, 0u);wait_for_wake(heap, waiter);- EXPECT_EQ(waiter.wake_count, 1u);- EXPECT(waiter.outcome == Body::SniffOutcome::Complete);- EXPECT_EQ(waiter.bytes.bytes(), whole_body.bytes().trim(MAX_SNIFF_BYTES));+ EXPECT_EQ(waiter->wake_count, 1u);+ EXPECT(waiter->outcome == Body::SniffOutcome::Complete);+ EXPECT_EQ(waiter->bytes.bytes(), whole_body.bytes().trim(MAX_SNIFF_BYTES));// A transfer of the body after sniffing still carries it from its first byte.ByteBuffer transferred;@@ -294,16 +301,16 @@ TEST_CASE(sniffing_a_body_set_up_during_a_pause_waits_for_the_resource_header)}EXPECT_EQ(harness.channel->write(whole_body.slice(100, 400)), FetchByteChannel::WriteResult::Accepted);- SniffWaiter waiter;- harness.body->wait_for_sniff_bytes(waiter.callback(heap));+ auto waiter = make_ref_counted<SniffWaiter>();+ harness.body->wait_for_sniff_bytes(waiter->callback(heap));run_wakes_and_tasks(heap);- EXPECT_EQ(waiter.wake_count, 0u);+ EXPECT_EQ(waiter->wake_count, 0u);EXPECT_EQ(harness.channel->write(whole_body.slice(500, 1500)), FetchByteChannel::WriteResult::Accepted);wait_for_wake(heap, waiter);- EXPECT_EQ(waiter.wake_count, 1u);- EXPECT(waiter.outcome == Body::SniffOutcome::Complete);- EXPECT_EQ(waiter.bytes.bytes(), whole_body.bytes().trim(MAX_SNIFF_BYTES));+ EXPECT_EQ(waiter->wake_count, 1u);+ EXPECT(waiter->outcome == Body::SniffOutcome::Complete);+ EXPECT_EQ(waiter->bytes.bytes(), whole_body.bytes().trim(MAX_SNIFF_BYTES));ByteBuffer transferred;for (auto const& taken : harness.channel->transfer_out())@@ -319,16 +326,16 @@ TEST_CASE(sniffing_a_body_that_ends_short_gives_all_of_it)harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });auto& heap = harness.realm->heap();- SniffWaiter waiter;- harness.body->wait_for_sniff_bytes(waiter.callback(heap));+ auto waiter = make_ref_counted<SniffWaiter>();+ harness.body->wait_for_sniff_bytes(waiter->callback(heap));EXPECT_EQ(harness.channel->write(MUST(Core::ImmutableBytes::copy("short"sv.bytes()))), FetchByteChannel::WriteResult::Accepted);(void)harness.channel->close();- EXPECT_EQ(waiter.wake_count, 0u);+ EXPECT_EQ(waiter->wake_count, 0u);wait_for_wake(heap, waiter);- EXPECT_EQ(waiter.wake_count, 1u);- EXPECT(waiter.outcome == Body::SniffOutcome::Complete);- EXPECT_EQ(waiter.bytes, MUST(ByteBuffer::copy("short"sv.bytes())));+ EXPECT_EQ(waiter->wake_count, 1u);+ EXPECT(waiter->outcome == Body::SniffOutcome::Complete);+ EXPECT_EQ(waiter->bytes, MUST(ByteBuffer::copy("short"sv.bytes())));}TEST_CASE(sniffing_a_body_that_errors_fails)@@ -339,15 +346,15 @@ TEST_CASE(sniffing_a_body_that_errors_fails)harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });auto& heap = harness.realm->heap();- SniffWaiter waiter;- harness.body->wait_for_sniff_bytes(waiter.callback(heap));+ auto waiter = make_ref_counted<SniffWaiter>();+ harness.body->wait_for_sniff_bytes(waiter->callback(heap));EXPECT_EQ(harness.channel->write(MUST(Core::ImmutableBytes::copy("partial"sv.bytes()))), FetchByteChannel::WriteResult::Accepted);(void)harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) });- EXPECT_EQ(waiter.wake_count, 0u);+ EXPECT_EQ(waiter->wake_count, 0u);wait_for_wake(heap, waiter);- EXPECT_EQ(waiter.wake_count, 1u);- EXPECT(waiter.outcome == Body::SniffOutcome::Failed);+ EXPECT_EQ(waiter->wake_count, 1u);+ EXPECT(waiter->outcome == Body::SniffOutcome::Failed);}TEST_CASE(sniffing_keeps_a_complete_header_through_a_later_error)@@ -358,18 +365,18 @@ TEST_CASE(sniffing_keeps_a_complete_header_through_a_later_error)harness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });auto& heap = harness.realm->heap();- SniffWaiter waiter;- harness.body->wait_for_sniff_bytes(waiter.callback(heap));+ auto waiter = make_ref_counted<SniffWaiter>();+ harness.body->wait_for_sniff_bytes(waiter->callback(heap));// The body fails once its resource header is complete, before the sniff waiter's wake has run.auto header = make_bytes(MAX_SNIFF_BYTES, 0);EXPECT_EQ(harness.channel->write(header), FetchByteChannel::WriteResult::Accepted);(void)harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) });- EXPECT_EQ(waiter.wake_count, 0u);+ EXPECT_EQ(waiter->wake_count, 0u);wait_for_wake(heap, waiter);- EXPECT_EQ(waiter.wake_count, 1u);- EXPECT(waiter.outcome == Body::SniffOutcome::Complete);- EXPECT_EQ(waiter.bytes.bytes(), header.bytes());+ EXPECT_EQ(waiter->wake_count, 1u);+ EXPECT(waiter->outcome == Body::SniffOutcome::Complete);+ EXPECT_EQ(waiter->bytes.bytes(), header.bytes());BodyStreamHarness::run_wakes();EXPECT(harness.stream->is_errored());@@ -385,8 +392,8 @@ static void check_a_channel_ending_fails_the_sniff_once(size_t written_byte_counharness.create_stream({ .low = 2 * KiB, .high = 4 * KiB });auto& heap = harness.realm->heap();- SniffWaiter waiter;- harness.body->wait_for_sniff_bytes(waiter.callback(heap));+ auto waiter = make_ref_counted<SniffWaiter>();+ harness.body->wait_for_sniff_bytes(waiter->callback(heap));EXPECT_EQ(harness.channel->write(make_bytes(written_byte_count, 0)), FetchByteChannel::WriteResult::Accepted);if (transfer)(void)harness.channel->transfer_out();@@ -395,8 +402,8 @@ static void check_a_channel_ending_fails_the_sniff_once(size_t written_byte_counwait_for_wake(heap, waiter);run_wakes_and_tasks(heap);- EXPECT_EQ(waiter.wake_count, 1u);- EXPECT(waiter.outcome == Body::SniffOutcome::Failed);+ EXPECT_EQ(waiter->wake_count, 1u);+ EXPECT(waiter->outcome == Body::SniffOutcome::Failed);}TEST_CASE(a_cancelled_channel_fails_a_sniff_short_of_its_header)@@ -432,9 +439,9 @@ TEST_CASE(a_body_over_bytes_sniffs_at_once)EXPECT(sniff_bytes.has_value());EXPECT_EQ(sniff_bytes->bytes, bytes.bytes().trim(MAX_SNIFF_BYTES));- SniffWaiter waiter;- body->wait_for_sniff_bytes(waiter.callback(heap));- EXPECT_EQ(waiter.wake_count, 1u);+ auto waiter = make_ref_counted<SniffWaiter>();+ body->wait_for_sniff_bytes(waiter->callback(heap));+ EXPECT_EQ(waiter->wake_count, 1u);}namespace {@@ -485,20 +492,20 @@ TEST_CASE(network_completion_runs_only_the_steps_awaited_for_its_body)auto later = FetchByteChannel::create({ .low = 16, .high = 64 }, adopt_ref(*new IgnoringProducerSink));// A later body's steps replace an earlier body's, and run once.- IGNORE_USE_IN_ESCAPING_LAMBDA size_t earlier_runs = 0;- IGNORE_USE_IN_ESCAPING_LAMBDA size_t later_runs = 0;- controller->when_network_completes_body(*earlier, GC::create_function(heap, [&] { ++earlier_runs; }));- controller->when_network_completes_body(*later, GC::create_function(heap, [&] { ++later_runs; }));+ auto earlier_runs = make_ref_counted<SharedValue<size_t>>();+ auto later_runs = make_ref_counted<SharedValue<size_t>>();+ controller->when_network_completes_body(*earlier, GC::create_function(heap, GC::captures(earlier_runs), [](auto& earlier_runs) { ++earlier_runs->value; }));+ controller->when_network_completes_body(*later, GC::create_function(heap, GC::captures(later_runs), [](auto& later_runs) { ++later_runs->value; }));controller->did_complete_network_body(*earlier);- EXPECT_EQ(earlier_runs, 0u);- EXPECT_EQ(later_runs, 0u);+ EXPECT_EQ(earlier_runs->value, 0u);+ EXPECT_EQ(later_runs->value, 0u);controller->did_complete_network_body(*later);controller->did_complete_network_body(*later);- EXPECT_EQ(later_runs, 1u);+ EXPECT_EQ(later_runs->value, 1u);// A stopped fetch runs no awaited steps.- controller->when_network_completes_body(*earlier, GC::create_function(heap, [&] { ++earlier_runs; }));+ controller->when_network_completes_body(*earlier, GC::create_function(heap, GC::captures(earlier_runs), [](auto& earlier_runs) { ++earlier_runs->value; }));controller->stop_fetch();controller->did_complete_network_body(*earlier);- EXPECT_EQ(earlier_runs, 0u);+ EXPECT_EQ(earlier_runs->value, 0u);}diff --git a/Tests/LibWeb/TestWindowProxyWorld.cpp b/Tests/LibWeb/TestWindowProxyWorld.cppindex a85f4095fd3..7f0215af484 100644--- a/Tests/LibWeb/TestWindowProxyWorld.cpp+++ b/Tests/LibWeb/TestWindowProxyWorld.cpp@@ -4,7 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/RefCounted.h>#include <LibGC/CellAllocator.h>+#include <LibGC/Function.h>#include <LibJS/Runtime/NativeFunction.h>#include <LibJS/Runtime/Realm.h>#include <LibJS/Script.h>@@ -67,6 +69,10 @@ GC_DEFINE_ALLOCATOR(TestPageClient);}+struct ListenerCall : RefCounted<ListenerCall> {+ bool value { false };+};+TEST_CASE(per_world_windowproxy_and_window_wrapper){Web::Platform::FontPlugin font_plugin(false);@@ -125,7 +131,7 @@ TEST_CASE(per_world_windowproxy_and_window_wrapper)EXPECT(entries_after_extension_init.is_number());EXPECT_EQ(entries_after_extension_init.as_double(), 1);- IGNORE_USE_IN_ESCAPING_LAMBDA auto extension_proxy = browsing_context->window_proxy_for(*extension_world, extension_realm);+ auto extension_proxy = browsing_context->window_proxy_for(*extension_world, extension_realm);EXPECT(extension_proxy);EXPECT(extension_proxy != main_proxy);EXPECT(extension_proxy == browsing_context->window_proxy_for(*extension_world, extension_realm));@@ -154,11 +160,11 @@ TEST_CASE(per_world_windowproxy_and_window_wrapper)EXPECT(&value.as_object().shape().realm() == &extension_realm);}- IGNORE_USE_IN_ESCAPING_LAMBDA bool listener_was_called = false;+ auto listener_was_called = make_ref_counted<ListenerCall>();auto callback_function = JS::NativeFunction::create(extension_realm,- [&](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {- listener_was_called = true;+ GC::create_function(GC::Heap::the(), GC::captures(extension_proxy, extension_realm, listener_was_called), [](auto& extension_proxy, auto& extension_realm, auto& listener_was_called, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ listener_was_called->value = true;auto this_value = vm.this_value();EXPECT(this_value.is_object());@@ -179,7 +185,7 @@ TEST_CASE(per_world_windowproxy_and_window_wrapper)EXPECT(¤t_target.as_object().shape().realm() == &extension_realm);return JS::js_undefined();- },+ }),1);auto& principal_settings = Web::Bindings::principal_host_defined_environment_settings_object(window->principal_realm());auto callback = GC::Heap::the().allocate<Web::WebIDL::CallbackType>(*callback_function, principal_settings);@@ -187,7 +193,7 @@ TEST_CASE(per_world_windowproxy_and_window_wrapper)auto event = Web::DOM::Event::create(extension_realm.global_object(), "windowproxy-test"_fly_string);EXPECT(window->dispatch_event(*event));- EXPECT(listener_was_called);+ EXPECT(listener_was_called->value);auto* popped_extension_execution_context = vm.pop_execution_context();EXPECT(popped_extension_execution_context == extension_execution_context.ptr());diff --git a/Tests/LibWeb/TestWorldCallback.cpp b/Tests/LibWeb/TestWorldCallback.cppindex 6ed88c8a052..22fc2b7783f 100644--- a/Tests/LibWeb/TestWorldCallback.cpp+++ b/Tests/LibWeb/TestWorldCallback.cpp@@ -4,7 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/RefCounted.h>#include <LibGC/CellAllocator.h>+#include <LibGC/Function.h>#include <LibJS/Runtime/NativeFunction.h>#include <LibTest/TestCase.h>#include <LibWeb/Bindings/HostDefined.h>@@ -27,6 +29,10 @@ static void install_test_host_defined(JS::Realm& realm, Web::Bindings::WrapperWorealm.set_host_defined(realm.heap().allocate<Web::Bindings::HostDefined>(intrinsics, *wrapper_world, principal_realm));}+struct ListenerCall : RefCounted<ListenerCall> {+ bool value { false };+};+TEST_CASE(extension_world_callback_uses_principal_settings_object){auto principal_realm = Web::Bindings::create_a_principal_javascript_realm();@@ -36,7 +42,7 @@ TEST_CASE(extension_world_callback_uses_principal_settings_object)install_test_host_defined(extension_realm, Web::Bindings::WrapperWorld::Type::Extension, *principal_realm);vm.push_execution_context(*extension_execution_context);- auto callback_function = JS::NativeFunction::create(extension_realm, [](JS::VM&) { return JS::js_undefined(); }, 0);+ auto callback_function = JS::NativeFunction::create(extension_realm, [](JS::VM&) -> JS::ThrowCompletionOr<JS::Value> { return JS::js_undefined(); }, 0);auto& principal_settings = Web::Bindings::principal_host_defined_environment_settings_object(*principal_realm);auto callback = GC::Heap::the().allocate<Web::WebIDL::CallbackType>(*callback_function, extension_realm);EXPECT(callback->callback_context.ptr() == &principal_settings);@@ -59,10 +65,10 @@ TEST_CASE(extension_world_event_listener_wraps_arguments_in_listener_realm)install_test_host_defined(extension_realm, Web::Bindings::WrapperWorld::Type::Extension, *principal_realm);vm.push_execution_context(*extension_execution_context);- IGNORE_USE_IN_ESCAPING_LAMBDA auto event_target = Web::DOM::EventTarget::create();- IGNORE_USE_IN_ESCAPING_LAMBDA bool listener_was_called = false;- auto callback_function = JS::NativeFunction::create(extension_realm, [&](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {- listener_was_called = true;+ auto event_target = Web::DOM::EventTarget::create();+ auto listener_was_called = make_ref_counted<ListenerCall>();+ auto callback_function = JS::NativeFunction::create(extension_realm, GC::create_function(GC::Heap::the(), GC::captures(event_target, extension_realm, listener_was_called), [](auto& event_target, auto& extension_realm, auto& listener_was_called, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ listener_was_called->value = true;auto this_value = vm.this_value();EXPECT(this_value.is_object());@@ -79,7 +85,7 @@ TEST_CASE(extension_world_event_listener_wraps_arguments_in_listener_realm)EXPECT(¤t_target.as_object().shape().realm() == &extension_realm);EXPECT(Web::Bindings::impl_from<Web::DOM::EventTarget>(¤t_target.as_object()) == event_target.ptr());- return JS::js_undefined(); }, 1);+ return JS::js_undefined(); }), 1);auto& principal_settings = Web::Bindings::principal_host_defined_environment_settings_object(*principal_realm);auto callback = GC::Heap::the().allocate<Web::WebIDL::CallbackType>(*callback_function, extension_realm);EXPECT(callback->callback_context.ptr() == &principal_settings);@@ -88,7 +94,7 @@ TEST_CASE(extension_world_event_listener_wraps_arguments_in_listener_realm)auto event = Web::DOM::Event::create("world-callback-test"_fly_string, 0);EXPECT(event_target->dispatch_event(*event));- EXPECT(listener_was_called);+ EXPECT(listener_was_called->value);auto* popped_extension_execution_context = vm.pop_execution_context();EXPECT(popped_extension_execution_context == extension_execution_context.ptr());diff --git a/Tests/LibWeb/TestWrapperWorld.cpp b/Tests/LibWeb/TestWrapperWorld.cppindex b6a41ce624d..e5caf12438c 100644--- a/Tests/LibWeb/TestWrapperWorld.cpp+++ b/Tests/LibWeb/TestWrapperWorld.cpp@@ -5,8 +5,10 @@*/#include <AK/NonnullOwnPtr.h>+#include <AK/RefCounted.h>#include <LibCore/EventLoop.h>#include <LibGC/CellAllocator.h>+#include <LibGC/Function.h>#include <LibGC/Weak.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/ArrayBuffer.h>@@ -851,7 +853,7 @@ TEST_CASE(cross_origin_descriptor_cache_does_not_root_realm_after_wrapper_dies)auto& wrapper_world = Web::Bindings::host_defined_wrapper_world(realm.realm());auto window = Web::HTML::Window::create();auto wrapper = Web::Bindings::wrap(wrapper_world, realm.realm(), window);- auto accessor = JS::NativeFunction::create(realm.realm(), [](JS::VM&) { return JS::js_undefined(); }, 0);+ auto accessor = JS::NativeFunction::create(realm.realm(), [](JS::VM&) -> JS::ThrowCompletionOr<JS::Value> { return JS::js_undefined(); }, 0);auto key = Web::HTML::CrossOriginKey {.current_settings_object = 1,.relevant_settings_object = 2,@@ -872,17 +874,21 @@ TEST_CASE(cross_origin_descriptor_cache_does_not_root_realm_after_wrapper_dies)EXPECT(!weak_realm);}+struct TimerFired : RefCounted<TimerFired> {+ bool value { false };+};+// An active timer lives only as long as its owner reaches it. One that nothing reaches is collected, and must be// stopped then rather than fire into a callback that was collected with it.TEST_CASE(unreachable_active_timer_is_stopped_when_collected){IGNORE_USE_IN_ESCAPING_LAMBDA Core::EventLoop event_loop;auto vm = JS::VM::create();- IGNORE_USE_IN_ESCAPING_LAMBDA bool fired = false;+ auto fired = make_ref_counted<TimerFired>();GC::Weak<Web::Platform::Timer> weak_timer;[&] {- auto timer = Web::Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(0), GC::create_function(GC::Heap::the(), [&] {- fired = true;+ auto timer = Web::Platform::Timer::create_single_shot(GC::Heap::the(), AK::Duration::from_milliseconds(0), GC::create_function(GC::Heap::the(), GC::captures(fired), [](auto& fired) {+ fired->value = true;}));timer->start();weak_timer = *timer;@@ -897,7 +903,7 @@ TEST_CASE(unreachable_active_timer_is_stopped_when_collected)quit_timer->start();event_loop.exec();- EXPECT(!fired);+ EXPECT(!fired->value);}TEST_CASE(extension_world_hash_cache_scales)diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cppindex dab40b786f0..8c50835db64 100644--- a/Utilities/wasm.cpp+++ b/Utilities/wasm.cpp@@ -11,6 +11,7 @@#include <AK/JsonArray.h>#include <AK/JsonObject.h>#include <AK/LexicalPath.h>+#include <AK/RefCounted.h>#include <AK/ScopeGuard.h>#include <AK/UFixedBigInt.h>#include <AK/Utf16String.h>@@ -21,6 +22,7 @@#include <LibCore/MappedFile.h>#include <LibCrypto/BigInt/SignedBigInteger.h>#include <LibFileSystem/FileSystem.h>+#include <LibGC/Function.h>#include <LibGC/Root.h>#include <LibJS/Runtime/AbstractOperations.h>#include <LibJS/Runtime/BigInt.h>@@ -41,6 +43,18 @@ using Wasm::Runtime::ValueKind;using Wasm::Runtime::ValueType;using WasmValue = Wasm::Runtime::Value;+// What a host function's "invoke" calls back into. NB: Both live in main() for as long as the utility runs.+struct ReentryTarget : RefCounted<ReentryTarget> {+ ReentryTarget(Wasm::Runtime::Store& store, Entity& main_instance)+ : store(store)+ , main_instance(main_instance)+ {+ }++ Wasm::Runtime::Store& store;+ Entity& main_instance;+};+struct BenchmarkTimings {JsonArray parse;JsonArray validation;@@ -415,8 +429,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)// The function's `this` can call back into the main instance's exports.auto reentry_this = JS::Object::create(realm, realm.intrinsics().object_prototype());+ auto reentry = make_ref_counted<ReentryTarget>(store, main_instance);auto invoke = JS::NativeFunction::create(- realm, [&store, &main_instance](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ realm, GC::create_function(vm->heap(), GC::captures(reentry), [](NonnullRefPtr<ReentryTarget>& reentry, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ auto& store = reentry->store;+ auto& main_instance = reentry->main_instance;if (!main_instance)return vm.throw_completion<JS::TypeError>("wasm reentry: instance not ready yet"_utf16);auto export_name = TRY(vm.argument(0).to_utf16_string(vm)).to_byte_string();@@ -464,7 +481,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)default:return JS::js_undefined();}- },+ }),1, "invoke"_utf16);reentry_this->define_direct_property("invoke"_utf16, invoke, JS::default_attributes);