← All reports

[5] WebGPU encode-time clear tracking trusted by never-submitted command buffers

MediumWebGPU Metal backendUninitializedMemory

WebGPU let a command buffer that never ran vouch that a texture was already zeroed.

0a45668

Medium. Script can forge "this texture is already zeroed" with work that never runs and deterministically read back as-allocated GPU memory. It stays Medium because the leak is read-only and its sensitivity rests on how the Metal allocator recycles memory, which nothing here pins down.

GPU APIs exposed to the web promise that a fresh texture reads as all zeros, and implementations usually keep that promise lazily, clearing a region only right before its first read. In WebKit's WebGPU backend, a per-slice flag on each Texture — the GPU-process wrapper around a Metal texture — records which (mip level, array slice) pairs are already initialized, and clearTextureIfNeeded, the helper that encodes a zero-fill blit, skips any slice whose flag is set. WebGPU also separates recording commands into an encoder from submitting them to the queue, so the flag is only trustworthy if the work that set it actually executes.

The angle: a page can record a full-coverage copy it never submits, leave the slice marked as cleared, and read the texture's as-allocated GPU memory back through a mappable buffer.

Per the commit message (rdar://187343075), encoding a render pass that was never submitted exposed a logic flaw in tracking which textures were zero-initialized; the fix stops assuming a texture is cleared until its work is submitted.

Source/WebGPU/WebGPU/CommandEncoder.mm

@@ -1257,7 +1259,7 @@
if (Queue::writeWillCompletelyClear(textureDimension, widthForMetal, logicalSize.width, heightForMetal, logicalSize.height, depthForMetal, logicalSize.depthOrArrayLayers))
- destinationTexture->setPreviouslyCleared(destination.mipLevel, destinationSlice);
+ destinationTexture->setProvisionallyCleared(destination.mipLevel, destinationSlice, *this);
else
clearTextureIfNeeded(destination, destinationSlice);
...
if (!blitCommandEncoder || texture.previouslyCleared(mipLevel, slice))
return;
...
- texture.setPreviouslyCleared(mipLevel, slice);
+ if (owningCommandEncoder)
+ texture.setProvisionallyCleared(mipLevel, slice, *owningCommandEncoder);
+ else
+ texture.setPreviouslyCleared(mipLevel, slice);
...
clearTracking();
+ m_device->getQueue()->discardProvisionalTextureClears(m_uniqueId);
m_device->removeCommandEncoder(m_uniqueId);

Source/WebGPU/WebGPU/CommandBuffer.mm

if (RefPtr commandEncoder = m_commandEncoder) {
auto& commandEncoderRef = *commandEncoder;
+ m_device->getQueue()->resolveProvisionalTextureClears(commandEncoderRef.uniqueId());
for (auto& function : m_preCommitHandlers)
result = function(*this, commandEncoderRef) && result;
- }
+ } else
+ m_device->getQueue()->resolveProvisionalTextureClears();

LayoutTests/fast/webgpu/texture-lazy-clear-forged-by-unsubmitted-encoder.html

+ // The copy is finished but never submitted, so nothing it recorded ever runs and the read still has to see the
+ // lazy zero clear.
+ let forged = newTexture();
+ recordFullCopy(forged).finish();
+ window.forgedRead = await read(forged);
...
+ shouldBeEqualToString('forgedRead', '0');

The change adds a provisional layer of clear-tracking state to Texture and Queue, switches every encode-time "cleared" write onto that provisional layer, and reconciles it at submit time and on every abandonment path.

The new state: Texture gains m_provisionalClears, a HashCountedSet<uint64_t> keyed by provisionalClearKey(mipLevel, slice) and separate from the durable m_clearedToZero, plus setProvisionallyCleared, promoteProvisionalClear, dropProvisionalClear, discardProvisionalClear and a private durablyCleared. previouslyCleared(mip, slice) now returns true if a slice is durably cleared or has any outstanding provisional claim, which keeps de-duplication working inside one encoder. Queue gains m_provisionalTextureClears, a vector of { ThreadSafeWeakPtr<Texture>, mipLevel, slice, commandEncoderId }, managed by addProvisionalTextureClear, removeProvisionalTextureClears, discardProvisionalTextureClears and resolveProvisionalTextureClears.

The call sites: every encode-time marker in CommandEncoder.mm, CommandEncoder.swift and RenderPassEncoder.mm now calls setProvisionallyCleared(..., encoder) — render-pass attachment, resolve-target and depth/stencil clears, the two writeWillCompletelyClear full-coverage fast paths (by variable names, the copyBufferToTexture and copyTextureToTexture destinations), and the attachment marking in RenderPassEncoder.mm. The static clearTextureIfNeeded gains an owningCommandEncoder parameter: non-null records a provisional claim; null (queue-side callers) keeps the durable setPreviouslyCleared.

Reconciliation: CommandBuffer::preCommitHandler calls resolveProvisionalTextureClears(encoderId), promoting the committing encoder's claims to durable; for every other encoder's outstanding claim it drops the texture-side flag, re-queues the entry, and encodes a zero-clear on the queue's own blit encoder if the slice is not otherwise cleared. PresentationContextIOSurface resolves before its direct compute-pass commit. Claims are discarded in ~CommandEncoder, discardCommandBuffer, the encoder invalidation path that sets m_lastErrorString (plausibly CommandEncoder::makeInvalid), and CommandBuffer::makeInvalid; a Queue.mm teardown path (plausibly Queue::makeInvalid) drains the whole provisional list via std::exchange and drops each live texture's claim directly. The queue-side writeTexture calls discardProvisionalClear on its destination slice before deciding whether a clear is needed.

Recording an effect as completed at enqueue time rather than commit time, so abandoned work leaves state that later fast paths trust to skip mandatory initialization.

Encoding vs. submission. A GPUCommandEncoder records commands (copyBufferToTexture, beginRenderPass, ...) into a command buffer, and finish() seals it into a GPUCommandBuffer. Nothing executes on the GPU until device.queue.submit([...]) commits it, and a finished buffer may be submitted later, never, or rejected by validation (e.g. the same buffer twice).

Zero-initialization and lazy clearing. The WebGPU spec requires new textures to behave as if every texel is zero. WebKit's Metal backend tracks initialized (mipLevel, slice) pairs in Texture::m_clearedToZero; before any operation that could read an uninitialized slice, CommandEncoder::clearTextureIfNeeded checks previouslyCleared(mip, slice) and, if false, encodes a blit from a zeroed temporary buffer.

Skipping redundant clears. Operations that fully overwrite a slice can skip the clear and mark it initialized directly — a copy covering the whole extent (checked by Queue::writeWillCompletelyClear) or a render pass with loadOp: clear.

Queue-side staging and the pre-commit hook. Queue owns its own staging command buffer and blit encoder for queue-side writes like queue.writeTexture. CommandBuffer::preCommitHandler runs immediately before a submitted buffer is committed to the MTLCommandQueue.

Weak references. ThreadSafeWeakPtr<T> is a WTF weak reference that returns null once the target is destroyed, letting the queue reference textures without extending their lifetime.

This is a logic error in resource-state tracking whose consequence is an uninitialized-memory read.

  Before:
  encoder A: full copy into slice  ─► setPreviouslyCleared   [durable]
  A finished / dropped / rejected  ─► recorded copy never runs
  encoder B: copyTextureToBuffer   ─► clearTextureIfNeeded: flag set, skip
  submit(B)                        ─► reads as-allocated memory   LEAK

  After:
  encoder A: full copy             ─► setProvisionallyCleared(slice, A)
  A dropped/invalid                ─► discardProvisionalTextureClears(A)
  A merely unsubmitted             ─► claim still pending
  submit(B): preCommitHandler      ─► resolve(B): drop A's claim,
                                      queue blit encodes zero-clear
  B reads                          ─► zeros

The "Before" rows show the missing invariant: a slice may be recorded as initialized only once the work that initializes it is guaranteed to execute. Encoders set the durable flag at encode time; the commands that write the texels lived only in that encoder's MTLCommandBuffer and ran only if queue.submit committed it. No path rolled the flag back when the encoder was abandoned, so a later, genuinely submitted read saw previouslyCleared == true in clearTextureIfNeeded and returned before encoding the zero-fill. The test exercises three abandonment routes: finish() without submit, dropping the encoder unfinished, and a submit rejected because the same buffer appears twice.

The forged flag also misled queue-side writes: a queue.writeTexture covering only part of a forged slice skipped its clear, leaving the uncovered region uninitialized (the test's partlyWrittenAfterForge case, which also checks the restored clear is ordered before the write).

The "After" rows introduce a debt an unsubmitted encoder "owes", and the test guards against it misbehaving. writtenAfterForge: a fully covering writeTexture initializes the slice itself, so the owed clear must not land on top of it — the queue write path's discardProvisionalClear prevents that. beforeDeferredCopyRead / afterDeferredCopyRead: a copy finished before a read but submitted after it must not be visible to the read, and must survive the zero-clear that read needed. The beforeDeferredCopyRead == "0" expectation requires the queue's catch-up clear to execute before the committing buffer's read; that ordering rests on Queue::finalizeBlitCommandEncoder committing the staging buffer ahead of the user MTLCommandBuffer, a condition the test asserts but the change does not itself establish. Likewise, the rejected double-submit case reaching a discard path is shown by the test's expected outcome rather than by the Queue::submit validation code.

Exploitation is reliable through the standard WebGPU API: the test's description states that a later submitted copyTextureToBuffer "trusted the flag and skipped the lazy zero clear", and each forged case asserts an all-zero read. A skipped clear returns the texture's as-allocated contents — prior data, if Metal/IOGPU allocations aren't zero-filled on allocation, which is the premise the lazy-clear design exists for. The primitive is per texture slice, up to device maximum dimensions and array layers, in attacker-chosen size and format, freely repeatable, with uncontrolled contents. It's not a write or control-flow primitive; it could serve as a pointer or ASLR leak only if non-pixel GPU-process data shared the same backing pages, which the supplied context does not establish. The open escalation question is whether texture allocations come from a pool shared across WebGPU devices, origins or processes, and whether size or format choices could steer reuse. The tracking lives in the GPU process and leaked bytes return to WebContent via buffer mapping; no code execution or control-sandbox crossing is involved, but residual memory from outside the attacker's context would cross a data-isolation boundary.

This vulnerability weakens the WebGPU resource zero-initialization guarantee, a memory-isolation boundary. WebGPU assumes web content can never observe the prior contents of GPU memory backing a new texture. Before the fix, script could forge the "already cleared" state without any write executing and read the texture back via mapAsync, returning whatever the Metal allocation held — and if the allocator recycled memory that previously held another page's, origin's or process's rendered content, that would expose cross-origin or cross-process pixel data.

Insight: This is a classic optimistic-commit flaw, and the fix's interesting part is the cross-encoder case: once encoders interleave, even correct commit-time promotion is insufficient, so the queue must emit catch-up clears for slices claimed by other still-pending encoders. The PresentationContextIOSurface hunk shows the hook every future direct commit to the MTLCommandQueue must remember, since anything bypassing preCommitHandler silently reintroduces the bug. [6] below is the same guarantee broken by a sibling ordering slip in the same week.