← All reports

[6] WebGPU `Queue::writeTexture` marks slices cleared before the write is emitted

MediumWebGPU Metal backendUninitializedMemory

4d2ad87

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

bool clearWasNeeded = false;
+ const bool writeCompletelyClearsSlice = writeWillCompletelyClear(textureDimension, widthForMetal, logicalSize.width, heightForMetal, logicalSize.height, depthForMetal, logicalSize.depthOrArrayLayers);
+ auto markSliceAsCleared = [&](NSUInteger destinationSlice) {
+ if (writeCompletelyClearsSlice)
+ texture->setPreviouslyCleared(destination.mipLevel, destinationSlice);
+ };
for (uint32_t layer = 0; layer < sliceCount; ++layer) {
...
- if (!texture->previouslyCleared(destination.mipLevel, destinationSlice)) {
- if (writeWillCompletelyClear(textureDimension, widthForMetal, logicalSize.width, heightForMetal, logicalSize.height, depthForMetal, logicalSize.depthOrArrayLayers))
- texture->setPreviouslyCleared(destination.mipLevel, destinationSlice);
- else {
- clearWasNeeded = true;
- clearTextureIfNeeded(destination, destinationSlice);
- }
+ if (!texture->previouslyCleared(destination.mipLevel, destinationSlice) && !writeCompletelyClearsSlice) {
+ clearWasNeeded = true;
+ clearTextureIfNeeded(destination, destinationSlice);
}
}
...
withBytes:byteCast<char>(data.subspan(sourceOffset).data())
bytesPerRow:bytesPerRow
bytesPerImage:0];
+ markSliceAsCleared(destinationSlice);
...
destinationOrigin:destinationOrigin
options:options];
+ markSliceAsCleared(destinationSlice);

Source/WebGPU/WebGPU/CommandEncoder.mm

if (texture.usage().contains(WebGPU::TextureUsage::Transient))
return;
- texture.setPreviouslyCleared(mipLevel, slice);
auto logicalExtent = texture.logicalMiplevelSpecificTextureExtent(mipLevel);
if (!logicalExtent.width)
return;
...
if (slice >= mtlTexture.arrayLength)
return;
+ texture.setPreviouslyCleared(mipLevel, slice);
[blitCommandEncoder
copyFromBuffer:temporaryBuffer
...

LayoutTests/ipc/webgpu-write-texture-unaligned-offset-marks-slice-cleared.html

+ // dataLayout.offset = 2 is legal for writeTexture ... Recording the slice as cleared and then skipping
+ // the write makes copyTextureToBuffer() elide the lazy zero-clear and disclose the poison.
+ writeTextureWithCopy(wholeTexture(texture), new Uint8Array(2 + IMAGE_SIZE).fill(WRITE), wholeImage(2), extent3D(SIZE, SIZE, 1));

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.

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.

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.