Skip to content

Truly independent web browser

LibGC+LibWeb: Keep the callable of a GC::Function outside the GC heap

Andreas Kling98fdde209cee
diff --git a/Libraries/LibGC/Function.h b/Libraries/LibGC/Function.h
index c8b7a64b27c..c9eb1d826ce 100644
--- a/Libraries/LibGC/Function.h
+++ b/Libraries/LibGC/Function.h
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2023, Andreas Kling <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -7,54 +8,120 @@
#pragma once
#include <AK/Function.h>
+#include <AK/ScopeGuard.h>
+#include <AK/StdLibExtras.h>
#include <LibGC/Cell.h>
+#include <LibGC/FunctionTable.h>
#include <LibGC/Heap.h>
+#include <typeinfo>
namespace GC {
+namespace Detail {
+
+// NB: A function is made in one library and called from another, so its signature is the hash of the mangled name of
+// its type, which every compiler and library spells the same. How a compiler spells the type differs: GCC, for one,
+// spells it as it was first written in each source file. Types of the same name with internal linkage, such as
+// those in an anonymous namespace, share one signature.
template<typename T>
-class Function final : public Cell {
+inline u64 const function_signature = [] {
+ u64 hash = 0xcbf29ce484222325;
+ for (auto const* character = typeid(T).name(); *character; ++character) {
+ hash ^= static_cast<u8>(*character);
+ hash *= 0x100000001b3;
+ }
+ return hash;
+}();
+
+}
+
+template<typename R, typename... Args>
+struct FunctionOperationsFor : FunctionOperations {
+ R (*invoke)(void* box, Args...) { nullptr };
+};
+
+template<typename T>
+class Function;
+
+template<typename R, typename... Args>
+class Function<R(Args...)> final : public Cell {
GC_CELL(Function, Cell);
GC_DECLARE_ALLOCATOR(Function);
public:
- static Ref<Function> create(Heap& heap, ESCAPING AK::Function<T>&& function)
+ using Operations = FunctionOperationsFor<R, Args...>;
+ using Lambda = AK::Function<R(Args...)>;
+
+ static Ref<Function> create(Heap& heap, ESCAPING AK::Function<R(Args...)>&& function)
{
- return heap.allocate<Function>(move(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;
}
- virtual ~Function() override = default;
+ R operator()(Args... args) const
+ {
+ auto const& slot = heap().function_table().slot(m_handle);
+ VERIFY(*slot.operations->signature == Detail::function_signature<R(Args...)>);
+ // NB: The box is outside the heap, so nothing the callable holds points into this cell. This pointer is kept
+ // live across the call, where the conservative scan of the stack finds it, so that a collection the callable
+ // runs after dropping the last reference to its function does not destroy the box under it.
+ ScopeGuard keep_alive = [this] { asm volatile("" : : "r"(this) : "memory"); };
+ return static_cast<Operations const&>(*slot.operations).invoke(slot.box, forward<Args>(args)...);
+ }
+
+ Function const& function() const { return *this; }
virtual void finalize() override
{
Base::finalize();
- m_function = nullptr;
+ if (!m_handle.is_valid())
+ return;
+ auto& table = heap().function_table();
+ auto const& slot = table.slot(m_handle);
+ slot.operations->destroy(slot.box);
+ table.free(m_handle);
+ m_handle = {};
}
- [[nodiscard]] AK::Function<T> const& function() const { return m_function; }
-
private:
- Function(AK::Function<T>&& function)
- : m_function(move(function))
- {
- }
+ Function() = default;
virtual void visit_edges(Visitor& visitor) override
{
Base::visit_edges(visitor);
- visitor.visit_possible_values(m_function.raw_capture_range());
+ if (!m_handle.is_valid())
+ return;
+ auto const& slot = heap().function_table().slot(m_handle);
+ slot.operations->visit_edges(slot.box, visitor);
}
- AK::Function<T> m_function;
+ // 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)...);
+ },
+ };
+
+ FunctionTableHandle m_handle;
};
-template<typename Callable, typename T = EquivalentFunctionType<Callable>>
+template<typename Callable, typename T = EquivalentFunctionType<RemoveCVReference<Callable>>>
static Ref<Function<T>> create_function(Heap& heap, ESCAPING Callable&& function)
{
return Function<T>::create(heap, AK::Function<T> { forward<Callable>(function) });
}
-template<typename T>
-GC_DEFINE_ALLOCATOR(Function<T>);
+template<typename R, typename... Args>
+GC_DEFINE_ALLOCATOR(Function<R(Args...)>);
}
diff --git a/Libraries/LibGC/FunctionTable.h b/Libraries/LibGC/FunctionTable.h
new file mode 100644
index 00000000000..ee487c5be33
--- /dev/null
+++ b/Libraries/LibGC/FunctionTable.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Noncopyable.h>
+#include <AK/NonnullOwnPtr.h>
+#include <AK/Vector.h>
+#include <AK/kmalloc.h>
+#include <LibGC/Cell.h>
+#include <LibGC/Export.h>
+#include <LibGC/ExternalEntityTable.h>
+
+namespace GC {
+
+using FunctionTableHandle = ExternalEntityTableHandle;
+
+// What a GC::Function does with the box that holds its captures. Each kind of function has one static instance. The
+// signature identifies the function type it was made for, so a handle that names another function's entry is caught
+// before its box is invoked as the wrong type.
+struct FunctionOperations {
+ u64 const* signature { nullptr };
+ void (*visit_edges)(void* box, Cell::Visitor&) { nullptr };
+ void (*destroy)(void* box) { nullptr };
+};
+
+// The parts of every GC::Function that live outside the GC heap: the operations of its callable and the box that
+// holds what it captured. A function cell holds only a handle to its entry, so the cell holds no pointer at all.
+class GC_API FunctionTable : private ExternalEntityTable {
+ AK_MAKE_NONCOPYABLE(FunctionTable);
+ AK_MAKE_NONMOVABLE(FunctionTable);
+
+public:
+ // A box this small is kept in its entry, which saves allocating one for most functions.
+ static constexpr size_t inline_box_capacity = 48;
+ static constexpr size_t box_alignment = 16;
+
+ struct Slot {
+ FunctionOperations const* operations { nullptr };
+ void* box { nullptr };
+ alignas(box_alignment) u8 inline_box[inline_box_capacity];
+ };
+ static_assert(sizeof(Slot) == 64);
+
+ struct Allocation {
+ FunctionTableHandle handle;
+ void* box { nullptr };
+ };
+
+ FunctionTable() = default;
+
+ // Reserves an entry with room for a box of box_size bytes, which the caller then constructs in place. The box keeps
+ // its address until the entry is freed, also while the table grows, as a callable may make functions as it runs.
+ ALWAYS_INLINE Allocation allocate(FunctionOperations const& operations, size_t box_size)
+ {
+ auto handle = allocate_entry(tag);
+ if (handle.index == m_chunks.size() * slots_per_chunk)
+ m_chunks.append(make<Chunk>());
+ auto& slot = slot_at(handle.index);
+ slot.operations = &operations;
+ if (box_size == 0)
+ slot.box = nullptr;
+ else if (box_size <= inline_box_capacity)
+ slot.box = slot.inline_box;
+ else
+ slot.box = kmalloc(box_size);
+ VERIFY(!box_size || slot.box);
+ return { handle, slot.box };
+ }
+
+ ALWAYS_INLINE Slot const& slot(FunctionTableHandle handle) const
+ {
+ VERIFY(is_valid(handle, tag));
+ return const_cast<FunctionTable&>(*this).slot_at(handle.index);
+ }
+
+ // Releases the entry of a function whose box has been destroyed.
+ ALWAYS_INLINE void free(FunctionTableHandle handle)
+ {
+ VERIFY(is_valid(handle, tag));
+ auto& slot = slot_at(handle.index);
+ if (slot.box && slot.box != slot.inline_box)
+ kfree(slot.box);
+ slot.operations = nullptr;
+ slot.box = nullptr;
+ free_entry(handle, tag);
+ }
+
+private:
+ static constexpr auto tag = balanced_external_entity_table_tag(1);
+ static constexpr size_t slots_per_chunk = 256;
+
+ struct Chunk {
+ AK_ALLOC_WITH_KMALLOC;
+ Slot slots[slots_per_chunk];
+ };
+
+ ALWAYS_INLINE Slot& slot_at(u32 index) { return m_chunks[index / slots_per_chunk]->slots[index % slots_per_chunk]; }
+
+ Vector<NonnullOwnPtr<Chunk>> m_chunks;
+};
+
+}
diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.h
index 781f5c4a45c..030cfdeb037 100644
--- a/Libraries/LibGC/Heap.h
+++ b/Libraries/LibGC/Heap.h
@@ -27,6 +27,7 @@
#include <LibGC/ConservativeVector.h>
#include <LibGC/CrossHeapMember.h>
#include <LibGC/Forward.h>
+#include <LibGC/FunctionTable.h>
#include <LibGC/HeapRoot.h>
#include <LibGC/IdleCollectionPolicy.h>
#include <LibGC/Root.h>
@@ -162,6 +163,8 @@ public:
void uproot_cell(ForeignCell* cell) { uproot_cell(as_cell(cell)); }
bool is_gc_deferred() const { return m_gc_deferrals > 0; }
+
+ FunctionTable& function_table() { return m_function_table; }
bool is_incremental_sweep_active() const { return m_incremental_sweep_active; }
void sweep_block(HeapBlock&);
@@ -367,6 +370,7 @@ private:
bool m_weak_pointers_to_dead_cells_are_cleared { false };
CollectionType m_current_collection_type { CollectionType::CollectGarbage };
StackInfo m_stack_info;
+ FunctionTable m_function_table;
AK::Function<void(HashMap<Cell*, GC::HeapRoot>&)> m_gather_embedder_roots;
Vector<AK::Function<void()>> m_post_gc_tasks;
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 16509efaa1d..4accdc6a922 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -1130,7 +1130,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// end-of-body given response.
auto algorithms = controller->algorithms();
if (algorithms->process_response_end_of_body())
- (algorithms->process_response_end_of_body())(response_view);
+ algorithms->process_response_end_of_body()->function()(response_view);
report_timing_if_appropriate();
});
@@ -1143,7 +1143,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// given response, with fetchParams’s task destination.
if (controller->algorithms()->process_response()) {
Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), [controller, response_view]() {
- controller->algorithms()->process_response()(response_view);
+ controller->algorithms()->process_response()->function()(response_view);
}));
}
@@ -1290,18 +1290,18 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
auto process_body = GC::create_function(GC::Heap::the(), [algorithms, response = response_view->record(), response_view](ByteBuffer bytes) {
if (auto body = response->body(); body.has_value()) {
if (auto source = body->source(); source.has_value()) {
- (algorithms->process_response_consume_body())(response_view, *source);
+ algorithms->process_response_consume_body()->function()(response_view, *source);
return;
}
}
// A body the transport delivered as slices of one mapping keeps that mapping instead of the bytes read.
if (auto const& network_transport = response->network_transport(); network_transport.has_value()) {
if (auto whole_body = network_transport->body_channel->whole_body(); whole_body.has_value()) {
- (algorithms->process_response_consume_body())(response_view, whole_body.release_value());
+ algorithms->process_response_consume_body()->function()(response_view, whole_body.release_value());
return;
}
}
- (algorithms->process_response_consume_body())(response_view, Core::ImmutableBytes::adopt(move(bytes)));
+ algorithms->process_response_consume_body()->function()(response_view, Core::ImmutableBytes::adopt(move(bytes)));
});
// 2. Let processBodyError be this step: run fetchParams’s process response consume body given response and
@@ -1311,7 +1311,7 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
setup_report_timing_steps();
// NB: A failed read does not always close or error the body's stream, which would otherwise end this.
end_rendering_pending_operation(controller.ptr());
- (algorithms->process_response_consume_body())(response_view, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
+ algorithms->process_response_consume_body()->function()(response_view, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
});
// 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with
@@ -1320,12 +1320,12 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const
// AD-HOC: For a sync XHR's body, run processBody directly (see read_body_in_parallel above;
// processResponseEndOfBody already ran, right after it).
if (read_body_in_parallel) {
- (algorithms->process_response_consume_body())(response_view, Empty {});
+ algorithms->process_response_consume_body()->function()(response_view, Empty {});
} else {
Infrastructure::queue_fetch_task(controller, controller->task_destination(), GC::create_function(GC::Heap::the(), [algorithms, response_view]() {
// NB: We have to provide fully_read a callback which accepts a ByteBuffer. Since that's not
// nullable, we just invoke process_response_consume_body with a null value manually here.
- (algorithms->process_response_consume_body())(response_view, Empty {});
+ algorithms->process_response_consume_body()->function()(response_view, Empty {});
}));
}
}
@@ -2991,7 +2991,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
if (request->body().has<Empty>()) {
if (fetch_params.controller()->algorithms()->process_request_end_of_body()) {
Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.controller()->task_destination(), GC::create_function(GC::Heap::the(), [fetch_params = NonnullRefPtr { fetch_params }]() {
- fetch_params->controller()->algorithms()->process_request_end_of_body()();
+ fetch_params->controller()->algorithms()->process_request_end_of_body()->function()();
}));
}
}
@@ -3010,7 +3010,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
// 3. If fetchParams’s process request body chunk length is non-null, then run fetchParams’s process
// request body chunk length given bytes’s length.
if (controller->algorithms()->process_request_body_chunk_length())
- controller->algorithms()->process_request_body_chunk_length()(length);
+ controller->algorithms()->process_request_body_chunk_length()->function()(length);
};
// 2. Let processEndOfBody be these steps:
@@ -3022,7 +3022,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
// 2. If fetchParams’s process request end-of-body is non-null, then run fetchParams’s process request
// end-of-body.
if (controller->algorithms()->process_request_end_of_body())
- controller->algorithms()->process_request_end_of_body()();
+ controller->algorithms()->process_request_end_of_body()->function()();
});
// 3. Let processBodyError given e be these steps:
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp
index 9d5c4ad0767..014b5c56c3e 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp
@@ -16,12 +16,18 @@ GC_DEFINE_ALLOCATOR(FetchAlgorithms);
GC::Ref<FetchAlgorithms> FetchAlgorithms::create(Input input)
{
- auto process_request_body_chunk_length = GC::create_function(GC::Heap::the(), move(input.process_request_body_chunk_length));
- auto process_request_end_of_body = GC::create_function(GC::Heap::the(), move(input.process_request_end_of_body));
- auto process_early_hints_response = GC::create_function(GC::Heap::the(), move(input.process_early_hints_response));
- auto process_response = GC::create_function(GC::Heap::the(), move(input.process_response));
- auto process_response_end_of_body = GC::create_function(GC::Heap::the(), move(input.process_response_end_of_body));
- auto process_response_consume_body = GC::create_function(GC::Heap::the(), move(input.process_response_consume_body));
+ // 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,
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h
index e3e026b5be5..f7927cadbb1 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h
@@ -33,12 +33,12 @@ public:
using ProcessResponseEndOfBodyFunction = Function<void(GC::Ref<Infrastructure::ResponseView>)>;
using ProcessResponseConsumeBodyFunction = Function<void(GC::Ref<Infrastructure::ResponseView>, BodyBytes)>;
- using ProcessRequestBodyChunkLengthHeapFunction = GC::Ref<GC::Function<ProcessRequestBodyChunkLengthFunction::FunctionType>>;
- using ProcessRequestEndOfBodyHeapFunction = GC::Ref<GC::Function<ProcessRequestEndOfBodyFunction::FunctionType>>;
- using ProcessEarlyHintsResponseHeapFunction = GC::Ref<GC::Function<ProcessEarlyHintsResponseFunction::FunctionType>>;
- using ProcessResponseHeapFunction = GC::Ref<GC::Function<ProcessResponseFunction::FunctionType>>;
- using ProcessResponseEndOfBodyHeapFunction = GC::Ref<GC::Function<ProcessResponseEndOfBodyFunction::FunctionType>>;
- using ProcessResponseConsumeBodyHeapFunction = GC::Ref<GC::Function<ProcessResponseConsumeBodyFunction::FunctionType>>;
+ using ProcessRequestBodyChunkLengthHeapFunction = GC::Ptr<GC::Function<ProcessRequestBodyChunkLengthFunction::FunctionType>>;
+ using ProcessRequestEndOfBodyHeapFunction = GC::Ptr<GC::Function<ProcessRequestEndOfBodyFunction::FunctionType>>;
+ using ProcessEarlyHintsResponseHeapFunction = GC::Ptr<GC::Function<ProcessEarlyHintsResponseFunction::FunctionType>>;
+ using ProcessResponseHeapFunction = GC::Ptr<GC::Function<ProcessResponseFunction::FunctionType>>;
+ using ProcessResponseEndOfBodyHeapFunction = GC::Ptr<GC::Function<ProcessResponseEndOfBodyFunction::FunctionType>>;
+ using ProcessResponseConsumeBodyHeapFunction = GC::Ptr<GC::Function<ProcessResponseConsumeBodyFunction::FunctionType>>;
// A request body whose stream is the only place its bytes are, with the reader fetch() acquired for that stream.
struct RequestBodyReader {
@@ -66,12 +66,12 @@ public:
Engine::BodyIntent body_intent() const { return m_body_intent; }
Optional<RequestBodyReader> const& request_body_reader() const { return m_request_body_reader; }
- ProcessRequestBodyChunkLengthFunction const& process_request_body_chunk_length() const { return m_process_request_body_chunk_length->function(); }
- ProcessRequestEndOfBodyFunction const& process_request_end_of_body() const { return m_process_request_end_of_body->function(); }
- ProcessEarlyHintsResponseFunction const& process_early_hints_response() const { return m_process_early_hints_response->function(); }
- ProcessResponseFunction const& process_response() const { return m_process_response->function(); }
- ProcessResponseEndOfBodyFunction const& process_response_end_of_body() const { return m_process_response_end_of_body->function(); }
- ProcessResponseConsumeBodyFunction const& process_response_consume_body() const { return m_process_response_consume_body->function(); }
+ ProcessRequestBodyChunkLengthHeapFunction process_request_body_chunk_length() const { return m_process_request_body_chunk_length; }
+ ProcessRequestEndOfBodyHeapFunction process_request_end_of_body() const { return m_process_request_end_of_body; }
+ ProcessEarlyHintsResponseHeapFunction process_early_hints_response() const { return m_process_early_hints_response; }
+ ProcessResponseHeapFunction process_response() const { return m_process_response; }
+ ProcessResponseEndOfBodyHeapFunction process_response_end_of_body() const { return m_process_response_end_of_body; }
+ ProcessResponseConsumeBodyHeapFunction process_response_consume_body() const { return m_process_response_consume_body; }
virtual void visit_edges(JS::Cell::Visitor&) override;
diff --git a/Tests/LibGC/CMakeLists.txt b/Tests/LibGC/CMakeLists.txt
index 46603347e71..69999e74147 100644
--- a/Tests/LibGC/CMakeLists.txt
+++ b/Tests/LibGC/CMakeLists.txt
@@ -7,6 +7,7 @@ set(TEST_SOURCES
TestGCContainers.cpp
TestGCEphemeron.cpp
TestGCFreeList.cpp
+ TestGCFunction.cpp
TestGCHeapGroup.cpp
TestGCIdleCollection.cpp
TestGCIncrementalSweep.cpp
diff --git a/Tests/LibGC/TestGCFunction.cpp b/Tests/LibGC/TestGCFunction.cpp
new file mode 100644
index 00000000000..061030b8132
--- /dev/null
+++ b/Tests/LibGC/TestGCFunction.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/OwnPtr.h>
+#include <AK/RefCounted.h>
+#include <LibGC/Cell.h>
+#include <LibGC/CellAllocator.h>
+#include <LibGC/Function.h>
+#include <LibGC/Heap.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/Root.h>
+#include <LibGC/Testing.h>
+#include <LibGC/WeakInlines.h>
+#include <LibTest/TestCase.h>
+
+namespace {
+
+class TestCell final : public GC::Cell {
+ GC_CELL(TestCell, GC::Cell);
+ GC_DECLARE_ALLOCATOR(TestCell);
+
+public:
+ i64 value { 0 };
+
+private:
+ TestCell() = default;
+};
+
+GC_DEFINE_ALLOCATOR(TestCell);
+
+class CellWithFunction final : public GC::Cell {
+ GC_CELL(CellWithFunction, GC::Cell);
+ GC_DECLARE_ALLOCATOR(CellWithFunction);
+
+public:
+ GC::Ptr<GC::Function<void()>> function;
+
+private:
+ CellWithFunction() = default;
+
+ virtual void visit_edges(Visitor& visitor) override
+ {
+ Base::visit_edges(visitor);
+ visitor.visit(function);
+ }
+};
+
+GC_DEFINE_ALLOCATOR(CellWithFunction);
+
+struct DestructionFlag {
+ AK_ALLOC_WITH_KMALLOC;
+
+ explicit DestructionFlag(bool& destroyed)
+ : destroyed(destroyed)
+ {
+ }
+ ~DestructionFlag() { destroyed = true; }
+
+ bool& destroyed;
+};
+
+struct RunState : RefCounted<RunState> {
+ GC::Weak<GC::Function<void()>> function;
+ bool survived_collection { false };
+};
+
+struct Holders {
+ GC::Root<GC::Function<int()>> function;
+ 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();
+}
+
+}
+
+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);
+}