Truly independent web browser
LibGC: Clear weak pointers to dead cells before running finalizers
Shannon Booth9ef68ea2669a
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 687e2efcacb..dfdd658e227 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -663,16 +663,21 @@ AK::JsonObject Heap::build_graph(ReadonlySpan<FlatPtr> callee_saved_registers)return graph;}+// This must run before any finalizer, so that no finalizer can reach a dead cell through a weak pointer. Finalizers run+// in no particular order, so such a cell may already have been finalized, and it may belong to another heap.+void Heap::clear_weak_pointers_to_dead_cells(bool report)+{+ ScopedPhaseTimer timer { report, g_phase_timings.sweep_weak_blocks_us };+ sweep_weak_blocks();+ m_weak_pointers_to_dead_cells_are_cleared = true;+}+void Heap::run_post_mark_phases(bool report){{ScopedPhaseTimer timer { report, g_phase_timings.finalize_unmarked_cells_us };finalize_unmarked_cells();}- {- ScopedPhaseTimer timer { report, g_phase_timings.sweep_weak_blocks_us };- sweep_weak_blocks();- }// Prune weak containers while we're still stop-the-world; doing this// during incremental sweep risks reading cells that have already been@@ -770,7 +775,9 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collectimark_live_cells(roots);}}+ clear_weak_pointers_to_dead_cells(report);run_post_mark_phases(report);+ m_weak_pointers_to_dead_cells_are_cleared = false;// For CollectEverything we must finish sweeping synchronously so that// every cell is collected before the Heap destructor returns. All@@ -1674,6 +1681,11 @@ void Heap::uproot_cell(Cell* cell)WeakImpl* Heap::create_weak_impl(void* ptr){+ // Once weak pointers to dead cells have been cleared, one that is created to a dead cell, e.g. by a finalizer of+ // this or another heap, must be null as well, or nothing would clear it before the cell is swept.+ if (m_weak_pointers_to_dead_cells_are_cleared && !static_cast<Cell*>(ptr)->is_marked())+ return &WeakImpl::the_null_weak_impl;+if (m_usable_weak_blocks.is_empty()) {// NOTE: These are leaked on Heap destruction, but that's fine since Heap is tied to process lifetime.auto* weak_block = WeakBlock::create();diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex d46a16454eb..bcb54d74443 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -244,6 +244,7 @@ private:void gather_roots(ConservativeScanOrigin const&, HashMap<Cell*, HeapRoot>&, Vector<StackFrameInfo>* out_stack_frames = nullptr, IncludeIncomingCrossHeapMembers = IncludeIncomingCrossHeapMembers::Yes);static void mark_live_cells_across(ReadonlySpan<Heap* const>, HashMap<Cell*, HeapRoot>& roots);+ void clear_weak_pointers_to_dead_cells(bool report);void run_post_mark_phases(bool report);void gather_conservative_roots(ConservativeScanOrigin const&, HashMap<Cell*, HeapRoot>&, Vector<StackFrameInfo>* out_stack_frames = nullptr);void gather_asan_fake_stack_roots(HashMap<FlatPtr, HeapRoot>&, FlatPtr, FlatPtr heap_region_start, FlatPtr heap_region_end, FlatPtr stack_reference, FlatPtr stack_top);@@ -315,6 +316,7 @@ private:bool m_should_gc_when_deferral_ends { false };bool m_collecting_garbage { false };+ bool m_weak_pointers_to_dead_cells_are_cleared { false };CollectionType m_current_collection_type { CollectionType::CollectGarbage };StackInfo m_stack_info;AK::Function<void(HashMap<Cell*, GC::HeapRoot>&)> m_gather_embedder_roots;diff --git a/Libraries/LibGC/HeapGroup.cpp b/Libraries/LibGC/HeapGroup.cppindex a287eb515c6..e5ef3475b32 100644--- a/Libraries/LibGC/HeapGroup.cpp+++ b/Libraries/LibGC/HeapGroup.cpp@@ -74,8 +74,13 @@ void HeapGroup::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, booHeap::mark_live_cells_across(m_heaps, roots);+ // Weak pointers may point across heaps, so clear them in every heap before any heap runs its finalizers.+ for (auto* heap : m_heaps)+ heap->clear_weak_pointers_to_dead_cells(print_report);for (auto* heap : m_heaps)heap->run_post_mark_phases(print_report);+ for (auto* heap : m_heaps)+ heap->m_weak_pointers_to_dead_cells_are_cleared = false;for (auto* heap : m_heaps) {Core::ElapsedTimer measurement_timer { Core::TimerType::Precise };diff --git a/Tests/LibGC/TestGCContainers.cpp b/Tests/LibGC/TestGCContainers.cppindex f12d265c2b1..12b77b22914 100644--- a/Tests/LibGC/TestGCContainers.cpp+++ b/Tests/LibGC/TestGCContainers.cpp@@ -32,6 +32,26 @@ class TestCell : public GC::Cell {GC_DEFINE_ALLOCATOR(TestCell);+class FinalizerObservingCell : public GC::Cell {+ GC_CELL(FinalizerObservingCell, GC::Cell);+ GC_DECLARE_ALLOCATOR(FinalizerObservingCell);++public:+ GC::Weak<TestCell> weak_cell;+ bool* weak_cell_was_null_while_finalizing { nullptr };+ bool* weak_to_self_was_null_while_finalizing { nullptr };++private:+ virtual void finalize() override+ {+ Base::finalize();+ *weak_cell_was_null_while_finalizing = !weak_cell;+ *weak_to_self_was_null_while_finalizing = !GC::Weak<FinalizerObservingCell> { *this };+ }+};++GC_DEFINE_ALLOCATOR(FinalizerObservingCell);+static GC::Heap& test_heap(){static AK::NeverDestroyed<GC::Heap> heap([](auto&) { });@@ -606,3 +626,23 @@ TEST_CASE(removed_conservative_hash_table_entry_not_reported)EXPECT(!possible_values_contain(table, cell.ptr()));}++TEST_CASE(weak_pointers_to_dead_cells_are_null_while_finalizing)+{+ auto& heap = test_heap();+ bool weak_cell_was_null_while_finalizing = false;+ bool weak_to_self_was_null_while_finalizing = false;++ {+ auto cell = heap.allocate<TestCell>();+ auto observer = heap.allocate<FinalizerObservingCell>();+ observer->weak_cell = cell.ptr();+ observer->weak_cell_was_null_while_finalizing = &weak_cell_was_null_while_finalizing;+ observer->weak_to_self_was_null_while_finalizing = &weak_to_self_was_null_while_finalizing;+ }++ scrub_stack();+ heap.collect_garbage(GC::Heap::CollectionType::CollectEverything);+ EXPECT(weak_cell_was_null_while_finalizing);+ EXPECT(weak_to_self_was_null_while_finalizing);+}diff --git a/Tests/LibGC/TestGCHeapGroup.cpp b/Tests/LibGC/TestGCHeapGroup.cppindex b3faae26c6c..a760ac5a16e 100644--- a/Tests/LibGC/TestGCHeapGroup.cpp+++ b/Tests/LibGC/TestGCHeapGroup.cpp@@ -11,6 +11,7 @@#include <LibGC/HeapGroup.h>#include <LibGC/Ptr.h>#include <LibGC/Root.h>+#include <LibGC/WeakInlines.h>#include <LibTest/TestCase.h>namespace {@@ -43,6 +44,28 @@ private:GC_DEFINE_ALLOCATOR(LinkedCell);+Optional<bool> s_weak_to_dead_foreign_cell_was_null_while_finalizing;++class WeakCreatingCell final : public GC::Cell {+ GC_CELL(WeakCreatingCell, GC::Cell);+ GC_DECLARE_ALLOCATOR(WeakCreatingCell);++public:+ // Not visited, so that the foreign cell dies whether or not we do.+ GC::RawPtr<LinkedCell> foreign_cell;++private:+ WeakCreatingCell() = default;++ virtual void finalize() override+ {+ Base::finalize();+ s_weak_to_dead_foreign_cell_was_null_while_finalizing = !GC::Weak<LinkedCell> { foreign_cell.ptr() };+ }+};++GC_DEFINE_ALLOCATOR(WeakCreatingCell);+// Under ASan, an instrumented function's locals live on a fake stack, so filling them would leave the real stack as it// was — and the conservative scan reads the real stack. So this function isn't instrumented.NO_SANITIZE_ADDRESS NEVER_INLINE void scrub_stack()@@ -79,6 +102,12 @@ NEVER_INLINE GC::Root<LinkedCell> allocate_cross_heap_chain(GC::Heap& heap_a, GCreturn holder;}+NEVER_INLINE void allocate_weak_creating_cell_and_foreign_garbage(GC::Heap& heap_a, GC::Heap& heap_b)+{+ auto cell = heap_a.allocate<WeakCreatingCell>();+ cell->foreign_cell = heap_b.allocate<LinkedCell>().ptr();+}+NEVER_INLINE void allocate_garbage(GC::Heap& heap){(void)heap.allocate<LinkedCell>();@@ -189,6 +218,30 @@ static NEVER_INLINE void group_collection_traces_live_cross_heap_chains()group.remove(heap_b);}+static NEVER_INLINE void group_collection_finalizer_creates_null_weak_to_dead_foreign_cell()+{+ GC::Heap heap_a([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ GC::Heap heap_b([](auto&) { }, GC::Heap::BecomeProcessDefault::No);++ heap_a.set_incremental_sweep_enabled(false);+ heap_b.set_incremental_sweep_enabled(false);+ GC::HeapGroup group;+ group.add(heap_a);+ group.add(heap_b);++ // The finalizer runs while heap B's weak pointers have already been cleared, whether or not B has run its own+ // finalizers yet, so a weak pointer that it creates to B's dead cell must be null.+ s_weak_to_dead_foreign_cell_was_null_while_finalizing = {};+ allocate_weak_creating_cell_and_foreign_garbage(heap_a, heap_b);+ scrub_stack();+ group.collect_garbage();+ EXPECT_EQ(s_weak_to_dead_foreign_cell_was_null_while_finalizing, true);+ EXPECT_EQ(s_live_linked_cells, 0u);++ group.remove(heap_a);+ group.remove(heap_b);+}+// Under ASan with detect_stack_use_after_return, a function's locals live on a fake stack, but its frame on the real// stack still reserves room for them — room it never writes, so it keeps whatever earlier calls left there, and the// conservative scan reads it. A stale pointer there can keep a dropped cell alive. So each case runs in a frame of its@@ -216,3 +269,9 @@ TEST_CASE(group_collection_traces_live_cross_heap_chains)scrub_stack();group_collection_traces_live_cross_heap_chains();}++TEST_CASE(group_collection_finalizer_creates_null_weak_to_dead_foreign_cell)+{+ scrub_stack();+ group_collection_finalizer_creates_null_weak_to_dead_foreign_cell();+}diff --git a/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.html b/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.htmlnew file mode 100644index 00000000000..d02697ef9f2--- /dev/null+++ b/Tests/LibWeb/Crash/SVG/use-element-fetch-in-collected-document.html@@ -0,0 +1,14 @@+<!DOCTYPE html>+<!-- An external <use> reference in a document without a browsing context starts a fetch that delays the document's+ load event. Nothing stops that fetch, so the document and its in-flight resource request become garbage together,+ and the request must not release its load event delayer against the dying document while it is being finalized. -->+<script>+ function startFetchInUnreachableDocument() {+ const doc = document.implementation.createHTMLDocument();+ const use = doc.createElementNS("http://www.w3.org/2000/svg", "use");+ use.setAttribute("href", new URL("../../Assets/120.png#target", document.baseURI).href);+ }++ startFetchInUnreachableDocument();+ internals.gc();+</script>