[6] JSC Wasm Memory grow UAF on concurrently-read MemoryHandle
Growing a WebAssembly.Memory could free its handle under a JIT or GC thread.
Medium. A real cross-thread UAF that script can reach, but the attacker has to win a race against a compiler or GC thread and then reclaim the freed handle before that thread reads it; the regression tests are explicitly probabilistic.
WebAssembly linear memory in JavaScriptCore is shared state: the script thread grows it, while background compiler and garbage-collector threads inspect it at the same time. A Wasm::Memory, the engine object behind WebAssembly.Memory, reaches its allocation through a BufferMemoryHandle, a thread-safe refcounted record of base pointer, size and mode. Concurrent readers rely on the handle reachable from a live memory being the same valid object for as long as that memory lives.
The angle: script that grows a bounds-checking WebAssembly.Memory while JSC is compiling or marking it can free the BufferMemoryHandle out from under a background thread that is about to read it.
[JSC] Update MemoryHandle in place when growing non-shared bounds-checking memory
MemoryHandlehas four possible configurations determined by its two modes: non-shared/shared and bounds-checking/signaling. In one of them, non-shared bounds-checking, growing a Wasm Memory replaced the underlyingMemoryHandlewith a new one representing the larger allocation. That replacement is a problem because aMemoryHandleis also accessed by JIT and GC threads. The other three modes never replace the handle associated with a Wasm Memory.This patch updates the same
MemoryHandleinstance in place with the new allocation, bringing that mode in line with the other three and avoiding the race.Tests:
JSTests/stress/wasm-memory-grow-races-ftl-call-wasm-mode-read.js,JSTests/stress/wasm-memory-grow-races-gc-marking-size-read.js(marked slow).
Source/JavaScriptCore/wasm/WasmMemory.cpp
Source/JavaScriptCore/wasm/WasmMemory.h
Source/JavaScriptCore/runtime/BufferMemoryHandle.cpp
Patch Details
The change replaces handle reseating in Memory::grow with an in-place swap of the handle's backing allocation, locks the handle's identity in at compile time, and simplifies the ArrayBuffer refresh path that no longer needs to chase a new handle.
In Memory::grow's non-shared BoundsChecking path, the code used to build a new BufferMemoryHandle, move the instance anchors over with transferAnchors, and reassign m_handle. It now calls BufferMemoryHandle::replaceAllocatedMemory(newMemory, desiredSize), which RELEASE_ASSERTs Default/BoundsChecking mode, rewrites m_memory, m_mappedCapacity and the atomic m_size (via updateSize), returns the old physical-byte charge with freePhysicalBytes(oldSize), and frees the old virtual pages. transferAnchors is deleted, and Wasm::Memory::m_handle becomes const Ref<BufferMemoryHandle>.
On the supporting side, the null-base-pointer special case in ~BufferMemoryHandle becomes a static helper, freeVirtualPagesUnlessNullBasePointer. ArrayBufferContents::refreshAfterWasmMemoryGrow and ArrayBuffer::refreshAfterWasmMemoryGrow lose their Wasm::Memory* parameter because the buffer's handle is now the same object as the memory's handle, and the caller in JSWebAssemblyMemory::growSuccessCallback is updated. A SaferCPP expectation line for wasm/WasmMemory.h is removed. Two slow stress tests race mem.grow(1) against FTL tier-up of callers strength-reduced to CallWasm, and against --collectContinuously=1 marking over 256 live memories.
Reseating a shared refcounted member on one thread while other threads dereference it through the owner without their own reference, so the last ref can drop between pointer load and field read.
Background
WebAssembly.Memory and its handle.
In JSC, a WebAssembly.Memory is backed by Wasm::Memory, which holds a BufferMemoryHandle. The handle is ThreadSafeRefCounted and describes one allocation: base pointer m_memory, atomic m_size, m_mappedCapacity, initial/maximum page counts, a MemorySharingMode (Default or Shared) and a MemoryMode (BoundsChecking or Signaling).
Signaling vs. BoundsChecking.
Signaling mode reserves a large virtual region with guard pages and relies on hardware faults to catch out-of-bounds Wasm accesses. BoundsChecking mode emits explicit bounds checks against the current size. BoundsChecking is used when fast-memory reservations are disabled (--useWasmFastMemory=0), unavailable on the platform, or exhausted (BufferMemoryManager::m_maxFastMemoryCount).
Memory::grow.
Grow enlarges the memory, then invokes a grow-success callback, which JSWebAssemblyMemory::growSuccessCallback uses to detach or refresh any associated ArrayBuffer.
ThreadSafeRefCounted and Ref.
The object is destroyed when its atomic refcount reaches zero. A raw pointer or reference obtained through another object's Ref member does not itself contribute a count.
Concurrent compilation.
DFG/FTL compilation runs on background worklist threads concurrently with the JS mutator, and those threads may read runtime objects referenced from the graph. In DFG strength reduction, a call to a constant-folded WebAssemblyFunction can become a CallWasm node, which FTL lowers to a direct JS-to-Wasm call; per the commit message, that lowering reads the callee memory's mode.
Concurrent marking.
JSC's GC can mark concurrently and in parallel. Marking threads run visitChildren on live cells and may read native-side state while the mutator keeps running.
Analysis
This is a cross-thread use-after-free on the BufferMemoryHandle object: a data race between the mutator reseating a refcounted member and helper threads that read it without taking a reference.
Mutator (JS) FTL plan / GC marker
------------ --------------------
h = memory.m_handle.ptr() (no ref)
mem.grow(1)
BoundsChecking + Default path
newHandle = new BufferMemoryHandle
m_handle = move(newHandle)
old handle refcount -> 0
~BufferMemoryHandle: free pages
free(handle)
h->m_mode / h->m_size <- UAF read
In the diagram, the right column loads the handle pointer and then dereferences it; the left column drops Memory's reference in between. In this configuration the other possible holders were the resizable ArrayBufferContents::m_memoryHandle, which refreshAfterWasmMemoryGrow itself reseated to the new handle, and a protectedHandle captured in a fixed-length buffer's destructor task. The GC-marking test never touches .buffer, so there the old handle's only owner was Memory, and the reassignment destroyed it: the destructor freed the old pages through Gigacage::freeVirtualPages, then the handle object itself was deallocated. Per the commit message and the test names, the two readers are the concurrent FTL compiler reading the memory's mode while lowering CallWasm, and GC marking threads reading the handle's size (for example for extra-memory reporting).
After the fix, the handle's identity is constant and only its interior changes. Reads of m_mode and m_sharingMode land on a live object and those fields are never written after construction, and m_size is std::atomic.
The regression tests are the trigger recipe:
- The FTL test runs
mem.grow(1)repeatedly while callers of a Wasm export tier up under--useConcurrentJIT=true, so DFG strength-reduces them toCallWasmand an FTL plan reads the memory's mode on a worklist thread. - The GC test keeps 256 live memories and grows them under
--collectContinuously=1, so marking threads keep visitingJSWebAssemblyMemorycells and reading handle size. - For the race to matter, the memory has to be in BoundsChecking mode. The GC test does not pass
--useWasmFastMemory=0, so whether its memories land there depends on fast-memory exhaustion againstmaxNumWasmFastMemories. - Both tests are slow and probabilistic, and pay off across many ASan runs.
Exploitability is gated by winning a narrow cross-thread race against an FTL plan or GC marker; the demonstrated consequence is a read of a freed BufferMemoryHandle's m_mode/m_size. What a reclaimed handle slot would let an attacker influence depends on how FTL's CallWasm lowering consumes the mode it reads, which is the open question for escalation.
This vulnerability weakens memory safety inside the WebContent process at the boundary between the JS mutator and JSC's concurrent helper threads. JSC assumes objects reachable from a live Wasm::Memory stay valid while compiler and marking threads inspect them, and before the fix that did not hold for the handle in non-shared bounds-checking mode. The demonstrated consequence is a cross-thread read of a freed BufferMemoryHandle.
Insight: Making m_handle a const Ref turns an implicit rule the other three configurations already followed into one the compiler enforces. The fix also changes lifetime semantics: old pages are now freed inside replaceAllocatedMemory rather than in the old handle's destructor, so a Ref<BufferMemoryHandle> no longer pins the old backing. Whether every holder of a cached base pointer (fixed-length ArrayBuffer destructor tasks, anchor-refreshed instance caches, off-thread readers of m_memory) is detached or refreshed before that free is the property to check.
Audit directions
- Refcounted members reseated by the owner while other threads read them through the owner without their own ref. An object reachable from a GC cell or a compiler-visible runtime object must either keep a stable identity or be read by concurrent threads only through a ref they hold. Narrow: grep JSC for non-const
Ref</RefPtr<members on objects that DFG/FTL plans orvisitChildrenread off-thread, such asWasm::Instance,Wasm::Table,Wasm::CalleeGroupandJSWebAssemblyModule, and look for any reassignment on the mutator. Match: a member assignment on the main thread plus a dereference in a*Plan,Lower*, orvisitChildren/visitAdditionalChildrenpath with no ref taken and no cell lock held. Wider: the same shape appears withstd::unique_ptrmembers replaced viareset(),Vectorreallocation under concurrent readers, andWriteBarrierslots whose pointee carries native state freed on replacement. Widest: any runtime with concurrent JIT or GC threads has this class, for example V8's background TurboFan reading heap-adjacent native handles or HotSpot's concurrent compiler readingMethod/ConstantPoolmetadata; those runtimes use explicit handle scopes or safepoint-deferred frees, so if a codebase lacks such a mechanism, ask whether any replaced object is freed before helper threads reach a safepoint. - In-place reallocation moving the hazard from the handle to its interior pointer.
replaceAllocatedMemorywrites the non-atomicm_memoryandm_mappedCapacityand frees the old pages immediately, so any off-thread or cached reader ofmemory()is the new candidate. Narrow: enumerate callers ofBufferMemoryHandle::memory(),Memory::basePointer()andmappedCapacity()reachable from JIT worklist threads, signal handlers (isInGrowableOrFastMemory), or GC, then confirm every holder of the old base pointer is refreshed through anchors or the grow-success callback beforefreeVirtualPagesUnlessNullBasePointerruns. Match: a base pointer captured beforegrowand used after it, relying on aRef<BufferMemoryHandle>to keep the bytes alive. Wider: the same shape inSharedArrayBufferContents, resizableArrayBufferviews, and typed-array vector caching. Widest: any container that swaps its buffer in place but frees the old one eagerly, such asrealloc-style buffers behindunsafealiasing in Rust orstd::vectorgrowth with outstandingdata()pointers. - Configuration matrices where one cell departs from a shared invariant. Review the remaining
MemorySharingModexMemoryModepaths for any operation that behaves differently in exactly one of the four configurations. Narrow: inspectMemory::grow,growShared,tryCreate,createZeroSizedand~BufferMemoryHandleswitch arms for per-cell differences in identity, ownership, or freeing order. Wider: apply the same matrix audit toArrayBufferContents(shared vs. non-shared, fixed vs. resizable) and to Wasm tier codegen that branches onMemoryMode. Match: a switch arm whose side effects (reallocation, deallocation, pointer reseating) do not occur in sibling arms. Widest: any system with a configuration matrix and concurrent consumers can hide one divergent cell, for example storage engines with per-mode page swapping or allocators with per-size-class release paths.