[2] Collector thread outlives its heap during JSC VM teardown
JSC's collector said goodbye to its heap, then kept working on it
Medium. A crash in practice, a UAF in principle. The common interleaving ends in a deterministic RELEASE_ASSERT; the rarer path touches a small GC-internal timer with no attacker-controlled fields, so going further would need both race-winning and reclaim of that slot.
Tearing down a garbage-collected heap in a multi-threaded engine is safe only if every helper thread working on that heap has stopped before the heap's members are destroyed. In JSC, each Heap (the per-VM object that owns all GC state) has a local Collector, a helper object that runs a dedicated collector thread and, under a debug option, a second collect-continuously thread. The expectation is that once Heap::shutDown() returns, no collector thread still touches heap members such as StopIfNecessaryTimer, a heap-owned timer that tells the mutator thread to pause for GC.
The angle: a page that repeatedly starts and terminates workers under concurrent GC could race a worker VM's teardown against that VM's own collector thread. That race crashes the renderer, and on a rarer interleaving it touches a freed StopIfNecessaryTimer.
Per the commit message, Heap::shutDown() waits only for the heap's Leave request to be processed, and that can happen before the collector thread has returned from m_stopIfNecessaryTimer->scheduleSoon():
- The collector thread is conducting a collection and calls
Heap::stopTheMutator(). The mutator holds heap access, so instead of stopping it, the collector thread hands it the conn by settingmutatorHasConnBit. - The mutator thread, inside
waitForCollector(), sees it has the conn, finishes the collection, and processes its own Leave request. - The collector thread has not yet returned from
m_stopIfNecessaryTimer->scheduleSoon(), which uses Heap state. - According to the commit message, the mutator then continues through
~VM, which unregisters the VM fromJSRunLoopTimer::Manager, and~Heapdestroysm_stopIfNecessaryTimerbeforem_localCollector, so~Collectorjoins the collector thread too late. - The collector thread accesses the freed
m_stopIfNecessaryTimer, or hits theRELEASE_ASSERTinJSRunLoopTimer::Manager::scheduleTimer()because the VM has unregistered.
According to the commit message, 323479@main removed an earlier join: before it, Heap::shutDown() joined the collector thread before tearing anything down. This commit restores that: Collector::shutDown() stops the collect-continuously thread and the collector thread, and Heap::shutDown() calls it for a local Collector right after leaving. ~Collector now asserts that the threads are already stopped instead of stopping them itself. The --useGlobalGC=true case still needs a fix, which depends on how stopping the mutators of several heaps will work. This commit fixes the local-Collector (--useGlobalGC=false) case.
Source/JavaScriptCore/heap/Heap.cpp
Source/JavaScriptCore/heap/Collector.cpp
JSTests/stress/many-agents-teardown.js
Patch Details
In Collector.cpp, the former body of Collector::~Collector(), stopCollectingContinuously() followed by stopThread(), moves into a new public Collector::shutDown() declared in Collector.h. The destructor no longer stops anything. It now carries three RELEASE_ASSERTs: m_heaps.isEmpty() (upgraded from a debug ASSERT), !m_collectContinuouslyThread, and m_threadShouldStop checked under m_threadLock. m_raceMarkStack->clear() stays in the destructor. stopCollectingContinuously() now nulls m_collectContinuouslyThread after waitForCompletion(), which is what lets the second assertion hold. stopThread() stops the CollectorThread and falls back to m_thread->join() only when tryStop(locker) fails. In Heap.cpp, Heap::shutDown() calls m_localCollector->shutDown() immediately after the Leave membership change is processed. The call is skipped when m_localCollector is null, which is the --useGlobalGC=true configuration. The new stress test spawns 16 root agents, each starting up to 32 leaf agents that queue 50 setTimeouts, all under --collectContinuously=1 --collectContinuouslyPeriodMS=0.1.
Treating a protocol-level acknowledgement from a worker thread as proof of thread quiescence, so owner teardown destroys state the worker is still executing against.
Background
VMs, heaps, and agents.
Each JSC VM owns exactly one Heap. In the jsc shell, $.agent.start() creates a separate agent with its own VM on its own thread. In the browser, each Web Worker likewise gets its own VM, created on worker start and destroyed on termination.
Local vs global collector.
In the local-Collector (--useGlobalGC=false) configuration, each Heap has its own m_localCollector. That Collector owns a CollectorThread, an AutomaticThread that polls m_threadShouldStop and shouldCollectInCollectorThread() under m_threadLock, and, when Options::collectContinuously() is set, an extra m_collectContinuouslyThread. With --useGlobalGC=true, a single never-destroyed Collector::globalCollector() serves all heaps.
The conn.
JSC's concurrent GC uses a token called the conn to decide which thread conducts the current collection phase: the collector thread or a mutator. When the collector needs to stop a mutator that holds heap access, it can hand the conn to that mutator, which then drives the collection itself from waitForCollector(). The handoff exists so a mutator that is busy holding heap access can make progress on GC instead of blocking.
Membership changes.
Heaps join and leave a Collector through requestMembershipChange() with Kind::Join or Kind::Leave. Whichever thread conducts next applies these changes between collections.
JSRunLoopTimer::Manager and StopIfNecessaryTimer.
JSRunLoopTimer::Manager is a process-wide singleton mapping each VM's JSLock to a PerVMData, which holds a RunLoop::Timer and a vector of Ref<JSRunLoopTimer>. registerVM/unregisterVM add and remove the entry. scheduleTimer() RELEASE_ASSERTs that the entry exists, while cancelTimer() tolerates its absence. StopIfNecessaryTimer is a heap-owned JSRunLoopTimer subclass; its scheduleSoon() arms the timer so the mutator thread soon calls heap.stopIfNecessary(). JSRunLoopTimer is ThreadSafeRefCounted.
C++ member destruction order. Non-static data members are destroyed in reverse declaration order, so a later-declared member's destructor runs before an earlier-declared one's.
Analysis
This is a teardown-ordering race that ends in either a deterministic RELEASE_ASSERT or a use-after-free, depending on the interleaving.
Collector thread Mutator thread (agent VM)
──────────────── ─────────────────────────
stopTheMutator(): mutator holds
heap access, set mutatorHasConnBit ──► waitForCollector(): owns conn
finishes collection
processes own Leave
Heap::shutDown() returns
m_stopIfNecessaryTimer ~VM: Manager::unregisterVM()
->scheduleSoon() ◄── window ──► ~Heap: m_stopIfNecessaryTimer dropped
├─ timer alive: scheduleTimer() ~Heap: m_localCollector destroyed
│ RELEASE_ASSERT (VM gone) └─► ~Collector stops thread (too late)
└─ timer freed: UAF reads
The mechanism follows the commit message, and the conn handoff is consistent with the Collector.h API. In the left column, the collector thread is mid-collection when it decides to stop the mutator. Because the mutator holds heap access, the collector hands it the conn and goes on to call scheduleSoon(). In the right column, the mutator now owns the conn, so it completes the collection itself and applies its own Leave. From Heap::shutDown()'s point of view, the Leave was processed, so it returns. But the collector thread has not left scheduleSoon(), and the handshake said nothing about where that thread is.
The mutator then proceeds through ~VM, which calls JSRunLoopTimer::Manager::unregisterVM() and erases the VM's PerVMData from m_mapping. Erasing that entry drops any Ref<JSRunLoopTimer> held in data.timers, which is consistent with ~Heap's reference then being the last one. The commit message places m_stopIfNecessaryTimer's destruction before m_localCollector's. As a result, the only remaining thread stop, inside ~Collector, runs after the timer is gone.
Before 323479@main, the commit message notes, Heap::shutDown() joined the collector thread before tearing anything down. Removing that early join left ~Collector as the sole stop, and member declaration order put that stop after the timer's destruction.
What the still-running collector thread hits depends on where it is in the window:
- Assertion path. The
StopIfNecessaryTimerobject is still allocated, soscheduleSoon()→setTimeUntilFire(0_s)→Manager::scheduleTimer()looks uptimer.m_apiLock. The VM is already gone from the mapping, soRELEASE_ASSERT(iter != m_mapping.end())fires ("We don't allow calling this after the VM dies"). - UAF path. The timer has been freed, so the reads of
m_isDisabledandisScheduled()inscheduleSoon(), them_apiLockread, and the lock acquisition inside theJSRunLoopTimerbase all touch freed memory.setTimeUntilFire()is expected to take a base-class lock (JSRunLoopTimer'sm_lock) before reachingscheduleTimer().
The stress test is a distilled reproduction:
- Run with
--collectContinuously=1 --collectContinuouslyPeriodMS=0.1, so every heap's collector is almost always mid-collection. - Start 16 root agents, each of which starts up to 32 leaf agents. That produces hundreds of independent VMs.
- Each leaf queues 50
setTimeouts, so it runs long enough to collect, then exits and tears its VM down while its collector thread is busy. - Across hundreds of teardowns, some land in the conn-handoff window and hit the assertion. Post-fix,
Collector::shutDown()stops both threads before any member is destroyed.
The discovery angle fits that shape. Stress testing or fuzzing that surfaced the scheduleTimer() RELEASE_ASSERT as a crash, followed by root-causing to the 323479@main regression, would produce exactly this kind of many-agents test.
On exploitability, the path would be reachable from web content via Worker creation and termination with concurrent GC, if the local-Collector/membership-change refactor has shipped in a browser build. That has not been established, and the regression test relies on the debug-only --collectContinuously options to widen the window. The common outcome would be a renderer crash on the RELEASE_ASSERT. For the UAF interleaving, the open question is whether an attacker could steer the collector thread to reach scheduleSoon() after ~Heap dropped the timer, and whether the freed JSRunLoopTimer-sized slot could be reclaimed before the m_isDisabled/isScheduled()/m_apiLock reads. A further question is whether any of those reads could feed a write or an indirect call. As the primitive stands, it is a racy UAF on a small, fixed-layout GC-internal object whose reads could at most drive lock operations on reclaimed memory. The timer object carries no attacker-controlled fields, so the primitive would likely stay weak. The bug lives in the WebContent process and does not cross the sandbox; a separate escape would be required.
This vulnerability weakens memory safety in the process hosting the JSC VM. Every VM teardown assumes that all helper threads have stopped touching a heap before its members are destroyed. Before the fix, that assumption could fail on the GC conn-handoff path, letting a collector thread touch a destroyed StopIfNecessaryTimer after the owning VM was gone. In the common interleaving the consequence would likely be a reliable RELEASE_ASSERT crash, i.e. denial of service of the renderer or worker host. If the freed timer were touched instead, the consequence would be a use-after-free on a GC-internal timer object. An attacker who could control that window could at most corrupt state inside the same process, which would not by itself breach the sandbox.
Insight: three things stand out. First, this is a regression. Per the commit message, 323479@main removed an early stop, and that stop turned out to be load-bearing for lifetime, not just cleanup. Refactors that move thread ownership into a separate object (here, Collector split out of Heap) tend to lose implicit ordering: the owner used to stop the thread first, but now the stop lives in a member whose destructor runs on declaration order. Second, the conn handoff is a subtle source of this bug class. Once a mutator can complete a collection on the collector's behalf, "the collector processed my Leave" no longer implies "the collector thread has stopped running code for my heap". Third, the fix is two-sided: it stops threads eagerly in shutDown(), and it converts ~Collector's implicit stop into RELEASE_ASSERTs, so any future path that skips shutDown() fails loudly instead of racing silently. --useGlobalGC=true is explicitly left unfixed and still carries this race class until the follow-up lands.
Audit directions
- Thread stopped by a member destructor that runs after sibling members the thread uses. A thread must be quiesced before anything it can touch is destroyed. Narrow: audit JSC classes that own an
AutomaticThread,Thread, or helper-pool client, and check member declaration order against the members the thread body dereferences. Start withHeap(m_localCollectorvs timers, sweepers,m_sharedCollectorMarkStack),JITWorklist,HeapHelperPoolclients, andSamplingProfiler. Wider: the same shape appears whenever the stop/join lives in astd::unique_ptr/UniqueRefmember's destructor rather than in an explicitshutDown()called first, including WTFWorkQueueowners andParallelHelperClient. Widest: any C++ class holding members whose destructors join, such asstd::jthreador Chromiumbase::Thread(whose destructor callsStop()), declared before resources their thread body uses. Plainstd::thread(which terminates if still joinable) and RustJoinHandle(which detaches on drop) do not join on destruction, so they are not this shape. Match tell: a member whose destructor joins a thread, where at least one member destroyed earlier is reachable from that thread's run loop. - Handshake completion is not quiescence. Check every teardown path that waits on a protocol acknowledgement (request processed, flag observed, ticket served) instead of on thread termination, and ask whether the acknowledging thread can keep executing for that owner afterward. Narrow: in
Heap.cppandCollector.cpp, trace each path where a mutator can take the conn (mutatorHasConnBit,waitForCollector(),stopTheMutator()), and enumerate the code the collector thread runs after handing off the conn but before returning topoll(). Wider: worker termination in WebCore (WorkerThreadstop vsWorkerGlobalScopeteardown), and GPU or Networking process connection invalidation that waits for a "done" message rather than thread exit. Widest: Go'sWaitGroup.Done()called before a goroutine's final access, completion handlers fired mid-function, and JavaExecutorService.shutdown()withoutawaitTermination(). Match tell: a signal or notify issued before the signaling thread's last access to shared state. - A join is a lifetime fence, not just cleanup. Review commits that remove or relocate
join(),waitForCompletion(), orstopThread()calls during ownership refactors, and verify that the removed call did not also establish a lifetime ordering. Narrow: diff 323479@main for every other early stop or join it dropped inHeap::shutDown()or VM teardown. Separately, examine the still-unfixeduseGlobalGCpath: thereglobalCollector()is never destroyed andm_localCollectoris null, so no stop occurs at heap teardown. Wider: any refactor that moves thread ownership into a shared or process-wide object (singleton collectors, shared worklists), where the owner can die without the thread ever stopping, so per-owner state needs its own quiescence handshake. Widest: codebases moving from per-instance to shared worker pools, such as V8's isolate-shared GC threads and database connection-pool refactors. Match tell: a refactor diff where ajoindisappears from an owner's shutdown and reappears only in a destructor, or nowhere.