Skip to content

Commit 5edecbf

Browse files
committed
[JSC] Make WeakSet safe for concurrent sweeping
https://bugs.webkit.org/show_bug.cgi?id=329377 rdar://191259964 Reviewed by Dan Hecht. Lets a WeakSet's dead handles be finalized off the mutator, one sweeper at a time, while the mutator keeps allocating and clearing Weak<> handles without a lock. 1 WeakBlock's free list is now one Atomic<uint64_t>, with a bit per weak atom that is set while the atom is free. The header's weak atoms are never set. Only the mutator clears (allocates) bits, so taking a cell is one exchangeAnd with no retry loop; any thread frees with one fetch_or, and exactly one free sees the block become empty. 2 A sweep starts finalizing a Dead slot with a CAS of its state bits from Dead to Finalized, and clear() takes a Dead slot with an exchange, so each dead handle is finalized at most once and a cleared handle's finalizer never runs. Because a mutator clear() of a Dead slot does not decrement m_deadCount, m_deadCount is now an upper bound that sweep() resets to 0 when done. 3 In order to avoid racing with the mutator, WeakImpl::tryFinalize() copies the weak value and context out of the slot before its CAS marks the impl Finalized (returning an empty WeakImplSnapshot if the CAS fails). This allows a finalized impl to be cleared and reused by the mutator while the finalizer itself is still running. 4 WeakHandleOwner::finalize() returns a FinalizeResult (KeepImpl or DeallocateImpl). An owner that wants the impl freed returns DeallocateImpl instead of clearing it from inside the finalizer, so the sweep frees it. This removes the need for `WeakImpl::asWeakImpl(JSValue*)`, which doesn't fit with concurrent finalizing in (3) where the handle wraps a stack copy of the WeakImpl. 5 Only the mutator unlinks blocks from a WeakSet. WeakSet::finalizeDeadHandles() is the part of sweep() that may run off the mutator, and releaseBlocks() hands back the blocks it emptied on the mutator. Heap::weakBlockLock() guards m_blocks and iteration targets. 6 WeakSet::lastChanceToFinalize() now repeats markLiveHandlesDead() and sweep() until no live handles remain, so handles allocated by a finalizer during VM teardown are finalized too. This change does not permit clearing other WeakImpls while finalizing off the mutator (a finalizer may still clear other handles when running on the mutator). It's possible this API is too restrictive and we'll want to support concurrent clearing, assuming it's perf neutral. Concurrent allocation seems to be a regression in the naive implementation (adding a lock around the WeakSet). If we ever want to support that we'll likely need a LocalAllocator like system. Canonical link: https://commits.webkit.org/325371@main
1 parent 62196da commit 5edecbf

177 files changed

Lines changed: 1402 additions & 388 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Source/JavaScriptCore/API/JSAPIWrapperObject.mm‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737
class JSAPIWrapperObjectHandleOwner final : public JSC::WeakHandleOwner {
3838
public:
39-
void finalize(JSC::Handle<JSC::Unknown>, void*) final;
39+
FinalizeResult finalize(JSC::Handle<JSC::Unknown>, void*) final;
4040
bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::AbstractSlotVisitor&, ASCIILiteral*) final;
4141
};
4242

@@ -46,14 +46,14 @@
4646
return &jsWrapperObjectHandleOwner.get();
4747
}
4848

49-
void JSAPIWrapperObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
49+
JSC::WeakHandleOwner::FinalizeResult JSAPIWrapperObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
5050
{
5151
JSC::JSAPIWrapperObject* wrapperObject = static_cast<JSC::JSAPIWrapperObject*>(handle.get().asCell());
5252
if (!wrapperObject->wrappedObject())
53-
return;
53+
return FinalizeResult::DeallocateImpl;
5454

5555
JSC::Heap::heap(wrapperObject)->releaseSoon(adoptNS(static_cast<id>(wrapperObject->wrappedObject())));
56-
JSC::WeakSet::deallocate(JSC::WeakImpl::asWeakImpl(handle.slot()));
56+
return FinalizeResult::DeallocateImpl;
5757
}
5858

5959
bool JSAPIWrapperObjectHandleOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, JSC::AbstractSlotVisitor& visitor, ASCIILiteral*)

‎Source/JavaScriptCore/API/JSManagedValue.mm‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
class JSManagedValueHandleOwner final : public JSC::WeakHandleOwner {
4444
public:
45-
void finalize(JSC::Handle<JSC::Unknown>, void* context) final;
45+
FinalizeResult finalize(JSC::Handle<JSC::Unknown>, void* context) final;
4646
bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::AbstractSlotVisitor&, ASCIILiteral*) final;
4747
};
4848

@@ -191,10 +191,11 @@ - (void)disconnectValue;
191191
return visitor.containsOpaqueRoot((__bridge void*)managedValue);
192192
}
193193

194-
void JSManagedValueHandleOwner::finalize(JSC::Handle<JSC::Unknown>, void* context)
194+
JSC::WeakHandleOwner::FinalizeResult JSManagedValueHandleOwner::finalize(JSC::Handle<JSC::Unknown>, void* context)
195195
{
196196
JSManagedValue *managedValue = (__bridge JSManagedValue *)context;
197197
[managedValue disconnectValue];
198+
return FinalizeResult::KeepImpl;
198199
}
199200

200201
#endif // JSC_OBJC_API_ENABLED

‎Source/JavaScriptCore/API/glib/JSAPIWrapperGlobalObject.cpp‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434

3535
class JSAPIWrapperGlobalObjectHandleOwner final : public JSC::WeakHandleOwner {
3636
public:
37-
void finalize(JSC::Handle<JSC::Unknown>, void*) final;
37+
FinalizeResult finalize(JSC::Handle<JSC::Unknown>, void*) final;
3838
};
3939

4040
static JSAPIWrapperGlobalObjectHandleOwner* jsAPIWrapperGlobalObjectHandleOwner()
@@ -43,14 +43,14 @@ static JSAPIWrapperGlobalObjectHandleOwner* jsAPIWrapperGlobalObjectHandleOwner(
4343
return &jsWrapperGlobalObjectHandleOwner.get();
4444
}
4545

46-
void JSAPIWrapperGlobalObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
46+
JSC::WeakHandleOwner::FinalizeResult JSAPIWrapperGlobalObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
4747
{
4848
auto* wrapperObject = static_cast<JSC::JSAPIWrapperGlobalObject*>(handle.get().asCell());
4949
if (!wrapperObject->wrappedObject())
50-
return;
50+
return FinalizeResult::DeallocateImpl;
5151

5252
JSC::Heap::heap(wrapperObject)->releaseSoon(std::unique_ptr<JSC::JSCGLibWrapperObject>(wrapperObject->wrappedObject()));
53-
JSC::WeakSet::deallocate(JSC::WeakImpl::asWeakImpl(handle.slot()));
53+
return FinalizeResult::DeallocateImpl;
5454
}
5555

5656
namespace JSC {

‎Source/JavaScriptCore/API/glib/JSAPIWrapperObjectGLib.cpp‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737
class JSAPIWrapperObjectHandleOwner final : public JSC::WeakHandleOwner {
3838
public:
39-
void finalize(JSC::Handle<JSC::Unknown>, void*) final;
39+
FinalizeResult finalize(JSC::Handle<JSC::Unknown>, void*) final;
4040
bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::AbstractSlotVisitor&, ASCIILiteral*) final;
4141
};
4242

@@ -46,14 +46,14 @@ static JSAPIWrapperObjectHandleOwner* jsAPIWrapperObjectHandleOwner()
4646
return &jsWrapperObjectHandleOwner.get();
4747
}
4848

49-
void JSAPIWrapperObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
49+
JSC::WeakHandleOwner::FinalizeResult JSAPIWrapperObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
5050
{
5151
auto* wrapperObject = static_cast<JSC::JSAPIWrapperObject*>(handle.get().asCell());
5252
if (!wrapperObject->wrappedObject())
53-
return;
53+
return FinalizeResult::DeallocateImpl;
5454

5555
JSC::Heap::heap(wrapperObject)->releaseSoon(std::unique_ptr<JSC::JSCGLibWrapperObject>(static_cast<JSC::JSCGLibWrapperObject*>(wrapperObject->wrappedObject())));
56-
JSC::WeakSet::deallocate(JSC::WeakImpl::asWeakImpl(handle.slot()));
56+
return FinalizeResult::DeallocateImpl;
5757
}
5858

5959
bool JSAPIWrapperObjectHandleOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, JSC::AbstractSlotVisitor& visitor, ASCIILiteral*)

‎Source/JavaScriptCore/API/glib/JSCWeakValue.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,12 @@ static void jscWeakValueClear(JSCWeakValue* weakValue)
7272

7373
class JSCWeakValueHandleOwner final : public JSC::WeakHandleOwner {
7474
public:
75-
void finalize(JSC::Handle<JSC::Unknown>, void* context) final
75+
FinalizeResult finalize(JSC::Handle<JSC::Unknown>, void* context) final
7676
{
7777
auto* weakValue = JSC_WEAK_VALUE(context);
7878
jscWeakValueClear(weakValue);
7979
g_signal_emit(weakValue, signals[CLEARED], 0, nullptr);
80+
return FinalizeResult::KeepImpl;
8081
}
8182
};
8283

‎Source/JavaScriptCore/heap/Heap.cpp‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2037,20 +2037,18 @@ void Heap::addFinalizer(JSCell* cell, LambdaFinalizer function)
20372037
WeakSet::allocate(cell, &m_lambdaFinalizerOwner, function.leak()); // Balanced by LambdaFinalizerOwner::finalize().
20382038
}
20392039

2040-
void Heap::CFinalizerOwner::finalize(Handle<Unknown> handle, void* context)
2040+
WeakHandleOwner::FinalizeResult Heap::CFinalizerOwner::finalize(Handle<Unknown> handle, void* context)
20412041
{
2042-
HandleSlot slot = handle.slot();
20432042
CFinalizer finalizer = std::bit_cast<CFinalizer>(context);
2044-
finalizer(slot->asCell());
2045-
WeakSet::deallocate(WeakImpl::asWeakImpl(slot));
2043+
finalizer(handle.get().asCell());
2044+
return FinalizeResult::DeallocateImpl;
20462045
}
20472046

2048-
void Heap::LambdaFinalizerOwner::finalize(Handle<Unknown> handle, void* context)
2047+
WeakHandleOwner::FinalizeResult Heap::LambdaFinalizerOwner::finalize(Handle<Unknown> handle, void* context)
20492048
{
20502049
auto finalizer = WTF::adopt(static_cast<LambdaFinalizer::Impl*>(context));
2051-
HandleSlot slot = handle.slot();
2052-
finalizer(slot->asCell());
2053-
WeakSet::deallocate(WeakImpl::asWeakImpl(slot));
2050+
finalizer(handle.get().asCell());
2051+
return FinalizeResult::DeallocateImpl;
20542052
}
20552053

20562054
void Heap::collectNowFullIfNotDoneRecently(Synchronousness synchronousness)

‎Source/JavaScriptCore/heap/Heap.h‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,10 @@ class Heap {
521521

522522
unsigned weakBlockCount() const { return m_weakBlockCount; }
523523

524+
// Guards changes to each WeakSet's m_blocks, so that WeakSet::finalizeDeadHandles() can walk a
525+
// WeakSet off the mutator. Never hold it across a finalizer, since clear() may take it.
526+
Lock& weakBlockLock() WTF_RETURNS_LOCK(m_weakBlockLock) { return m_weakBlockLock; }
527+
524528
#if ENABLE(RESOURCE_USAGE)
525529
size_t blockBytesAllocated() const { return m_blockBytesAllocated; }
526530
#endif
@@ -651,11 +655,11 @@ class Heap {
651655
static constexpr size_t minExtraMemory = 256;
652656

653657
class CFinalizerOwner final : public WeakHandleOwner {
654-
void finalize(Handle<Unknown>, void* context) final;
658+
FinalizeResult finalize(Handle<Unknown>, void* context) final;
655659
};
656660

657661
class LambdaFinalizerOwner final : public WeakHandleOwner {
658-
void finalize(Handle<Unknown>, void* context) final;
662+
FinalizeResult finalize(Handle<Unknown>, void* context) final;
659663
};
660664

661665
Lock& lock() LIFETIME_BOUND { return m_lock; }
@@ -864,6 +868,7 @@ class Heap {
864868
Seconds m_lastEdenGCLength { 10_ms };
865869
#endif
866870

871+
Lock m_weakBlockLock;
867872
DoublyLinkedList<WeakBlock> m_detachedWeakBlocks;
868873
DoublyLinkedList<WeakBlock> m_pooledWeakBlocks;
869874
unsigned m_pooledWeakBlockCount { 0 };

‎Source/JavaScriptCore/heap/WeakBlock.cpp‎

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2012-2021 Apple Inc. All rights reserved.
2+
* Copyright (C) 2012-2021, 2026 Apple Inc. All rights reserved.
33
*
44
* Redistribution and use in source and binary forms, with or without
55
* modification, are permitted provided that the following conditions
@@ -62,34 +62,29 @@ void WeakBlock::destroy(JSC::Heap& heap, WeakBlock* block)
6262

6363
WeakBlock::WeakBlock(JSC::Heap& heap, CellContainer container)
6464
: DoublyLinkedListNode<WeakBlock>()
65+
, m_freeList(allFreeMask())
6566
, m_container(container)
6667
, m_heap(heap)
6768
{
68-
for (size_t i = 0; i < weakImplCount(); ++i) {
69-
WeakImpl* weakImpl = &weakImpls()[i];
70-
new (NotNull, weakImpl) WeakImpl;
71-
pushFreeCell(weakImpl);
72-
}
69+
for (size_t i = 0; i < weakImplCount(); ++i)
70+
new (NotNull, &weakImpls()[i]) WeakImpl;
7371

7472
ASSERT(isEmpty());
7573
assertFreeListIsConsistent();
7674
}
7775

7876
void WeakBlock::didBecomeEmpty()
7977
{
80-
ASSERT(isEmpty());
81-
8278
switch (m_ownership) {
8379
case Ownership::Attached:
84-
// A walk that runs finalizers is holding this block; WeakSet::sweep collects it afterwards.
85-
if (m_isIterationTarget)
86-
return;
80+
// May have been allocated from since it became empty; WeakSet rechecks.
8781
m_container.weakSet().didBecomeEmpty(this);
8882
break;
8983
case Ownership::Detached:
9084
// A detached block is on no WeakSet and is never swept, reaped or visited, and every slot in
9185
// it is already finalized, so only this call can change it. That makes returning it to the
9286
// Heap safe at any reentrancy depth, including from within a finalizer.
87+
ASSERT(isEmpty());
9388
ASSERT(!m_container);
9489
m_heap.releaseDetachedWeakBlock(this);
9590
break;
@@ -98,34 +93,43 @@ void WeakBlock::didBecomeEmpty()
9893
}
9994
}
10095

101-
void WeakBlock::lastChanceToFinalize()
96+
void WeakBlock::reapAllLiveHandles()
10297
{
98+
ASSERT(!m_isIterationTarget);
10399
for (size_t i = 0; i < weakImplCount(); ++i) {
104100
WeakImpl* weakImpl = &weakImpls()[i];
105-
WeakImpl::State state = weakImpl->state();
106-
if (state >= WeakImpl::Finalized)
107-
continue;
108-
if (state == WeakImpl::Live) {
109-
weakImpl->setState(WeakImpl::Dead);
101+
if (weakImpl->state() == WeakImpl::Live) {
102+
weakImpl->setDead();
110103
--m_liveCount;
111-
++m_deadCount;
104+
++m_deadCountUpperBound;
112105
}
113-
finalize(weakImpl);
114106
}
115107
}
116108

117109
void WeakBlock::sweep()
118110
{
119-
for (size_t i = 0; m_deadCount && i < weakImplCount(); ++i) {
111+
for (size_t i = 0; m_deadCountUpperBound && i < weakImplCount(); ++i) {
120112
WeakImpl* weakImpl = &weakImpls()[i];
121-
// finalize() calls out to a WeakHandleOwner, which may clear handles in this block or any
122-
// other. Clearing only pushes onto a free list, so the rest of this scan stays valid.
123-
if (weakImpl->state() == WeakImpl::Dead)
124-
finalize(weakImpl);
113+
uintptr_t stateWord = weakImpl->stateWord();
114+
if (WeakImpl::stateOf(stateWord) != WeakImpl::Dead)
115+
continue;
116+
117+
auto snapshot = weakImpl->trySetFinalized(stateWord);
118+
if (!snapshot)
119+
continue;
120+
121+
--m_deadCountUpperBound;
122+
if (!snapshot.weakHandleOwner)
123+
continue;
124+
125+
if (snapshot.weakHandleOwner->finalize(Handle<Unknown>::wrapSlot(&snapshot.jsValue), snapshot.context) == WeakHandleOwner::FinalizeResult::DeallocateImpl) {
126+
ASSERT(weakImpl->state() == WeakImpl::Finalized);
127+
weakImpl->clear();
128+
}
125129
}
126130

127-
ASSERT(!m_deadCount);
128-
assertFreeListIsConsistent();
131+
// The main thread could have already clear()'d, which doesn't update this count.
132+
m_deadCountUpperBound = 0;
129133
}
130134

131135
template<typename ContainerType, typename Visitor>
@@ -186,6 +190,8 @@ void WeakBlock::visit(SlotVisitor& visitor) { visitImpl(visitor); }
186190

187191
void WeakBlock::reap()
188192
{
193+
ASSERT(!m_isIterationTarget);
194+
assertFreeListIsConsistent();
189195
if (!m_liveCount)
190196
return;
191197

@@ -202,9 +208,9 @@ void WeakBlock::reap()
202208
if (m_container.isMarked(markingVersion, weakImpl->jsValue().asCell()))
203209
continue;
204210

205-
weakImpl->setState(WeakImpl::Dead);
211+
weakImpl->setDead();
206212
--m_liveCount;
207-
++m_deadCount;
213+
++m_deadCountUpperBound;
208214
}
209215
}
210216

0 commit comments

Comments
 (0)