← All reports

[2] Collector thread outlives its heap during JSC VM teardown

MediumJSC Heap / CollectorUAF

JSC's collector said goodbye to its heap, then kept working on it

eaf0efa

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():

  1. 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 setting mutatorHasConnBit.
  2. The mutator thread, inside waitForCollector(), sees it has the conn, finishes the collection, and processes its own Leave request.
  3. The collector thread has not yet returned from m_stopIfNecessaryTimer->scheduleSoon(), which uses Heap state.
  4. According to the commit message, the mutator then continues through ~VM, which unregisters the VM from JSRunLoopTimer::Manager, and ~Heap destroys m_stopIfNecessaryTimer before m_localCollector, so ~Collector joins the collector thread too late.
  5. The collector thread accesses the freed m_stopIfNecessaryTimer, or hits the RELEASE_ASSERT in JSRunLoopTimer::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

dataLogIf(Options::logGC(), "left the collector, ");
}
 
+ if (m_localCollector) {
+ m_localCollector->shutDown();
+ dataLogIf(Options::logGC(), "stopped the collector's threads, ");
+ }
+
if (Options::dumpHeapStatisticsAtVMDestruction()) [[unlikely]]

Source/JavaScriptCore/heap/Collector.cpp

Collector::~Collector()
{
- ASSERT(m_heaps.isEmpty());
+ RELEASE_ASSERT(m_heaps.isEmpty());
+ RELEASE_ASSERT(!m_collectContinuouslyThread);
+ {
+ Locker locker { *m_threadLock };
+ RELEASE_ASSERT(m_threadShouldStop);
+ }
+ m_raceMarkStack->clear();
+}
+
+void Collector::shutDown()
+{
stopCollectingContinuously();
stopThread();
- m_raceMarkStack->clear();
}
...
void Collector::stopCollectingContinuously()
RefPtr { m_collectContinuouslyThread }->waitForCompletion();
+ m_collectContinuouslyThread = nullptr;
}

JSTests/stress/many-agents-teardown.js

+//@ runDefault("--collectContinuously=1", "--collectContinuouslyPeriodMS=0.1")
+for (let i = 0; i < rootAgents; i++)
+ $.agent.start(rootSource); // each root starts up to 32 leaf agents queuing setTimeouts

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.

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.

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:

The stress test is a distilled reproduction:

  1. Run with --collectContinuously=1 --collectContinuouslyPeriodMS=0.1, so every heap's collector is almost always mid-collection.
  2. Start 16 root agents, each of which starts up to 32 leaf agents. That produces hundreds of independent VMs.
  3. 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.
  4. 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.