Skip to content
HN On Hacker News ↗

Right Code, Wrong Comment: The Pointer Chase Inside zlib

▲ 10 points • 5 comments • by dataisland99 • 5d ago • HN discussion ↗

Pangram verdict · v3.3

We believe that this text is a mix of AI and human-written content.

80 %

AI likelihood · overall

AI
20% human-written 80% AI-generated
SEGMENTS · HUMAN 5 of 23
SEGMENTS · AI 18 of 23
WORD COUNT 1,607
PEAK AI % 100% · §3
Analyzed
Nov 22
backend: pangram/v3.3
Segments scanned
23 windows
avg 70 words each
Distribution
20 / 80%
human / AI fraction
Verdict
AI
Pangram v3.3

Article text · 1,607 words · 23 segments analyzed

Human AI-generated
§1 Human · 0%

At zlib/trees.c:945, inside the inner loop of compress_block, sits a single assertion: /* Check for no overlay of pending_buf on needed symbols */ #ifdef LIT_MEM Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow"); #else Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); #endif In every release build of zlib (#ifndef ZLIB_DEBUG), Assert preprocesses to whitespace.

§2 AI · 100%

Neither compress_block, nor send_bits, nor put_byte checks whether s->pending has room before writing to s->pending_buf.

§3 AI · 100%

When we set out to build machine-checked Lean 4 safety proofs for both zlib and zlib-ng (zlib × Lean; repository cla7aye15I4nd/oss-proof), most of both codebases came down to familiar systems invariants: ring-buffer wraparound in inflate_fast, hash-chain bounds over uninitialized slots in longest_match, and state-machine discipline across streaming calls.

§4 AI · 100%

Line 945 of zlib's trees.c was different.

§5 AI · 100%

Right above the buffer allocation in deflate.c, zlib's authors wrote a 38-line mathematical proof that this stripped assertion can never fire—and that proof is wrong. Yet when we put down the theorem prover and tried to construct an exploit input that actually crashes compress_block, every single attempt hit an invisible wall. This post walks through the whole investigation from the ground up: What deflate actually does: why zlib needs two passes per block, and why two cursors end up racing through the same pending_buf array. Why deflate.c's proof fails (and why an exploit still won't fit): why an average bit-length bound cannot prevent a mid-block collision—and why a collision would trigger an out-of-bounds .rodata read, not just corrupt output. How the C code connects to our Lean 4 proof: step by step, how pointer mutations and bi_buf bit-shifts reduce to pure Huffman-tree inequalities—culminating in an algebraic cancellation that closes memLevel 1..2 without brute-force search.

§6 AI · 100%

Proof geometry vs.

§7 AI · 100%

physical reality: the exact byte-and-bit closest approaches we synthesized on unmodified deflate(), why slot-by-slot proofs hit a mathematical ceiling near 980 while physical C stops at 720, and how one could close that gap. If you have never read zlib's source code, variable names like pending_buf, sym_buf, bi_valid, and _dist_code look opaque. The underlying idea, however, is straightforward once you trace a concrete string like "abcde_abcde_!" through one DEFLATE block. Pass 1: Why deflate Cannot Emit Bits Immediately¶ Suppose deflate is scanning "abcde_abcde_!". Its LZ77 matcher (deflate_fast or deflate_slow) spots that the second "abcde" repeats the bytes 6 positions earlier, turning the 13-byte string into 9 symbols: 'a', 'b', 'c', 'd', 'e', '_', Match(dist = 6, len = 5), '_', '!' Why doesn't deflate immediately write the Huffman bitcodes for 'a', 'b', 'c' to the output stream as soon as it sees them? Because it does not know the Huffman tree yet! Optimal Huffman coding assigns short bitstrings (down to 1 bit) to frequent symbols and long bitstrings (up to 15 bits) to rare ones. Until deflate has scanned the entire block and counted how many times each byte and match length occurs, it cannot build the block's custom Huffman trees. So deflate processes every block in two passes: Pass 1 — Record & Tally (_tr_tally, trees.c:1095–1119): As the matcher scans input, it parks each symbol in an intermediate array sym_buf using a fixed 3-byte (24-bit) encoding—two bytes for dist (0 for a literal, 1..32506 for a match) and one byte for lc (the literal byte, or len - 3)—while incrementing frequency counters Freq[]. Pass 2 — Build Trees & Emit Bits (_tr_flush_block, trees.c:997–1089): Once sym_buf fills up, deflate builds Huffman trees from Freq[], reads back the recorded 3-byte symbols from sym_buf one by one, and packs their variable-length bitcodes into the output byte queue pending_buf. Buckets and Extra Bits: How a 3-Byte Symbol Can Become 48 Bits (or 1 Bit)¶ There is one more piece of the format we need before everything clicks: how matches are Huffman-coded. A match distance dist can be anywhere from 1 to 32,768. If DEFLATE built a Huffman tree with 32,768 leaves, transmitting the tree description at the start of every block would cost kilobytes—far larger than small files! Instead, RFC 1951 §3.2.5 splits every length and distance into a coarse bucket (which is Huffman-coded) plus raw binary "extra bits" (which pinpoint the exact offset inside that bucket): Literals & Lengths share one 286-symbol tree (dyn_ltree): codes 0..255 are literal bytes; 256 is END_BLOCK; 257..285 are 29 length buckets, carrying 0 to 5 extra bits (for example, bucket 284 covers lengths 227..257 using 1 Huffman code + 5 extra bits; bucket 285 is length 258 alone with 0 extra bits). Distances use a 30-symbol tree (dyn_dtree): codes 0..29 are 30 distance buckets, carrying 0 to 13 extra bits (bucket 29 covers distances 16,385..32,768 using 1 Huffman code + 13 extra bits). To map dist - 1 (0..32,767) to its bucket 0..29 in \(O(1)\) time, zlib uses a 512-byte lookup table _dist_code[512] (deflate.h:320–321). Because DEFLATE caps Huffman code lengths at 15 bits, one 3-byte symbol in sym_buf can turn into: As little as 1 bit (a very frequent literal byte), or As much as \(15 + 5 + 15 + 13 = 48\) bits (a rare match landing in a 5-extra-bit length bucket and a 13-extra-bit distance bucket)—twice the 24 bits it occupied in sym_buf! Three Competing Block Formats—and the Shared Buffer Overlay¶ When Pass 1 finishes recording up to \(n \le B - 1\) symbols—where \(B = \mathrm{lit}\_\mathrm{bufsize} = 2^{\mathrm{memLevel}+6}\) ranges from \(128\) (memLevel = 1) to \(32{,}768\) (memLevel = 9, default \(16{,}384\) at memLevel = 8)—_tr_flush_block evaluates three legal DEFLATE encodings for the block and picks whichever produces the fewest bytes: Stored (00): Abandon compression and copy the raw uncompressed input bytes straight out of the sliding window (stored_len + 4 bytes). Fixed Huffman (01): Use RFC 1951's hardcoded Huffman tables (literals take 8 or 9 bits, lengths 7 or 8 bits, distances 5 bits). No tree header is needed—just a 3-bit tag—and every symbol costs at most \(8 + 5 + 5 + 13 = 31\) bits. Dynamic Huffman (10): Build custom trees dyn_ltree and dyn_dtree from Freq[]. Because the decoder does not know these custom trees yet, send_all_trees must serialize the tree code-lengths at the very start of the block (compressed with a tiny 19-symbol run-length Huffman tree called bl_tree) before compress_block encodes symbol 0.

§8 AI · 100%

Now look at memory layout.

§9 AI · 100%

Pass 2 only begins when pending_buf (the output queue) has been completely flushed to the caller (pending = 0), leaving at most bi_valid <= 7 leftover bits from the previous block sitting in the 16-bit shift register bi_buf.

§10 Human · 0%

Rather than allocating \(4B\) bytes for pending_buf plus another \(3B\) bytes for sym_buf, deflateInit2_ (deflate.c:463–520) allocates one 4B-byte array, leaves the first \(B\) bytes (8B bits) empty as a head start, and places sym_buf directly at pending_buf + B: s->lit_bufsize = 1 << (memLevel + 6); /* B: 128 .. 32768 (16384 by default) */ ... s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, LIT_BUFS); /* 4 * B bytes */ s->pending_buf_size = (ulg)s->lit_bufsize * 4; ... s->sym_buf = s->pending_buf + s->lit_bufsize; /* starts 1/4 of the way in */ s->sym_end = (s->lit_bufsize - 1) * 3; /* max n = B - 1 triples */ Step through all four stages of a block below to watch how Pass 1 and Pass 2 share pending_buf[0 ..

§11 AI · 100%

4B): Once compress_block starts Pass 2b, two cursors race left-to-right across the same array: The Runner (B + 3k): starts at byte \(B\) (\(8B\) bits).

§12 AI · 100%

On step \(k\), reading symbol \(k\) frees 3 bytes, advancing the boundary of unread symbols by +24 bits. The Chaser (pending + bi_valid): starts near byte \(0\) (with at most 7 leftover bits), leaps forward by the 3-bit tag + dynamic tree header before symbol 0 is read, and then advances by 1 to 48 bits per symbol. Overwriting [B .. B + 3k) is completely harmless—those symbols have already been read!

§13 AI · 100%

Disaster strikes only if the Chaser ever catches B + 3k and overwrites a symbol that compress_block hasn't read yet.

§14 AI · 100%

2.

§15 AI · 100%

Why Overwriting sym_buf Breaks Memory Safety—and Why deflate.c's Proof Is Wrong¶ Not Just Corrupt Output: The _dist_code[512] Cliff¶ Before trying to break or prove this invariant, ask a triage question: if s->pending did overtake B + 3k and overwrite unread symbols, wouldn't deflate merely emit a corrupt compressed stream?

§16 Human · 0%

Look twenty lines above the Assert in trees.c:913–939: dist = s->sym_buf[sx++] & 0xff; dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; lc = s->sym_buf[sx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ } else { code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); ... dist--; /* dist is now the match distance - 1 */ code = d_code(dist); Assert(code < D_CODES, "bad d_code"); send_code(s, code, dtree); Remember _dist_code[512] from Pass 1? Its macro in deflate.h:320–321 has no bounds check: #define d_code(dist) \ ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) When _tr_tally records a legitimate match, 1 <= dist <= MAX_DIST <= 32506, so dist - 1 <= 32505 <= 32767, and 256 + ((dist - 1) >> 7) stays safely inside 256 ..

§17 AI · 73%

511.

§18 AI · 100%

If compressed bits overwrite an unread symbol in sym_buf, the two bytes of dist become an arbitrary uint16_t up to 65535. Any value in 32769 ..

§19 AI · 100%

65535 (0x8001 ..

§20 AI · 100%

0xffff) enters the else branch and drives 256 + ((dist - 1) >> 7) to indices 512 ..

§21 AI · 100%

767—an out-of-bounds read up to 256 bytes past _dist_code in .rodata!

§22 Human · 0%

If that adjacent .rodata byte exceeds 60, send_code(s, code, dtree) and extra_dbits[code] read out of bounds again on dyn_dtree[61] and extra_dbits[30].

§23 Human · 0%

Drag the 16-bit dist slider below past 32,768 to see the exact cascade: So even if your goal is pure memory safety—proving deflate free of undefined behavior—you cannot dodge proving that the Chaser never catches the Runner.