[5] WebGPU encode-time clear tracking trusted by never-submitted command buffers
WebGPU let a command buffer that never ran vouch that a texture was already zeroed.
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
Source/WebGPU/WebGPU/CommandBuffer.mm
LayoutTests/fast/webgpu/texture-lazy-clear-forged-by-unsubmitted-encoder.html
Patch Details
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.
Background
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.
Analysis
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.
Audit directions
- State recorded as done at encode or enqueue time instead of at commit time. The invariant: a fast path may only trust a completion flag set by work guaranteed to have executed. Narrow: grep
Source/WebGPU/WebGPUfor other per-resource flags mutated insideCommandEncoder,RenderPassEncoder,ComputePassEncoderorRenderBundleEncodermethods — buffer initialization or clear tracking, query-set reset state, indirect-validation caches likem_skippedDrawIndexedValidationKeys— and check whether each is deferred to anaddOnCommitHandleror rolled back ondiscardCommandBuffer/makeInvalid. Wider: any record-then-replay API layer — WebGL/ANGLE deferred clears, RenderBundle replay, Dawn's and wgpu's subresource-initialization tracking. Widest: any system mutating an "applied" bit at enqueue rather than commit, such as Vulkan or D3D12 resource-state trackers and database write-behind caches. In code review, a setter on shared resource state called from an encoding method with no matching undo on the encoder's abandon or invalid paths is the tell. - Commit paths that bypass the central pre-commit hook. When correctness depends on
CommandBuffer::preCommitHandlerrunning before every GPU commit, any direct commit that skips it reintroduces the bug. Narrow: trace every caller ofQueue::commandBufferWithDescriptorand everycommiton anMTLCommandBufferoutsideQueue::submit— presentation,copyExternalImageToTexture, XR projection layers, the queue's own staging buffer — and confirm each callsresolveProvisionalTextureClearsor provably cannot read a provisionally claimed slice. Wider: any subsystem with a flush-hook invariant, such as WebGLflushpaths or Canvas2D GPU-backed flushes. Widest: any codebase enforcing a transactional invariant in one dispatcher while resources can be committed through side doors — ORMs with raw-SQL escape hatches, kernel I/O paths bypassing a block-layer barrier. Tell: a commit call site with no reference to the hook or the state it reconciles. - Ordering between queue-side staging work and user-submitted command buffers. Check that clears or writes encoded on
Queue's private blit encoder execute before (or after, as required) the user buffer they protect, and that deferred catch-up clears can never land on top of later-written data. ExamineQueue::finalizeBlitCommandEncoderand the queue-sidewriteTexture/writeBufferpaths for cases where the staging buffer commits after the submitted buffer and would overwrite or miss user data. Wider: any API offering both immediate queue writes and deferred encoded work on the same resource, such as DawnQueue::WriteTextureor Vulkan transfer queues with semaphores. Widest: any producer/consumer pair sharing a resource across two submission streams, such as CPU write-combining buffers flushed alongside DMA descriptors. Tell: two command streams touching the same subresource with ordering implied only by CPU call order rather than explicit commit order or a fence; verification likely needs runtime readback tests like this commit's, not static review alone.