[6] WebGPU `Queue::writeTexture` marks slices cleared before the write is emitted
Squarely Medium: the same zero-init guarantee as [5], broken by a different ordering slip. The flag was set from a prediction that the upload would cover the slice, and an unaligned offset then skipped the upload. The ceiling is one stale texture slice; cross-context reach depends on IOSurface and Metal pool reuse.
Lazy zero-initialization only holds if "already initialized" bookkeeping is updated after the initializing write happens, never before it. In WebKit's WebGPU backend, Queue::writeTexture — the GPU-process implementation of GPUQueue.writeTexture, which uploads CPU bytes into a texture — consults writeWillCompletelyClear, a predicate deciding whether an upload covers a whole slice, to skip the separate zero-fill. The per-slice cleared flag that gates that zero-fill is supposed to describe memory that has actually been written.
The angle: whoever controls writeTexture parameters can get a slice marked initialized while the upload is skipped, then copy the slice's stale backing-store bytes into a mappable buffer.
Per the commit message (rdar://187344513), setPreviouslyCleared is now deferred until validation completes, since otherwise contents from earlier allocations can leak.
Source/WebGPU/WebGPU/Queue.mm
Source/WebGPU/WebGPU/CommandEncoder.mm
LayoutTests/ipc/webgpu-write-texture-unaligned-offset-marks-slice-cleared.html
Patch Details
Queue::writeTexture computes writeCompletelyClearsSlice once and adds a markSliceAsCleared lambda that sets the flag only when that value is true. The per-slice pre-loop no longer sets the flag; it only decides whether a lazy clearTextureIfNeeded is required (!previouslyCleared && !writeCompletelyClearsSlice). A markSliceAsCleared(destinationSlice) or markSliceAsCleared(0) call now follows every emitted write — the CPU-side -replaceRegion:...withBytes: calls for 1D, 2D and 3D, and the blit-encoder copyFromBuffer:... calls — so only code paths that actually issued a write mark the slice. In CommandEncoder::clearTextureIfNeeded, setPreviouslyCleared moves from the top of the function, ahead of the logicalExtent.width check and other early returns, to just before the zero-fill copyFromBuffer:temporaryBuffer. The Swift mirror in CommandEncoder.swift gets the same move. A new IPC layout test drives crafted RemoteQueue::WriteTextureWithCopy messages with an unaligned offset, plus a GLib skip expectation.
Committing an "initialized" flag before the side effect it certifies has happened, so a later bail-out leaves the flag set over memory never written.
Background
WebGPU lazy zero-initialization. The spec requires textures and buffers to appear zero-filled on first use, even though the underlying GPU memory may be recycled. Implementations usually defer the clear until it is needed rather than clearing eagerly at allocation.
previouslyCleared(mipLevel, slice).
The Metal backend's per-subresource bit recording that a (mip level, array slice) holds defined contents. When false, CommandEncoder::clearTextureIfNeeded encodes a blit from a zeroed temporary buffer into the slice before it is read or partially written.
writeWillCompletelyClear.
Decides whether an upload covers the entire logical extent of a slice; if it does, a separate clear is redundant because the write itself initializes every texel.
Queue::writeTexture paths.
Implements GPUQueue.writeTexture with several encoding paths: a CPU-side -[MTLTexture replaceRegion:...withBytes:] path used when the queue is idle, and staged blit-encoder copyFromBuffer: paths otherwise, each split by texture dimension (1D, 2D, 3D).
Presentation-context textures.
GPUCanvasContext.getCurrentTexture() returns textures backed by IOSurfaces recycled between frames. Per the regression test's comment, PresentationContextIOSurface::getCurrentTexture() resets their cleared bits on each acquisition so recycled content is re-cleared — WebGPU's defence against handing a page last frame's pixels.
Process model.
WebGPU commands are serialized from WebContent over IPC (RemoteQueue, RemoteCommandEncoder, ...) and executed in the GPU process.
Analysis
This is an uninitialized-memory disclosure caused by a state-tracking ordering error.
Before: After:
writeTexture(offset = 2) writeTexture(offset = 2)
pre-loop: full coverage? pre-loop: full coverage?
└─► setPreviouslyCleared(slice) └─► no flag, no clear yet
replaceRegion path replaceRegion path
└─► unaligned offset: write skipped └─► unaligned offset: write skipped
└─► markSliceAsCleared not reached
copyTextureToBuffer() copyTextureToBuffer()
└─► flag set: skip zero-fill └─► flag unset: zero-fill
└─► stale bytes into buffer └─► zeros into buffer
In the left column, writeWillCompletelyClear served as a proxy for "this write will initialize the whole slice", and the flag was committed — and the lazy clear skipped — on that prediction alone. Per the test's comments, the idle-queue replaceRegion path then skipped the write for a dataLayout.offset of 2, which is legal for writeTexture but not a multiple of the texel block size. The commit message frames this as validation not having completed when the bit was set. The slice was left holding its old contents, marked initialized, and never zero-filled.
clearTextureIfNeeded had the same shape in both its C++ and Swift copies: the bit was set before early returns such as !logicalExtent.width and slice >= mtlTexture.arrayLength, so a clear that bailed out still recorded the slice as cleared. The right column moves every state commit to sit immediately after a concrete emitting call, so any bail-out leaves the flag untouched.
The test uses a presentation-context texture backed by a recycled IOSurface. Its comment states that PresentationContextIOSurface::getCurrentTexture() resets previouslyCleared() to false on each acquisition precisely so stale content is re-cleared; this bug defeated exactly that reset. The readback path is copyTextureToBuffer, which the test shows eliding the zero-fill once the flag is set, and the test asserts that the "poison" written earlier is not disclosed.
The result is a reliable, attacker-triggered read of uninitialized texture memory: a bounded info leak of one mip/slice of the attacker's own texture, returned through a mappable buffer. There is no write primitive and no control over which memory backs the texture. The regression test only reads back bytes the same page wrote earlier; a cross-boundary leak would need the IOSurface pool behind PresentationContextIOSurface, or the Metal heap behind ordinary textures, to hand a page memory last owned by a different context, origin or process. That pool's reuse scope sets the ceiling. The bug sits in the GPU process but returns data to the WebContent caller, and it neither crosses the sandbox nor executes code there.
This vulnerability weakens the WebGPU resource-initialization guarantee, a memory-confidentiality boundary. WebGPU requires that no resource ever exposes contents left by earlier allocations, and this implementation enforces that through the per-slice previouslyCleared bit. Before the fix, an attacker controlling writeTexture parameters could leave a slice marked cleared but unwritten and read it back with copyTextureToBuffer, disclosing whatever the backing memory previously held — per the commit message, contents from earlier allocations.
Takeaway: Set an "initialized" bit immediately after the call that actually performs the initialization, never from the predicate that predicted it — and when the function exists in both .mm and .swift, fix the ordering in both.
Audit directions
- Initialization flag committed before the write it certifies. The invariant: a resource-initialization bit may only be set after the initializing write is actually encoded. Narrow: grep
Source/WebGPU/WebGPUforsetPreviouslyCleared(and buffer-side equivalents (initialized-range tracking inBuffer.mm); for each call, check whether anyreturn,breakor validation failure sits between it and the correspondingreplaceRegion/copyFromBuffer/ render-pass clear, starting with callers incopyBufferToTexture,copyTextureToTextureand render-pass load/store handling inCommandEncoder.mm. Wider: anywhere a lazy-init tracker is updated from a predicate — a render pass marking an attachment initialized fromloadOp/storeOpbefore validation,clearBuffermarking ranges zeroed before size checks. Widest: any lazy zero-init scheme with a dirty or valid bitmap — Dawn'sSetIsSubresourceContentInitialized, wgpu'sInitTracker, Vulkan/D3D12 resource-state trackers, OS page-zeroing caches. In code review, a state mutation followed by a fallible operation in the same function with no rollback on the failure path is the shape to flag. - The same invariant duplicated across parallel implementations. Here the C++
.mmand Swift.swiftcopies of one function, where a fix applied to one can be missed in the other. Narrow: diff the C++ and Swift versions ofclearTextureIfNeeded,copyTextureToBuffer,copyBufferToTextureandwriteTexture-adjacent helpers inSource/WebGPU/WebGPU, looking for different ordering of state updates and early returns. Wider: any WebKit component mid-migration between languages or backends, such as WebGPU Swift bridging and other@_expose(Cxx)bridges. Widest: any codebase with duplicate fast/slow paths or platform-specific copies of a security check, such as Dawn's per-backend implementations. Tell: two functions with the same name or contract where a guard or state write sits at a different position relative to the early returns. - Read-back paths that trust the cleared bit with no independent check. Ask whether
copyTextureToBuffer, texture-to-texture copy, or bind-group texture sampling rely solely onpreviouslyCleared()to decide whether to zero-fill. Narrow: trace each consumer ofpreviouslyClearedinCommandEncoder.mm/.swiftand in bind-group / render-pass setup. Wider: for presentation textures, check that every acquisition and resize path inPresentationContextIOSurfaceresets the bits, and that reconfiguring or recreating render buffers cannot bypass the reset. This class is bound to WebKit's own IOSurface-recycling model; the transferable lesson is covered by the first direction. Tell: a path that acquires or reuses a backing allocation without resetting its initialization state.