Repository navigation
Conversation
A yams daemon extracting PDFs reached 9 GB in zpdf decompression. Most of
it was Form XObjects: handleDoOperator decompressed a form on every Do
into the page scratch arena, where free() is a no-op, so a form drawn N
times on a page stayed alive N times (up to 256 MB each).
- Forms are decompressed once per page and cached in the page arena.
- Document.page_decompress_limit caps the bytes one page may decompress
(page content plus forms). Default unlimited. A page over the limit
keeps the text extracted before it. C API:
zpdf_set_page_decompress_limit().
- decompressStreamLimited() passes its limit to the bounded FlateDecode
and LZW decoders and checks every filter stage. decompressStream()
keeps its old limits.
- FlateDecode with a predictor no longer leaks the decoded buffer.
Bugs found by fuzzing and new tests:
- ASCII85: a group above 2^32-1 ("uuuuu") overflowed a u32, illegal
behavior in ReleaseFast. Such groups are now rejected.
- LZW: single-byte table entries pointed at a stack temporary and
readBits did not mask off the previous code's bits or read the last
bytes, so most LZW streams decoded to garbage. Rewritten as a
prefix/suffix table with no per-entry allocation, checked against the
PDF reference example and a string-table reference decoder.
Tests: repeated-form peak memory, page limit behavior, a seeded property
test over random forms and limits, decompression bomb limits, ASCII85
overflow, LZW reference and differential, and a std.testing.fuzz target
(Zig 0.16+). Tested on Zig 0.16 and 0.17.
On 2,067 real PDFs, against the release yams ships: peak RSS -31%,
extraction time -15%; one LZW file now extracts (36 -> 2,418 chars).
Signed-off-by: trvon <me@trevon.dev>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved ABI, decompression-limit, memory-leak, compatibility, and page-budget issues leave critical correctness and resource-safety gaps, including paths that can allocate beyond the documented limits.
9 open issues
Enforce output limits during filter decoding · New Gate the Zig 0.15.2-incompatible fuzz callback · New Apply the page budget during content stream decompression · New Cache failed form decodes to prevent repeated allocations · New Declare the exported setter in the CFFI ABI · New Enforce the output limit for no-op filter fallbacks · New Free the original Flate output after predictor application · New Honor the LZW EarlyChange DecodeParms setting · New Apply the page limit across all public extraction APIs · New
What changed in this PR
This pull request limits per-page PDF extraction memory, caches repeated Form XObject decompression, and fixes ASCII85 and LZW decoding. It also adds regression, fuzz, memory, and C API coverage.
Changes:
- Adds configurable per-page decompression budgets and per-page form caching.
- Adds bounded decompression and corrects ASCII85 overflow and LZW dictionary handling.
- Expands memory, decoder, integration, and randomized tests.
- Exposes the page decompression limit through the C API.
This pull request requires changes.
| File | Changes | Final review comments |
|---|---|---|
src/testpdf.zig |
Adds peak-allocation tracking and repeated-form PDF generation helpers. | No review comments. |
src/root.zig |
Adds page decompression budgets and cached Form XObject extraction. | Critical — Page-content streams are decompressed before the budget is applied, allowing compressed bombs to exceed the limit (L547, 4 votes). Critical — Failed form decodes are retried for every Do, potentially retaining partial output and causing unbounded scratch memory growth (L2294, 1 vote).Moderate — Other public extraction APIs do not propagate the configured page limit (L145, 2 votes). |
src/integration_test.zig |
Adds repeated-form, memory-limit, and randomized extraction tests. | No review comments. |
src/decompress.zig |
Adds limited decompression and revises predictor, ASCII85, and LZW handling. | Critical — Several filters allocate their complete output before checking the limit, so peak memory remains unbounded for those stages (L77, 4 votes). Moderate — Predictor handling leaks the original decoded buffer (L155, 4 votes). Moderate — Empty or malformed filter configurations can bypass the output limit (L49, 3 votes). Moderate — LZW ignores EarlyChange 0 (L508, 2 votes).Moderate — LZW output can exceed the limit before the length check (L550, 1 vote). Critical — The fuzz callback references std.testing.Smith unconditionally, breaking Zig 0.15.2 compilation despite the compatibility guard (L778, 1 vote). |
src/capi.zig |
Exposes the page decompression limit through the native API. | Moderate — The setter is missing from python/zpdf/_cdef.h, leaving the checked-in CFFI ABI declaration out of sync (L66, 4 votes). |
Review effort: Lite
Comment on lines
+77
to
+80
| const result = try applyFilter(allocator, current, f, param, limit); | ||
| if (result.len > limit) { | ||
| allocator.free(result); | ||
| return DecompressError.OutputTooLarge; |
Comment on lines
+778
to
+779
| if (comptime @hasDecl(std.testing, "Smith")) { | ||
| try std.testing.fuzz({}, fuzzDecompressLimited, .{ |
Comment on lines
+547
to
+548
| var budget = DecompressBudget{ .remaining = self.page_decompress_limit }; | ||
| if (!budget.take(content.len)) return; |
Comment on lines
+2294
to
+2297
| const decoded = decompress.decompressStreamLimited(ctx.scratch_allocator, xobj_resolved.data, filter, params, ctx.budget.remaining) catch |err| { | ||
| if (err == error.OutOfMemory) return err; | ||
| return; // corrupt, unsupported, or over the page budget: skip the form | ||
| }; |
|
|
||
| /// Cap the bytes one page's text extraction may decompress (page content | ||
| /// plus Form XObjects). 0 means unlimited, the default. | ||
| export fn zpdf_set_page_decompress_limit(handle: ?*ZpdfDocument, limit: usize) void { |
| max_out: usize, | ||
| ) ![]u8 { | ||
| const limit = @min(max_out, MAX_DECOMPRESSED_SIZE); | ||
| if (filter == null and data.len > max_out) return DecompressError.OutputTooLarge; |
| max_out: usize, | ||
| ) ![]u8 { | ||
| return decodeFlateDecodeWithLimit(allocator, data, params, MAX_DECOMPRESSED_SIZE); | ||
| return decodeFlateDecodeWithLimit(allocator, data, params, @min(max_out, MAX_DECOMPRESSED_SIZE)); |
Comment on lines
508
to
510
| max_out: usize, | ||
| ) ![]u8 { | ||
| _ = params; // TODO: EarlyChange parameter |
| /// page content and every Form XObject it draws. Bounds per-page scratch | ||
| /// memory. Unlimited by default; a page over the limit yields the text | ||
| /// extracted before it was reached. | ||
| page_decompress_limit: usize = std.math.maxInt(usize), |
- Page content is decompressed through getPageContentsLimited() on every extraction path, so page_decompress_limit applies to text, bounds, structured, fast and image extraction, and stops decompression at the limit instead of checking afterwards. - ASCII85, ASCIIHex, RunLength and the image pass-through enforce the limit while producing output. An empty or malformed /Filter is checked too. - decompressStreamLimited(): the filter-name slice pointed at an array scoped to a switch arm; it now lives in the function. - FlateDecode: free the decoded buffer when a predictor is applied, and grow the output geometrically (capped at the limit) instead of an exact reserve per 64 KiB chunk. - LZW honors /DecodeParms /EarlyChange (default 1). The decoder always used the EarlyChange 0 width rule, so long default streams decoded wrong past code 511. Round-trip tested with an encoder for both values. - A form that fails to decode is cached as failed and not retried on every Do. - The fuzz callback sits inside the Zig 0.16 guard so 0.15 never analyzes its Smith signature. - python/zpdf/_cdef.h declares zpdf_set_page_decompress_limit(). The LZW file from the real-PDF sweep now extracts 99,435 chars (2,418 before this change, 36 on the old release). Zig 0.16 and 0.17 pass. Signed-off-by: trvon <me@trevon.dev>
This was referenced Nov 5, 2026
Owner
Author
|
Consumed by trvon/yams#427 (stack #425 -> #426 -> #427 on trvon/yams). Merge this one first, with a merge commit so the submodule SHA pinned there stays reachable. |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Bounds per-page extraction memory and fixes two decoders. Found while tracing a yams daemon that reached 9 GB in zpdf decompression.
Memory
Dointo the page arena (free()is a no-op), so a form drawn N times stayed alive N times, up to 256 MB each. Now decompressed once per page and cached.Document.page_decompress_limit/zpdf_set_page_decompress_limit(): cap on bytes one page may decompress. Default unlimited.decompressStreamLimited()passes the limit to the bounded FlateDecode and LZW decoders and checks every filter stage.Decoders
u32, illegal behavior in ReleaseFast. Now rejected.readBitsdid not mask the previous code's bits or read the final bytes, so most LZW streams decoded to garbage. Rewritten as a prefix/suffix table. Checked against the PDF reference example and a string-table reference.Tests
Repeated-form peak memory, page limit behavior, seeded property test over random forms and limits, bomb limits (inclusive boundary), ASCII85 overflow, LZW reference and differential,
std.testing.fuzztarget (0.16+). 6.4M-input seeded sweep plus 48k generated PDFs under ReleaseSafe: no leaks or violations. Zig 0.16 and 0.17: all tests pass.Real PDFs
2,067 PDFs vs. the zpdf yams ships: peak RSS -31%, time -15%, one LZW file now extracts (36 -> 2,418 chars).
Not from this PR
3d36a17(harden malformed PDF handling, Lulzx#11) makes one of those PDFs extract nothing: "Failed to parse XRef table at offset 0", 0 pages. Bisected on Zig 0.16;6980be0extracts 37,695 bytes. Worth an issue.