Skip to content

Truly independent web browser

LibGC: Don’t collect when a deferral ends during a block sweep

sideshowbarkerd8f230741689
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index 2dbe02dbf18..313c6a20434 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -2027,11 +2027,17 @@ void Heap::undefer_gc()
VERIFY(m_gc_deferrals > 0);
--m_gc_deferrals;
- if (!m_gc_deferrals) {
- if (m_should_gc_when_deferral_ends)
- collect_garbage();
- m_should_gc_when_deferral_ends = false;
- }
+ if (m_gc_deferrals || !m_should_gc_when_deferral_ends)
+ return;
+
+ // NB: A destructor that a block sweep runs can end a deferral of its own, e.g. the one around constructing a cell
+ // it allocates. For the reason will_allocate() gives, no collection may start there, so the request waits for
+ // a deferral that ends outside the sweep.
+ if (m_block_sweeps_in_progress > 0)
+ return;
+
+ collect_garbage();
+ m_should_gc_when_deferral_ends = false;
}
void Heap::uproot_cell(Cell* cell)
diff --git a/Tests/LibGC/TestGCIncrementalSweep.cpp b/Tests/LibGC/TestGCIncrementalSweep.cpp
index f7a2cf619f2..27f6641c086 100644
--- a/Tests/LibGC/TestGCIncrementalSweep.cpp
+++ b/Tests/LibGC/TestGCIncrementalSweep.cpp
@@ -113,6 +113,36 @@ TEST_CASE(allocating_from_a_destructor_during_a_sweep_does_not_free_reachable_ce
EXPECT(!s_reachable_cell_was_destroyed);
}
+TEST_CASE(ending_a_deferral_from_a_destructor_during_a_sweep_does_not_start_a_collection)
+{
+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);
+ heap.enable_stats();
+ s_cell_that_allocates_when_destroyed_was_destroyed = false;
+ s_reachable_cell_was_destroyed = false;
+
+ auto reachable_cell = allocate_unreachable_then_reachable_cell(heap);
+ GC::scrub_stack_for_testing();
+
+ // This collection marks the reachable cell and leaves the destruction of the other one to the incremental sweep.
+ heap.collect_garbage();
+ EXPECT(heap.is_incremental_sweep_active());
+ EXPECT(!s_cell_that_allocates_when_destroyed_was_destroyed);
+
+ // A collection requested under a deferral runs once the deferral ends, and finishes that sweep first. That destroys
+ // the unreachable cell, and its allocation ends the deferral that the construction of the new cell starts.
+ {
+ GC::DeferGC defer_gc { heap };
+ heap.collect_garbage();
+ }
+
+ EXPECT(s_cell_that_allocates_when_destroyed_was_destroyed);
+ EXPECT(!s_reachable_cell_was_destroyed);
+
+ AK::JsonObject stats;
+ heap.add_stats(stats);
+ EXPECT_EQ(stats.get_u64("gc.collections"sv), 2u);
+}
+
TEST_CASE(free_cells_that_a_destructor_takes_while_a_collection_finishes_the_sweep_go_back_to_their_block)
{
GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);