Skip to content

fix(extract): bound page memory and fix LZW and ASCII85 decoding - #2

Open
trvon wants to merge 2 commits into
mainfrom
fix/form-xobject-memory
Open

trvon wants to merge 2 commits into
mainfrom
fix/form-xobject-memory

Conversation

@trvon

@trvon trvon commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Bounds per-page extraction memory and fixes two decoders. Found while tracing a yams daemon that reached 9 GB in zpdf decompression.

Memory

  • Form XObjects were decompressed on every Do into 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.
  • FlateDecode with a predictor no longer leaks the decoded buffer.

Decoders

  • ASCII85: groups above 2^32-1 overflowed a u32, illegal behavior in ReleaseFast. Now rejected.
  • LZW: single-byte entries pointed at a stack temporary, and readBits did 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.fuzz target (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; 6980be0 extracts 37,695 bytes. Worth an issue.

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>
Copilot AI lite review requested due to automatic review settings November 5, 2026 04:44

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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 thread src/decompress.zig
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 thread src/decompress.zig Outdated
Comment on lines +778 to +779
if (comptime @hasDecl(std.testing, "Smith")) {
try std.testing.fuzz({}, fuzzDecompressLimited, .{
Comment thread src/root.zig
Comment on lines +547 to +548
var budget = DecompressBudget{ .remaining = self.page_decompress_limit };
if (!budget.take(content.len)) return;
Comment thread src/root.zig
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
};
Comment thread src/capi.zig

/// 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 {
Comment thread src/decompress.zig Outdated
max_out: usize,
) ![]u8 {
const limit = @min(max_out, MAX_DECOMPRESSED_SIZE);
if (filter == null and data.len > max_out) return DecompressError.OutputTooLarge;
Comment thread src/decompress.zig
max_out: usize,
) ![]u8 {
return decodeFlateDecodeWithLimit(allocator, data, params, MAX_DECOMPRESSED_SIZE);
return decodeFlateDecodeWithLimit(allocator, data, params, @min(max_out, MAX_DECOMPRESSED_SIZE));
Comment thread src/decompress.zig Outdated
Comment on lines 508 to 510
max_out: usize,
) ![]u8 {
_ = params; // TODO: EarlyChange parameter
Comment thread src/root.zig
/// 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>
@trvon

trvon commented Nov 5, 2026

Copy link
Copy Markdown
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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants