Skip to content

Commit 9207c83

Browse files
committed
[JSC] Add thread-safety capabilities for the GC protocol's roles
https://bugs.webkit.org/show_bug.cgi?id=329878 rdar://191634814 Reviewed by Yusuke Suzuki. The mutator-collector protocol has rules about which thread may call what: only a thread with heap access polls, requests and waits for the Collector; only the conductor runs the phases, including each heap's part of them; and only the collector thread stops and resumes the mutator. Only assertConn checked any of this, and only the conn bits. Encoding the rules lets the compiler and debug asserts check that they still hold as the protocol changes for global collections. Add a capability for each role, checked at compile time by thread-safety analysis and established by asserts that check the thread at run time: - HeapAccessHolderRole, per heap. assertIsAccessHolder() checks that the current thread has access to the heap, using a debug-only record of the thread that acquired it. In iOS's legacy WebKit, where the UI thread and WebThread share access, it checks that the current thread holds the web lock instead. - CollectorThreadRole, per Collector. assertIsCollectorThread() compares with the thread recorded when the collector thread starts. - ConductorRole, one global token. checkIsConductor(), which replaces assertConn, checks the conn bits and that the current thread is the conductor they name. It runs in every build where a thread starts conducting and at each phase change; assertIsConductor() runs it elsewhere in debug builds only, so release builds check no more than before. - ConductorWithWorldStoppedRole, another global token, for the phases that stop the world. assertIsConductorWithWorldStopped() grants both it and ConductorRole, and in debug builds checks that the phase stops the world and that every heap has been stopped. Methods that rely on the mutators being stopped require it, so calling them in the Concurrent phase fails to build. A method requires a role when it is only safe to run in that role. Public entry points assert their role, since their callers do not hold the capability. The analysis does not carry a capability into a lambda, so each forEachHeap lambda that calls a method requiring a conductor role first asserts it. Heap's methods for the collector thread assert it at run time instead: the capability is a Collector member, and Heap.h only forward-declares Collector, so an annotation there cannot name it. clearMutatorWaiting and applyMembershipChangeWithLock run in either of two roles, which the analysis cannot express, so they assert at run time only. A later change will rebuild assertIsMutatorOrMutatorIsStopped(), and the places where BlockDirectory reads its bits without its lock, on these roles. Also remove five unused declarations, including hasHeapAccess(), whose last use this replaces. Canonical link: https://commits.webkit.org/325851@main
1 parent cc2d7f1 commit 9207c83

6 files changed

Lines changed: 275 additions & 107 deletions

File tree

‎Source/JavaScriptCore/heap/Collector.cpp‎

Lines changed: 76 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ class Collector::CollectorThread final : public AutomaticThread {
8181
PollResult poll(const AbstractLocker&) final
8282
{
8383
assertIsHeld(*m_collector.m_threadLock);
84+
m_collector.assertIsCollectorThread();
8485
if (m_collector.m_threadShouldStop) {
8586
m_collector.m_threadIsWorking = false;
8687
return PollResult::Stop;
@@ -95,13 +96,17 @@ class Collector::CollectorThread final : public AutomaticThread {
9596

9697
WorkResult work() final
9798
{
99+
m_collector.assertIsCollectorThread();
98100
m_collector.collectInCollectorThread();
99101
return WorkResult::Continue;
100102
}
101103

102104
void threadDidStart() final
103105
{
104106
Thread::registerGCThread(GCThreadType::Main);
107+
#if ASSERT_ENABLED
108+
m_collector.m_collectorThreadUID.storeRelaxed(Thread::currentSingleton().uid());
109+
#endif
105110
}
106111

107112
void threadIsStopping(const AbstractLocker&) final
@@ -235,7 +240,7 @@ GCRequest::Ticket Collector::requestCollection(Heap& requester, GCRequest reques
235240
// right now. This is an optimization that prevents the collector thread from ever starting in most
236241
// cases.
237242
ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
238-
ASSERT(requester.hasHeapAccess());
243+
requester.assertIsAccessHolder();
239244
ASSERT(!(requester.m_worldState.load() & Heap::stoppedBit));
240245
// It's okay for a heap to request a GC while its membership is pending, but it can't be the conductor yet.
241246
if ((m_lastServedTicket == m_lastGrantedTicket) && !m_threadIsWorking && hasHeap(requester)) {
@@ -285,6 +290,7 @@ CollectionScope Collector::decideCollectionScope()
285290

286291
void Collector::collectInCollectorThread()
287292
{
293+
checkIsConductor(GCConductor::Collector);
288294
for (;;) {
289295
RunCurrentPhaseResult result = runCurrentPhase(GCConductor::Collector, nullptr);
290296
switch (result) {
@@ -301,9 +307,11 @@ void Collector::collectInCollectorThread()
301307

302308
void Collector::collectInMutatorThread(Heap& conductor)
303309
{
310+
conductor.assertIsAccessHolder();
304311
ASSERT(hasHeap(conductor));
305312
ASSERT(!m_conductingHeap);
306313
SetForScope setConductingHeap { m_conductingHeap, &conductor };
314+
checkIsConductor(GCConductor::Mutator);
307315
for (;;) {
308316
RunCurrentPhaseResult result = runCurrentPhase(GCConductor::Mutator, nullptr);
309317
switch (result) {
@@ -314,6 +322,7 @@ void Collector::collectInMutatorThread(Heap& conductor)
314322
case RunCurrentPhaseResult::NeedCurrentThreadState:
315323
sanitizeStackForVM(conductor.vm());
316324
auto lambda = [&] (CurrentThreadState& state) {
325+
assertIsConductor(GCConductor::Mutator);
317326
for (;;) {
318327
RunCurrentPhaseResult result = runCurrentPhase(GCConductor::Mutator, &state);
319328
switch (result) {
@@ -335,7 +344,6 @@ void Collector::collectInMutatorThread(Heap& conductor)
335344

336345
auto Collector::runCurrentPhase(GCConductor conn, CurrentThreadState* conductingMutatorState) -> RunCurrentPhaseResult
337346
{
338-
assertConn(conn);
339347
m_conductingMutatorState = conductingMutatorState;
340348
m_conductorThread = &Thread::currentSingleton();
341349

@@ -408,6 +416,7 @@ NEVER_INLINE bool Collector::runNotRunningPhase(GCConductor conn)
408416

409417
NEVER_INLINE bool Collector::runBeginPhase(GCConductor conn)
410418
{
419+
assertIsConductorWithWorldStopped(conn);
411420
MonotonicTime startTime = MonotonicTime::now();
412421

413422
{
@@ -421,7 +430,7 @@ NEVER_INLINE bool Collector::runBeginPhase(GCConductor conn)
421430
CollectionScope scope = decideCollectionScope();
422431

423432
beginSignpost(scope, conn);
424-
beginCollectionInEachHeap(scope, startTime);
433+
beginCollectionInEachHeap(conn, scope, startTime);
425434

426435
if (scope == CollectionScope::Full) {
427436
m_opaqueRoots.clear();
@@ -479,10 +488,11 @@ NEVER_INLINE bool Collector::runBeginPhase(GCConductor conn)
479488
return changePhase(conn, CollectorPhase::Fixpoint);
480489
}
481490

482-
void Collector::beginCollectionInEachHeap(CollectionScope scope, MonotonicTime startTime)
491+
void Collector::beginCollectionInEachHeap(GCConductor conn, CollectionScope scope, MonotonicTime startTime)
483492
{
484493
HeapVersion markingVersion = m_heaps.first()->objectSpace().markingVersion();
485494
forEachHeap([&](Heap& heap) {
495+
assertIsConductorWithWorldStopped(conn);
486496
// SlotVisitor caches one marking version and uses it for every heap, so they must all have the
487497
// same one. A heap that joined after the others have collected can take their version. That is
488498
// safe only because it has never been collected: all of its blocks are still at nullVersion,
@@ -521,6 +531,7 @@ void Collector::setUpVisitors(CollectionScope scope)
521531

522532
NEVER_INLINE bool Collector::runFixpointPhase(GCConductor conn)
523533
{
534+
assertIsConductorWithWorldStopped(conn);
524535
RELEASE_ASSERT_IMPLIES(conn == GCConductor::Mutator, m_conductingMutatorState);
525536

526537
SlotVisitor& visitor = *m_collectorSlotVisitor;
@@ -635,6 +646,7 @@ NEVER_INLINE bool Collector::runConcurrentPhase(GCConductor conn)
635646

636647
NEVER_INLINE bool Collector::runReloopPhase(GCConductor conn)
637648
{
649+
assertIsConductorWithWorldStopped(conn);
638650
dataLogIf(Options::logGC(), "[GC<", *this, ">: ", gcConductorShortName(conn), " ");
639651

640652
m_scheduler->didStop();
@@ -647,6 +659,7 @@ NEVER_INLINE bool Collector::runReloopPhase(GCConductor conn)
647659

648660
NEVER_INLINE bool Collector::runEndPhase(GCConductor conn)
649661
{
662+
assertIsConductorWithWorldStopped(conn);
650663
m_scheduler->endCollection();
651664

652665
{
@@ -666,7 +679,7 @@ NEVER_INLINE bool Collector::runEndPhase(GCConductor conn)
666679
visitor.flushExtraMemoryVisited();
667680
});
668681

669-
endCollectionInEachHeap();
682+
endCollectionInEachHeap(conn);
670683

671684
forEachSlotVisitor(
672685
[&](SlotVisitor& visitor) {
@@ -696,15 +709,17 @@ NEVER_INLINE bool Collector::runEndPhase(GCConductor conn)
696709
endSignpost();
697710

698711
forEachHeap([&](Heap& heap) {
712+
assertIsConductorWithWorldStopped(conn);
699713
heap.setNeedCollectionEpilogue();
700714
heap.recordCollectionTime(m_afterGC - m_beforeGC);
701715
});
702716
return changePhase(conn, CollectorPhase::NotRunning);
703717
}
704718

705-
void Collector::endCollectionInEachHeap()
719+
void Collector::endCollectionInEachHeap(GCConductor conn)
706720
{
707721
forEachHeap([&](Heap& heap) {
722+
assertIsConductorWithWorldStopped(conn);
708723
ASSERT(heap.m_mutatorMarkStack->isEmpty());
709724

710725
// Executing CodeBlocks keep writing their profiles without barriers after this collection. Remembering
@@ -719,6 +734,7 @@ void Collector::endCollectionInEachHeap()
719734
verifyGC();
720735

721736
forEachHeap([&](Heap& heap) {
737+
assertIsConductorWithWorldStopped(conn);
722738
heap.verifyHeapAfterMarking();
723739
heap.pruneDeadReferences();
724740
heap.prepareForAllocation();
@@ -728,7 +744,7 @@ void Collector::endCollectionInEachHeap()
728744

729745
bool Collector::changePhase(GCConductor conn, CollectorPhase nextPhase)
730746
{
731-
assertConn(conn);
747+
checkIsConductor(conn);
732748

733749
m_lastPhase = m_currentPhase;
734750
m_nextPhase = nextPhase;
@@ -740,7 +756,7 @@ bool Collector::changePhase(GCConductor conn, CollectorPhase nextPhase)
740756
// mutator is handed the conn instead, and finishes the transition at its next poll.
741757
NEVER_INLINE bool Collector::finishChangingPhase(GCConductor conn)
742758
{
743-
assertConn(conn);
759+
checkIsConductor(conn);
744760

745761
if (m_nextPhase == m_currentPhase)
746762
return true;
@@ -758,11 +774,14 @@ NEVER_INLINE bool Collector::finishChangingPhase(GCConductor conn)
758774
// End sets the epilogue bit just before resuming into NotRunning, and nothing else sets it during a collection.
759775
RELEASE_ASSERT(heap().needCollectionEpilogue() == (m_currentPhase == CollectorPhase::End));
760776

761-
resumeThePeriphery();
777+
resumeThePeriphery(conn);
762778
if (conn == GCConductor::Collector)
763779
heap().resumeTheMutator();
764-
else
780+
else {
781+
// For thread-safety analysis: the conductor role does not carry the conducting heap's access.
782+
heap().assertIsAccessHolder();
765783
heap().handleNeedCollectionEpilogue();
784+
}
766785
} else {
767786
RELEASE_ASSERT(!suspendedBefore);
768787
RELEASE_ASSERT(suspendedAfter);
@@ -780,18 +799,19 @@ NEVER_INLINE bool Collector::finishChangingPhase(GCConductor conn)
780799
// A mutator runs any pending epilogue before it starts conducting, and only End sets the bit.
781800
RELEASE_ASSERT(!heap().needCollectionEpilogue());
782801
}
783-
stopThePeriphery();
802+
stopThePeriphery(conn);
784803
}
785804
}
786805

787806
m_currentPhase = m_nextPhase;
788807
return true;
789808
}
790809

791-
void Collector::stopThePeriphery()
810+
void Collector::stopThePeriphery(GCConductor conn)
792811
{
793812
m_isCompilerThreadsSuspended = suspendCompilerThreads();
794813
forEachHeap([&](Heap& heap) {
814+
assertIsConductor(conn);
795815
unsigned worldState = heap.m_worldState.load();
796816
if (&heap == m_conductingHeap)
797817
RELEASE_ASSERT(worldState & Heap::mutatorHasConnBit, worldState);
@@ -800,13 +820,20 @@ void Collector::stopThePeriphery()
800820
heap.stopThePeriphery();
801821
});
802822
m_collectorSlotVisitor->setMutatorsAreStopped(true);
823+
#if ASSERT_ENABLED
824+
m_worldIsStopped = true;
825+
#endif
803826

804827
m_stopTime = MonotonicTime::now();
805828
}
806829

807-
NEVER_INLINE void Collector::resumeThePeriphery()
830+
NEVER_INLINE void Collector::resumeThePeriphery(GCConductor conn)
808831
{
809-
forEachHeap([](Heap& heap) {
832+
#if ASSERT_ENABLED
833+
m_worldIsStopped = false;
834+
#endif
835+
forEachHeap([&](Heap& heap) {
836+
assertIsConductor(conn);
810837
heap.resumeThePeriphery();
811838
});
812839
// Before any mutator runs again.
@@ -840,6 +867,7 @@ void Collector::resumeCompilerThreads()
840867

841868
auto Collector::requestMembershipChange(MembershipChange&& change) -> MembershipChange::Ticket
842869
{
870+
change.heap->assertIsAccessHolder();
843871
Locker locker { *m_threadLock };
844872
auto ticket = ++m_lastRequestedMembershipChange;
845873
// If the Collector is idle, apply the change now: no collection can start while this thread holds the lock. This
@@ -876,6 +904,8 @@ void Collector::applyAllMembershipChangesWithLock(Vector<Heap*, 8>& changedHeaps
876904

877905
void Collector::applyMembershipChangeWithLock(MembershipChange& change)
878906
{
907+
// An idle Collector's requester, or the conductor.
908+
ASSERT(change.heap->currentThreadIsAccessHolder() || currentThreadIsConductor());
879909
RELEASE_ASSERT(m_currentPhase == CollectorPhase::NotRunning);
880910
Heap& heap = *change.heap;
881911
switch (change.kind) {
@@ -897,14 +927,45 @@ void Collector::applyMembershipChangeWithLock(MembershipChange& change)
897927
}
898928

899929
// Only the conducting heap's mutator has the conn, and none does while the collector thread conducts.
900-
void Collector::assertConn(GCConductor conn)
930+
void Collector::checkIsConductor(GCConductor conn)
901931
{
902932
RELEASE_ASSERT_IMPLIES(conn == GCConductor::Mutator, m_conductingHeap);
903933
forEachHeap([&](Heap& heap) {
904934
heap.checkConn(conn == GCConductor::Mutator && &heap == m_conductingHeap ? GCConductor::Mutator : GCConductor::Collector);
905935
});
936+
if (conn == GCConductor::Mutator)
937+
m_conductingHeap->assertIsAccessHolder();
938+
else
939+
assertIsCollectorThread();
940+
}
941+
942+
#if ASSERT_ENABLED
943+
void Collector::assertIsConductor(GCConductor conn)
944+
{
945+
checkIsConductor(conn);
906946
}
907947

948+
void Collector::assertIsConductorWithWorldStopped(GCConductor conn)
949+
{
950+
assertIsConductor(conn);
951+
ASSERT(worldShouldBeSuspended(m_currentPhase));
952+
ASSERT(m_worldIsStopped);
953+
}
954+
955+
void Collector::assertIsCollectorThread() const
956+
{
957+
ASSERT(m_collectorThreadUID.loadRelaxed() == Thread::currentSingleton().uid());
958+
}
959+
960+
bool Collector::currentThreadIsConductor() const
961+
{
962+
if (m_conductingHeap)
963+
return m_conductingHeap->currentThreadIsAccessHolder();
964+
return m_collectorThreadUID.loadRelaxed() == Thread::currentSingleton().uid();
965+
}
966+
#endif
967+
968+
908969
bool Collector::anyMutatorHasConnWithLock()
909970
{
910971
for (Heap* heap : m_heaps) {

0 commit comments

Comments
 (0)