Truly independent web browser
LibGC+LibCore+LibWeb+WebContent: Collect without the stack in gcAsync()
Andreas Kling70f439ef91d5
diff --git a/Libraries/LibCore/ThreadEventQueue.cpp b/Libraries/LibCore/ThreadEventQueue.cppindex f6e85a60b86..6e2ef80fb7c 100644--- a/Libraries/LibCore/ThreadEventQueue.cpp+++ b/Libraries/LibCore/ThreadEventQueue.cpp@@ -7,6 +7,7 @@#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/Once.h>+#include <AK/ScopeGuard.h>#include <AK/Vector.h>#include <LibCore/EventLoopImplementation.h>#include <LibCore/EventReceiver.h>@@ -48,6 +49,8 @@ struct ThreadEventQueue::Private {Mutex mutex;Vector<QueuedEvent> queued_events;+ // Only the queue's own thread reads and writes this.+ size_t processing_depth { 0 };};static pthread_key_t s_current_thread_event_queue_key;@@ -131,6 +134,9 @@ size_t ThreadEventQueue::process()events = move(m_private->queued_events);}+ ++m_private->processing_depth;+ ScopeGuard leave = [this] { --m_private->processing_depth; };+for (auto& queued_event : events) {if (auto receiver = queued_event.receiver.strong_ref()) {switch (queued_event.event_type) {@@ -159,6 +165,11 @@ size_t ThreadEventQueue::process()return events.size();}+bool ThreadEventQueue::is_processing_nested() const+{+ return m_private->processing_depth > 1;+}+bool ThreadEventQueue::has_pending_events() const{MutexLocker locker(m_private->mutex);diff --git a/Libraries/LibCore/ThreadEventQueue.h b/Libraries/LibCore/ThreadEventQueue.hindex 1e226e18551..2e80148fd93 100644--- a/Libraries/LibCore/ThreadEventQueue.h+++ b/Libraries/LibCore/ThreadEventQueue.h@@ -48,6 +48,10 @@ public:// Returns true if there are events waiting to be flushed.bool has_pending_events() const;+ // Returns true while process() runs inside an event that an outer process() dispatched, as it does when that event+ // spins a nested event loop.+ bool is_processing_nested() const;+private:ThreadEventQueue();~ThreadEventQueue();diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 8dd25e0b1dd..36bf0fc054c 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -908,11 +908,19 @@ NO_SANITIZE_ADDRESS void Heap::collect_garbage(CollectionType collection_type, brun_collection(captured_registers, collection_type, print_report);}-void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, CollectionType collection_type, bool print_report)+void Heap::collect_garbage_without_scanning_the_stack()+{+ VERIFY(!heap_access_is_forbidden_on_this_thread());+ VERIFY(is_on_owner_thread());+ run_collection({}, CollectionType::CollectGarbage, false, false);+}++void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, CollectionType collection_type, bool print_report, bool scan_stack){ConservativeScanOrigin origin {.stack_floor = bit_cast<FlatPtr>(__builtin_frame_address(0)),.callee_saved_registers = callee_saved_registers,+ .scan_stack = scan_stack,};VERIFY(!m_collecting_garbage);@@ -1257,7 +1265,7 @@ void Heap::gather_roots(ConservativeScanOrigin const& origin, HashMap<Cell*, HeaScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.gather_embedder_roots_us };m_gather_embedder_roots(roots);}- {+ if (origin.scan_stack) {ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.gather_conservative_roots_us };gather_conservative_roots(origin, roots, out_stack_frames);}diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex eec4d4474e2..b36bc947f09 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -85,6 +85,11 @@ public:// they are in the frame it runs in, and the frames below become the scan's floor. The definitions are// NO_SANITIZE_ADDRESS so that the capture buffer stays on the real stack rather than ASan's fake one.NEVER_INLINE void collect_garbage(CollectionType = CollectionType::CollectGarbage, bool print_report = false);++ // Collects without taking any root from the stack or the registers, so no stale or lookalike word there keeps a+ // cell alive. Only safe where every cell the stack refers to is rooted some other way, as in the outermost turn of+ // the event loop.+ void collect_garbage_without_scanning_the_stack();NEVER_INLINE AK::JsonObject dump_graph();// A cell on a retaining path, which reaches the next one through a field it visits. The cell is live until the next@@ -281,12 +286,13 @@ private:struct ConservativeScanOrigin {FlatPtr stack_floor { 0 };ReadonlySpan<FlatPtr> callee_saved_registers;+ bool scan_stack { true };};// NB: NEVER_INLINE so that these stay below their entry point's frame, and so that __builtin_frame_address(0)// yields a floor that leaves out their own frames -- which is what keeps the collection's large locals from// being scanned.- NEVER_INLINE void run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, CollectionType, bool print_report);+ NEVER_INLINE void run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, CollectionType, bool print_report, bool scan_stack = true);NEVER_INLINE AK::JsonObject build_graph(ReadonlySpan<FlatPtr> callee_saved_registers);NEVER_INLINE Vector<RetainingPath> build_retaining_paths(ReadonlySpan<FlatPtr> callee_saved_registers, AK::Function<bool(Cell&)> const& is_target, size_t max_paths);diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex eb5bf0360d7..aba48e63474 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -16,6 +16,7 @@#include <LibCompositing/DisplayList/DisplayListResources.h>#include <LibCore/EventLoop.h>#include <LibCore/System.h>+#include <LibCore/ThreadEventQueue.h>#include <LibCore/TimeZone.h>#include <LibGC/Heap.h>#include <LibGC/RootVector.h>@@ -401,14 +402,28 @@ u32 Internals::worker_agent_count() constreturn Bindings::worker_agent_count();}+static void collect_garbage_from_the_outermost_event_loop_turn(GC::Root<WebIDL::Promise>);+void Internals::gc_async(GC::Ref<WebIDL::Promise> promise){- // Queue a LibCore event to run the collection, so that it runs outside the JS execution context with as small a- // stack as possible.- Core::deferred_invoke([promise = GC::make_root(promise)] {+ collect_garbage_from_the_outermost_event_loop_turn(GC::make_root(promise));+}++static void collect_garbage_from_the_outermost_event_loop_turn(GC::Root<WebIDL::Promise> promise)+{+ // Queue a LibCore event to run the collection, so that it runs outside the JS execution context. Nothing on the stack+ // of the outermost event loop turn refers to a cell that is not rooted some other way, so the collection leaves the+ // stack out. A word there that only looks like a cell pointer would otherwise keep that cell alive, and one in a+ // frame of the event loop itself would keep it alive for every later collection too.+ Core::deferred_invoke([promise = move(promise)]() mutable {+ // A nested event loop has script waiting further up the stack, so wait for it to finish.+ if (Core::ThreadEventQueue::current().is_processing_nested()) {+ collect_garbage_from_the_outermost_event_loop_turn(move(promise));+ return;+ }auto& realm = WebIDL::promise_realm(*promise);HTML::TemporaryExecutionContext execution_context { realm };- realm.vm().heap().collect_garbage();+ realm.vm().heap().collect_garbage_without_scanning_the_stack();WebIDL::resolve_promise(*promise);});}diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex ae131af5340..2fcca8741b5 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -163,14 +163,18 @@ static void install_crash_signal_handlers()static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site);-ErrorOr<int> ladybird_main(Main::Arguments arguments)+// What the process keeps for as long as its event loop runs.+struct ProcessState {+ NonnullRefPtr<WebContent::ConnectionFromClient> client;+ OwnPtr<Core::StatsLog> stats_log;+};++// NB: NEVER_INLINE so that the locals of the setup are gone from the stack before the event loop runs. ladybird_main()+// stays on the stack for the life of the process, below every collection. A collection from the outermost turn of+// the event loop takes no roots from the stack, so no frame that is still on the stack then may hold the only+// reference to a cell. Keep ladybird_main() down to what has to outlive the event loop, and never a cell.+NEVER_INLINE static ErrorOr<ProcessState> initialize_process(Main::Arguments arguments){- AK::set_rich_debug_enabled(true);-- install_crash_signal_handlers();-- auto& event_loop = Core::EventLoop::initialize_for_current_thread();-WebView::platform_init();Web::Platform::EventLoopPlugin::install(*new Web::Platform::EventLoopPlugin);@@ -330,6 +334,17 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)});}+ return ProcessState { move(webcontent_client), move(stats_log) };+}++ErrorOr<int> ladybird_main(Main::Arguments arguments)+{+ AK::set_rich_debug_enabled(true);++ install_crash_signal_handlers();++ auto& event_loop = Core::EventLoop::initialize_for_current_thread();+ auto process_state = TRY(initialize_process(arguments));return event_loop.exec();}