JSC] Wasm tail call to a same-instance JS import should use a restore frame
CVE: CVE-2026-113903 · Safari 27.2 · Released October 26, 2026 Impact: Processing maliciously crafted web content may lead to unexpected memory modification Apple's description: A use-after-free issue was addressed with improved memory management. Credit: Eddy Tsalolikhin, OpenAI Codex Security - Amy Burnett, Lily Cohl (@GenericCoding)
High. A same-instance tail call into JS skipped the reload of Wasm's register-cached memory base, so a memory.grow inside the import left the caller addressing the pre-grow buffer. Whether that is a use-after-free or silent divergence depends on what happens to the old backing store.
WebAssembly code in JavaScriptCore does not look up its linear memory on every access. The base address and bounds size live in reserved callee-save registers, and every path back into Wasm code is expected to refresh them if something could have moved the memory. Tail calls break the usual "reload after the call returns" pattern because they discard the caller's frame. JSC compensates by inserting a restore frame, a small frame tagged with RestoreFrameCallee that reloads the instance and memory registers on the way back. The invariant at stake is that this restore frame must be installed whenever the tail-call target can invalidate the cached registers, and not only when the target belongs to a different instance.
The angle: A page running Wasm can make a function's cached memory base outlive a memory grow, so the function's later loads and stores go through the pre-grow buffer instead of the live one.
Source/JavaScriptCore/wasm/WasmBBQJIT.cpp
JSTests/wasm/stress/tail-call-same-instance-js-import-memory-grow.js
Patch Details
The patch widens the condition under which a Wasm tail call installs a restore frame. Previously the only trigger was "the callee's target instance differs from the current wasmInstance." After the fix, a restore frame is also emitted when the callee's boxed callee bits equal WasmToJSCallee::singleton(), meaning the tail call exits to a JS import, even when the target instance is the same. Each execution tier lowers tail calls independently, so the same rule is written three times.
Tier lowering.
- IPInt (
InPlaceInterpreter64.asm,.ipint_tail_call_common). The unconditionalbpeq r1, wasmInstance, .ipint_tail_call_no_restore_framebecomes a two-step test. A different instance branches to the new.ipint_tail_call_check_existing_framelabel, which is the original restore-frame path. A same-instance call loads_g_wasmToJSCalleeBoxedintot4and jumps tono_restore_frameonly ifIPIntCallCalleediffers from it. The comment block about register aliasing (r1==t2on x86_64,r1==t1on ARM64) explains why the new comparison usest4. - BBQ (
BBQJIT::emitIndirectTailCall).Jump isSameInstanceis replaced by a pair of jumps.needsRestoreFrame(instanceNotEqual) jumps straight into the restore path. On fall-through, the importable function'soffsetOfBoxedCallee()is loaded andbranchIfCalleeNotWasmToJSproducesskipRestoreFrame, which jumps pastemitRestoreInstanceFrameIfNeededandloadWebAssemblyGlobalState. - OMG (
OMGIRGenerator::emitIndirectCall, tail-call patchpoint). The patch appendsboxedCalleeCalleeto the patchpoint as aValueRep::SomeRegisterinput atpatchArgsIndex + 2. The comment explains why: the rep thatcreateTailCallPatchpointalready appends isLateColdAnyand may live on the stack, while the new branch needs the value in a GPR. The generator then uses the same instance-or-WasmToJS branch structure ahead of the restore-frame setup and thecageConditionally(Gigacage::Primitive, ...)reload ofwasmBaseMemoryPointerandwasmBoundsCheckingSizeRegister.
Plumbing.
WasmIRGeneratorHelpers.haddsbranchIfCalleeNotWasmToJS(), abranchPtr(NotEqual, …)againstCalleeBits::boxNativeCallee(&WasmToJSCallee::singleton())used by both JIT tiers.WasmCallee.cpp/.hadd anextern "C"global,g_wasmToJSCalleeBoxed, filled insideWasmToJSCallee::singleton()'sstd::call_once. IPInt is hand-written assembly and cannot embed a C++-computed immediate, so it reads this global instead.IPIntPlan::didCompleteCompilationnow eagerly instantiatesWasmToJSCallee::singleton()next toRestoreFrameCallee::singleton()wheneveruseWasmTailCallsis on. That guarantees the global holds the real boxed value before any IPInt code can compare against it. The global is zero-initialized ({ }), so a missing initialization would never match a real callee.
Both JIT tiers carry a FIXME suggesting that WasmCallableFunction::targetInstance could be overloaded to hold a JSFunction for JS-exiting callees. The instance comparison would then fail for JS imports on its own, and the second test could go away.
Test. The new stress test covers return_call, return_call_indirect and return_call_ref, plus a non-tail call_indirect control. All cases run under --useWasmFastMemory=false, and --wasmInliningMaximumWasmCalleeSize=0 keeps $tail as a real call. Each module embeds a unique constant so no two cases share compiled code or tier-up state. The warmArg 0/1 split exercises both a JIT-tiered $tail and one left in IPInt underneath a tiered-up $observe.
Background
Execution tiers. JSC runs WebAssembly in three tiers. IPInt is an in-place interpreter written in JSC's offlineasm dialect, BBQ is a fast baseline JIT, and OMG is the optimizing JIT built on the B3 compiler backend. Hot functions move up the tiers, and each tier generates its own call and tail-call sequences.
Pinned memory registers.
A callee-save register is one that a called function must preserve, so the caller can rely on its value across a call. JSC Wasm reserves several of these for per-instance state. wasmContextInstancePointer holds the current JSWebAssemblyInstance. wasmBaseMemoryPointer holds the linear-memory base address. In bounds-checking mode, wasmBoundsCheckingSizeRegister holds the current memory size used for explicit bounds checks. Wasm loads and stores compute addresses relative to these registers and do not reload them on every access.
Memory modes and the Gigacage.
In MemoryMode::Signaling ("fast memory"), a large virtual reservation backs the memory and guard pages enforce bounds, so growing never moves the base. In MemoryMode::BoundsChecking, the memory is an ordinary allocation guarded by explicit bounds checks, and growing a non-shared memory may allocate a new buffer and copy the old contents into it. Shared memories never move. Wasm memory pointers are also caged: the Gigacage is a reserved virtual region for primitive data buffers, and cageConditionally(Gigacage::Primitive, …) forces a pointer to stay within that region.
Call-boundary reload conventions.
Within one instance, a direct wasm-to-wasm call does not reload the pinned registers on return; the caller assumes the callee left them valid. A normal call to a JS import does reload them afterward, because JS can call memory.grow.
Wasm tail calls.
return_call, return_call_indirect and return_call_ref replace the current frame with the callee's, so the callee returns directly to the tail-caller's own caller. Any code the tail-calling function would have run after the call simply does not exist.
Restore frames.
Because a tail call can switch instances, JSC lazily inserts a small frame tagged with RestoreFrameCallee (emitRestoreInstanceFrameIfNeeded, wasm_restore_frame_return). When the callee returns through it, the frame reloads the instance and memory registers before returning to the real caller. It is inserted lazily so that intra-module tail-call chains stay cheap.
WasmToJSCallee and callee bits.
Every frame records a callee identifying what is running there. WasmToJSCallee is a singleton callee identifying the wasm-to-JS import path. CalleeBits::boxNativeCallee produces the tagged pointer stored in import call metadata, so comparing a callee's boxed bits against the singleton's tells generated code whether a call exits to JS.
Analysis
This is a missing reload on a tail-call return path. The safeguard that refreshes register-cached memory state was keyed on instance identity, which does not capture a same-instance JS import that can move memory.
$observe (wasm) $tail (wasm) $f (JS import)
───────────────── ───────────── ──────────────────────
base=B_old size=S_old
call $tail ────────────► same instance:
(no reload expected) restore frame? NO
return_call $f ──────► mem.grow(1)
[frame gone] realloc: B_old → B_new
copy contents
◄────────────────────────────────────────────── return (no reload)
i32.store / i32.load
via B_old, S_old ✗ ← stale base and bounds
The diagram walks the three frames in the test. $observe makes a plain same-instance call to $tail, which under JSC's convention means $observe will not reload its pinned registers when $tail returns. Normally that is safe: $tail is Wasm in the same instance, so it either leaves the memory alone or, if it calls JS, reloads the registers itself after JS returns. Because $tail performs a return_call to the JS import $f, the middle column's frame no longer exists by the time JS runs. The reload $tail would have executed after the call is gone, and the single safeguard JSC provides for that situation is the restore frame.
All three tiers decided whether to insert that restore frame with one test: targetInstance != wasmInstance. A JS import imported into the same module has the current instance as its target, so it fails the test and the restore frame is skipped. That decision sits at the "restore frame? NO" annotation in the diagram. JS then calls mem.grow(1), and returns along the bottom arrow directly into $observe, which still holds B_old and S_old in its pinned registers.
The test turns that into a concrete trigger:
- Warm up
observe(warmArg)at least 500 times so$observe, and withwarmArg == 1also$tail, tier up and keep the memory base in a pinned register.$fis a no-op during warm-up. - Flip
grown = trueand callobserve(1), which calls$tail, which tail-calls$f. $fcallsmem.grow(1). With a non-shared memory inMemoryMode::BoundsChecking, grow reallocates the backing store and copies the old contents.$fwritesNEW_MARKatLOAD_OFFin the new buffer and clearsSTORE_OFF, because the copy carried over the warm-up'sSTORE_VAL.- Control returns to
$observe, which runsi32.storeatSTORE_OFFandi32.loadatLOAD_OFFthrough its cached base. - Before the fix, the load returns
OLD_MARK, which only exists in the pre-grow buffer, and the store never lands in the live memory.
The call_indirect control case covers the non-tail form through the same funcref. It always reloaded the pinned registers on return and was never affected; its job is to catch a fix that breaks or over-restores the non-tail path.
What those stale accesses amount to depends on the old allocation's lifetime after reallocation. If the pre-grow backing store is released once grow completes, $observe's loads and stores are a use-after-free on the old memory allocation. If the store is kept alive, they are stale-but-mapped accesses that silently diverge from the live memory. In both cases the accesses are bounded by the stale bounds size S_old relative to the stale base B_old: the bounds register went stale together with the base, so the window is exactly the old buffer's extent. Apple's impact line, "unexpected memory modification," matches the freed-buffer reading.
Reachability is broad on the trigger side and narrow on the configuration side. Everything the attacker needs is ordinary web content: a Wasm module with a memory, a JS import that calls memory.grow, and a same-instance return_call, return_call_indirect or return_call_ref to that import. The constraint is the memory mode. The memory must be non-shared and running in BoundsChecking mode, because in Signaling mode grow never moves the base, and shared memories never move at all. The test forces BoundsChecking with --useWasmFastMemory=false. An attacker would need a configuration that lands in that mode.
If the old buffer is freed, the result would be an attacker-indexed read/write primitive over a freed region. Offsets and values come from ordinary i32.load / i32.store, constrained to the stale window. That would be a strong renderer-plane memory-corruption foothold, though escalation depends on reclaiming that region with something worth corrupting. The primitive is also confined to the primitive Gigacage. OMG's reload goes through cageConditionally(Gigacage::Primitive, ...), and the stale base was caged the same way when it was loaded, so the accesses cannot leave the cage. Escaping it would require a separate primitive. If the old buffer stays alive, the effect degrades to an integrity bug: the module's view of memory and the live memory diverge, with no out-of-allocation access. The bug is confined to the WebContent process and does not cross the sandbox; impact beyond the renderer would need a separate escape.
The fix restores the invariant by adding the missing predicate rather than replacing the old one. In BBQ, the instance comparison now branches into the restore path (needsRestoreFrame). On fall-through, the code loads the importable function's boxed callee and skips the restore frame only when that callee is not WasmToJSCallee. OMG mirrors this inside the tail-call patchpoint, after pinning boxedCalleeCallee to a register so the comparison has an operand. IPInt performs the same comparison against _g_wasmToJSCalleeBoxed, and the eager singleton construction in IPIntPlan ensures that global is populated before the interpreter reads it. With the patch, the "restore frame? NO" box in the diagram becomes "YES" for a JS import, and the return from $f passes through wasm_restore_frame_return, which reloads B_new and S_new before $observe runs again.
The restore frame was gated on who the callee was (another instance) instead of what it could do (move memory), so a same-instance JS import returned into Wasm with a stale base.
Insight
JSC already knew that tail calls remove the implicit "caller fixes things up after the call returns" step, and built restore frames for it. The weak point is structural. The rule deciding when a restore frame is needed is hand-written three times, once in IPInt assembly, once in BBQ and once in OMG, with no shared helper or assertion tying them together. The patch had to land in all three, and the test deliberately spans tiers through the warmArg 0/1 split so that an IPInt $tail under a JIT-compiled $observe is exercised as well. Each tier is a separate code generator that must preserve the same pinned-register contract, so per-tier divergence is a recurring risk for this kind of invariant. The two FIXMEs pointing at each other across BBQ and OMG show that the authors know the second check is a patch over an incomplete proxy, not a redesign of it.
Audit directions
-
Register-cached derived state whose refresh depends on a post-call reload. Base pointers, bounds and instance pointers are safe only if every return path into code that trusts them passes through a reload whenever something on that path could invalidate them. Narrow: enumerate every Wasm frame-replacing or frame-skipping path in
InPlaceInterpreter64.asm,WasmBBQJIT.cppandWasmOMGIRGenerator.cpp. For each, check whether the callee can reach JS or a memory-moving builtin without a pending restore: directreturn_callto imports,return_call_reftoWasmBuiltinCallee, exception landing pads andcatchentry, OSR entry, and stack unwinding after athrowfrom JS. Wider: the same shape applies to JIT-cached typed-array vectors or butterfly pointers held across calls that can resize or detach the backing store. Widest: any Wasm engine with a pinned heap-base register faces this question at every tail call and unwind edge, including Wasmtime/Cranelift's pinned heap register, V8 Liftoff/Turbofan's cached memory start, and SpiderMonkey's HeapReg reload after calls. Match tell: a call-site variant (tail, unwind, landing pad) that bypasses the code that normally runs after the call, with no substitute reload installed on the return path. -
Compensating fixups gated on a proxy predicate. Here,
targetInstance != wasmInstancestood in for "the callee may move memory," and the two agree only in the common case. Narrow: audit every caller ofemitRestoreInstanceFrameIfNeededand every IPInt branch to.ipint_tail_call_no_restore_frame. Check whether any remaining same-instance callee kind can still run JS or grow memory. Wider: search JSC Wasm for other fast paths keyed on instance identity orCalleeGroupidentity that skip reloading memory state, such as call-site linking in wasm-to-wasm stubs andcall_refcaching. Widest: look for any optimizer that elides a safety action based on an identity check (same module, same origin, same thread) instead of the capability actually at risk. This includes IC guards in other JITs and capability checks in permission systems. Match tell: a skip condition whose comment or name describes who the callee is rather than what the callee can do. -
One runtime invariant implemented independently in several execution tiers. A fix that lands in one tier but not another reopens the bug at tier boundaries. Narrow: for each Wasm tail-call or restore-frame rule, diff the IPInt asm, BBQ and OMG implementations side by side. Check that IPInt-to-BBQ, BBQ-to-OMG and OSR transitions preserve the same pinned-register contract; the test's
warmArgsplit is a template for this. Wider: apply the same cross-tier consistency review to JSC's LLInt/Baseline/DFG/FTL handling of exception-check placement and structure watchpoints. Widest: any multi-tier VM has the same exposure, including V8 (Ignition/Sparkplug/Maglev/Turbofan) and SpiderMonkey (Baseline/Ion). Match tell: a semantic rule encoded as hand-written branches in more than one code generator, with no shared helper or assertion tying them together.