Skip to content

Truly independent web browser

LibGC: Check that heaps are used on their own thread

Andreas Klingbde963a638cf
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index 47a1cf50e2c..4cb3714173f 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -334,6 +334,7 @@ Heap::Heap(AK::Function<void(HashMap<Cell*, GC::HeapRoot>&)> gather_embedder_roo
Heap::~Heap()
{
+ VERIFY(is_on_owner_thread());
collect_garbage(CollectionType::CollectEverything);
free_weak_blocks();
@@ -415,6 +416,7 @@ void Heap::finish_stats_collection()
void Heap::will_allocate(size_t size, TriggersCollection triggers_collection)
{
ASSERT(!heap_access_is_forbidden_on_this_thread());
+ ASSERT(is_on_owner_thread());
if (triggers_collection == TriggersCollection::No) {
m_total_allocated_bytes += size;
return;
@@ -949,6 +951,7 @@ bool heap_access_is_forbidden_on_this_thread()
NO_SANITIZE_ADDRESS void Heap::collect_garbage(CollectionType collection_type, bool print_report)
{
VERIFY(!heap_access_is_forbidden_on_this_thread());
+ VERIFY(is_on_owner_thread());
jmp_buf registers;
setjmp(registers);
ReadonlySpan<FlatPtr> captured_registers { reinterpret_cast<FlatPtr const*>(registers), sizeof(jmp_buf) / (sizeof(FlatPtr)) };
diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.h
index 50093dd2324..724c00bf06d 100644
--- a/Libraries/LibGC/Heap.h
+++ b/Libraries/LibGC/Heap.h
@@ -35,6 +35,7 @@
#include <LibGC/RootVector.h>
#include <LibGC/WeakBlock.h>
#include <LibGC/WeakContainer.h>
+#include <pthread.h>
namespace GC {
@@ -60,6 +61,7 @@ public:
explicit Heap(AK::Function<void(HashMap<Cell*, GC::HeapRoot>&)> gather_embedder_roots, BecomeThreadDefault = BecomeThreadDefault::Yes);
~Heap();
+ // The default heap of the calling thread.
static Heap& the();
static void set_default_heap_for_testing(Heap&);
@@ -108,6 +110,11 @@ public:
NEVER_INLINE Vector<RetainingPath> find_retaining_paths(AK::Function<bool(Cell&)> const& is_target, size_t max_paths);
static String describe_root(HeapRoot const&);
+ // A heap belongs to the thread that created it: the collector only scans that thread's stack, and nothing in the heap
+ // is synchronized. That thread has to destroy it as well. Collections and destruction verify this, allocation and
+ // rooting are debug assertions.
+ bool is_on_owner_thread() const { return pthread_equal(m_owner_thread, pthread_self()); }
+
bool should_collect_on_every_allocation() const { return m_should_collect_on_every_allocation; }
// This is true for any CollectEverything cycle, not only heap teardown.
bool is_collecting_everything() const { return m_collecting_garbage && m_current_collection_type == CollectionType::CollectEverything; }
@@ -328,6 +335,8 @@ private:
};
OwnPtr<Stats> m_stats;
+ pthread_t m_owner_thread { pthread_self() };
+
size_t m_gc_bytes_threshold { 0 };
size_t m_allocated_bytes_since_last_gc { 0 };
diff --git a/Libraries/LibGC/Root.cpp b/Libraries/LibGC/Root.cpp
index 623ec9a8fad..a7713350b5e 100644
--- a/Libraries/LibGC/Root.cpp
+++ b/Libraries/LibGC/Root.cpp
@@ -16,12 +16,14 @@ RootImpl::RootImpl(Cell* cell, SourceLocation location)
, m_location(location)
{
ASSERT(!heap_access_is_forbidden_on_this_thread());
+ ASSERT(m_cell->heap().is_on_owner_thread());
m_cell->heap().did_create_root({}, *this);
}
RootImpl::~RootImpl()
{
ASSERT(!heap_access_is_forbidden_on_this_thread());
+ ASSERT(m_cell->heap().is_on_owner_thread());
m_cell->heap().did_destroy_root({}, *this);
}
diff --git a/Libraries/LibGC/RootHashMap.cpp b/Libraries/LibGC/RootHashMap.cpp
index dc478443002..68835ffa4ff 100644
--- a/Libraries/LibGC/RootHashMap.cpp
+++ b/Libraries/LibGC/RootHashMap.cpp
@@ -17,11 +17,13 @@ RootHashMapBase::RootHashMapBase()
RootHashMapBase::RootHashMapBase(Heap& heap)
: m_heap(&heap)
{
+ ASSERT(m_heap->is_on_owner_thread());
m_heap->did_create_root_hash_map({}, *this);
}
RootHashMapBase::~RootHashMapBase()
{
+ ASSERT(m_heap->is_on_owner_thread());
m_heap->did_destroy_root_hash_map({}, *this);
}
diff --git a/Libraries/LibGC/RootHashTable.cpp b/Libraries/LibGC/RootHashTable.cpp
index 6e6d6a44751..643a47568d1 100644
--- a/Libraries/LibGC/RootHashTable.cpp
+++ b/Libraries/LibGC/RootHashTable.cpp
@@ -18,11 +18,13 @@ RootHashTableBase::RootHashTableBase()
RootHashTableBase::RootHashTableBase(Heap& heap)
: m_heap(&heap)
{
+ ASSERT(m_heap->is_on_owner_thread());
m_heap->did_create_root_hash_table({}, *this);
}
RootHashTableBase::~RootHashTableBase()
{
+ ASSERT(m_heap->is_on_owner_thread());
m_heap->did_destroy_root_hash_table({}, *this);
}
diff --git a/Libraries/LibGC/RootVector.cpp b/Libraries/LibGC/RootVector.cpp
index a16bb1e215e..38e35b6c3ad 100644
--- a/Libraries/LibGC/RootVector.cpp
+++ b/Libraries/LibGC/RootVector.cpp
@@ -20,12 +20,14 @@ RootVectorBase::RootVectorBase(Heap& heap)
: m_heap(&heap)
{
ASSERT(!heap_access_is_forbidden_on_this_thread());
+ ASSERT(m_heap->is_on_owner_thread());
m_heap->did_create_root_vector({}, *this);
}
RootVectorBase::~RootVectorBase()
{
ASSERT(!heap_access_is_forbidden_on_this_thread());
+ ASSERT(m_heap->is_on_owner_thread());
m_heap->did_destroy_root_vector({}, *this);
}
diff --git a/Tests/LibGC/CMakeLists.txt b/Tests/LibGC/CMakeLists.txt
index 4a431564906..0d1906527d9 100644
--- a/Tests/LibGC/CMakeLists.txt
+++ b/Tests/LibGC/CMakeLists.txt
@@ -10,6 +10,7 @@ set(TEST_SOURCES
TestGCHeapGroup.cpp
TestGCIdleCollection.cpp
TestGCIncrementalSweep.cpp
+ TestGCThreads.cpp
TestGCVisitor.cpp
TestMember.cpp
TestNanBoxedValue.cpp
@@ -17,4 +18,4 @@ set(TEST_SOURCES
)
target_sources(TestLibGC PRIVATE ${TEST_SOURCES})
-target_link_libraries(TestLibGC PRIVATE LibGC)
+target_link_libraries(TestLibGC PRIVATE LibGC LibThreading)
diff --git a/Tests/LibGC/TestGCThreads.cpp b/Tests/LibGC/TestGCThreads.cpp
new file mode 100644
index 00000000000..de5ec3ad967
--- /dev/null
+++ b/Tests/LibGC/TestGCThreads.cpp
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AssertionFailure.h>
+#include <AK/Atomic.h>
+#include <AK/Vector.h>
+#include <LibGC/BlockAllocator.h>
+#include <LibGC/Cell.h>
+#include <LibGC/CellAllocator.h>
+#include <LibGC/Heap.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/Root.h>
+#include <LibGC/Testing.h>
+#include <LibGC/Weak.h>
+#include <LibGC/WeakInlines.h>
+#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+
+#if !defined(AK_OS_WINDOWS)
+# include <sys/wait.h>
+# include <unistd.h>
+#endif
+
+namespace {
+
+Atomic<size_t> s_live_cells { 0 };
+
+class ThreadTestCell final : public GC::Cell {
+ GC_CELL(ThreadTestCell, GC::Cell);
+ GC_DECLARE_ALLOCATOR(ThreadTestCell);
+
+public:
+ virtual ~ThreadTestCell() override { s_live_cells.fetch_sub(1); }
+
+ GC::Ptr<ThreadTestCell>& next() { return m_next; }
+
+private:
+ ThreadTestCell() { s_live_cells.fetch_add(1); }
+
+ virtual void visit_edges(Visitor& visitor) override
+ {
+ Base::visit_edges(visitor);
+ visitor.visit(m_next);
+ }
+
+ GC::Ptr<ThreadTestCell> m_next;
+};
+
+GC_DEFINE_ALLOCATOR(ThreadTestCell);
+
+template<typename Callback>
+void run_on_threads(size_t thread_count, IGNORE_USE_IN_ESCAPING_LAMBDA Callback callback)
+{
+ Vector<NonnullRefPtr<Threading::Thread>> threads;
+ for (size_t i = 0; i < thread_count; ++i) {
+ auto thread = Threading::Thread::construct("GCThreadTest"sv, [&callback] {
+ callback();
+ return static_cast<intptr_t>(0);
+ });
+ thread->start();
+ threads.append(move(thread));
+ }
+ for (auto& thread : threads)
+ MUST(thread->join());
+}
+
+void churn_cells()
+{
+ GC::Heap heap([](auto&) { });
+ heap.set_incremental_sweep_enabled(false);
+ EXPECT_EQ(&GC::Heap::the(), &heap);
+
+ // More than one block of cells, and enough weak pointers for a weak block.
+ auto list = GC::make_root(heap.allocate<ThreadTestCell>());
+ Vector<GC::Weak<ThreadTestCell>> weak_pointers;
+ for (size_t i = 0; i < 2000; ++i) {
+ auto cell = heap.allocate<ThreadTestCell>();
+ cell->next() = list.cell();
+ list = GC::make_root(cell);
+ weak_pointers.append(cell);
+ }
+ heap.collect_garbage();
+ for (auto& weak : weak_pointers)
+ EXPECT(weak.ptr());
+ list = {};
+}
+
+}
+
+TEST_CASE(heaps_on_several_threads_do_not_share_their_allocators)
+{
+ run_on_threads(8, [] {
+ for (size_t i = 0; i < 10; ++i)
+ churn_cells();
+ });
+ EXPECT_EQ(s_live_cells.load(), 0u);
+}
+
+TEST_CASE(heap_blocks_come_back_when_a_heap_goes_away)
+{
+ auto churn = [] {
+ run_on_threads(4, [] {
+ for (size_t i = 0; i < 10; ++i)
+ churn_cells();
+ });
+ };
+
+ churn();
+ auto committed_end = GC::BlockAllocator::heap_region_committed_end();
+ for (size_t i = 0; i < 20; ++i)
+ churn();
+ // NB: The decommit worker may have one chunk prepared ahead of the blocks that are in use.
+ EXPECT(GC::BlockAllocator::heap_region_committed_end() <= committed_end + 2 * MiB);
+}
+
+TEST_CASE(a_new_heap_can_become_the_default_of_a_thread)
+{
+ run_on_threads(1, [] {
+ {
+ GC::Heap heap([](auto&) { });
+ EXPECT_EQ(&GC::Heap::the(), &heap);
+ }
+ GC::Heap heap([](auto&) { });
+ EXPECT_EQ(&GC::Heap::the(), &heap);
+ });
+}
+
+TEST_CASE(null_weak_pointers_can_be_copied_on_several_threads)
+{
+ run_on_threads(8, [] {
+ for (size_t i = 0; i < 1'000'000; ++i) {
+ GC::Weak<ThreadTestCell> weak;
+ auto copy = weak;
+ EXPECT(!copy);
+ }
+ });
+}
+
+TEST_CASE(weak_pointer_can_outlive_its_heap)
+{
+ GC::Weak<ThreadTestCell> weak;
+ {
+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);
+ auto cell = heap.allocate<ThreadTestCell>();
+ weak = cell;
+ EXPECT(weak);
+ }
+ EXPECT(!weak);
+ auto copy = weak;
+ EXPECT(!copy);
+ weak = nullptr;
+ EXPECT(!copy);
+}
+
+#if !defined(AK_OS_WINDOWS)
+static constexpr int verification_failure_exit_code = 42;
+
+template<typename Callback>
+static bool crashes(Callback callback)
+{
+ auto pid = fork();
+ VERIFY(pid >= 0);
+ if (pid == 0) {
+ // NB: A failed check would print a symbolized backtrace before it crashes, which takes about a second.
+ AK::set_assertion_failure_callback([](auto, auto) { _exit(verification_failure_exit_code); });
+ callback();
+ _exit(0);
+ }
+ int status = 0;
+ VERIFY(waitpid(pid, &status, 0) == pid);
+ return WIFEXITED(status) && WEXITSTATUS(status) == verification_failure_exit_code;
+}
+
+TEST_CASE(a_heap_must_go_away_on_its_own_thread)
+{
+ EXPECT(crashes([] {
+ auto* heap = new GC::Heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);
+ run_on_threads(1, [heap] { delete heap; });
+ }));
+}
+
+TEST_CASE(a_heap_must_collect_on_its_own_thread)
+{
+ EXPECT(crashes([] {
+ auto* heap = new GC::Heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);
+ run_on_threads(1, [heap] { heap->collect_garbage(); });
+ }));
+}
+#endif