Skip to main content
coreydaley.dev

A dangling withUnsafeBytes pointer broke every Brotli file over 64 KiB

Until May 29, Purrchiver’s engine couldn’t open any Brotli (.br) file larger than about 64 KiB compressed. The error was:

Brotli stream processing failed

Small files worked fine. The files that failed are the ones Brotli is mostly used for: precompressed web assets of the kind nginx and Cloudflare serve. Creating large .br files had the same bug. The cause was one Swift pattern that looks correct and isn’t.

The bug

Purrchiver decoded Brotli with Apple’s Compression framework, which streams through a C struct, compression_stream. You point src_ptr at some input, set src_size, and call compression_stream_process in a loop. Each call consumes some input, advancing src_ptr and shrinking src_size, and writes some output. When the input runs out, you refill it.

The refill looked like this:

if stream.src_size == 0, let chunk = try input.read(upToCount: 64 * 1024) {
    inputBuffer = chunk
    inputBuffer.withUnsafeBytes { raw in
        stream.src_ptr = raw.baseAddress!.assumingMemoryBound(to: UInt8.self)
        stream.src_size = raw.count
    }
}
// ...later, outside the closure:
compression_stream_process(&stream, flags)

The pointer withUnsafeBytes hands you is only valid inside the closure. This code saves it in a struct that outlives the closure, and the C library goes on reading through it on every later process call. Keeping the Data in a variable doesn’t help, because Swift promises nothing about where its bytes live once the closure returns. Storing that pointer is undefined behavior, whatever it happens to do at runtime.

Why only over 64 KiB? A small file arrives in a single read, and every call that consumes it happens while that one buffer is still sitting where it was. The pointer was invalid in principle but still worked by luck. A larger file needs a second read, so inputBuffer gets reassigned, and from then on the decoder is reading memory that no longer holds the input. The Brotli decoder sees garbage and returns an error. The encode loop had the same pattern.

The fix

Give the stream memory whose lifetime you control, and copy each chunk into it:

let srcBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: chunkSize)
defer { srcBuf.deallocate() }

if stream.src_size == 0, let chunk = try input.read(upToCount: chunkSize), !chunk.isEmpty {
    chunk.copyBytes(to: srcBuf, count: chunk.count)
    stream.src_ptr = UnsafePointer(srcBuf)
    stream.src_size = chunk.count
}

The buffer lives for the whole function, the C library can hold on to it across as many process calls as it likes, and the copy costs very little next to the decompression. The same change went into the encoder, and a regression test now decodes a committed Brotli file of about 200 KB and compares every byte.

The general rule: if a C API keeps a pointer after the call returns, the pointer can’t come from withUnsafeBytes, withUnsafeBufferPointer, or & on a Swift value. Those are only for calls that finish before the closure does. compression_stream, z_stream, and most streaming codec structs keep the pointer.

How it was found: test against the real tools

Brotli read had no unit test at all, which is how this shipped. But a unit test written by the same person who wrote the codec probably wouldn’t have caught it either. That person tends to pick a small, convenient input, and a small input hides this bug.

What caught it was a new suite with one job: prove that Purrchiver’s output works in the standard tools, and that the standard tools’ output works in Purrchiver. For every format, the suite round-trips through the native command-line tool in both directions and compares bytes:

  • Ours to theirs. Purrchiver writes the archive, the native tool (gzip, xz, zstd, brotli, 7zz, zip, and so on) extracts it, and the result is compared to the original files byte for byte.
  • Theirs to ours. The native tool creates the archive, Purrchiver reads it, and the same comparison runs.

A few choices made the suite useful:

  • The input is big enough. The single-file tests use a 256 KiB pseudo-random blob that barely compresses, so the .br file is about 256 KiB and the decoder has to refill its input several times. The folder tests use enough files to push ZIP onto its parallel path.
  • It runs the code the app ships. Writes go through the same compressor the app calls, including the parallel ZIP merge, and reads go through the same reader. A test harness that called the codec some other way could have missed this.
  • A missing tool skips the test; it doesn’t fail it. Each test checks that its tool is installed, so the suite runs on any machine and reports what it could check.
  • It covers encryption too. ZIP with AES, 7z with AES, and Apple Encrypted Archive go both ways, including wrong-password cases. Read-only formats like RAR, CAB, and LHA get the theirs-to-ours direction against fixtures.

It runs as its own target, separate from the fast unit tests, and as its own job in CI. It started with 58 tests. The Brotli bug is what it caught, and the fix landed alongside the suite.

What to take away

  • A stored pointer from withUnsafeBytes is a bug even when tests pass. The tell is a C struct field being assigned inside the closure.
  • Test with inputs bigger than your buffer. Chunked code has one path for the first chunk and another for every later one, and small inputs only exercise the first.
  • Your own reader agreeing with your own writer proves very little. Compare against the tools everyone else uses, in both directions.

Related posts