fix(render): bound the objects lopdf's fallback parses from object streams and arrays (#5083)

## What this changes

lopdf's fallback loader (used by `inspect` when the lazy reader fails, and always by `attachment_data`) parsed every object stream eagerly, capping only decoded bytes. A stream of `0 0 0 …` inside the 256 MiB limit built ~120M `Object`s (10+ GB) and aborted. This bounds what it builds:

- **Per top-level object:** at most 4,194,304 objects (`parser::MAX_OBJECT_NODES`, the same as cos's `MAX_NODES`), counting every array element and dictionary value at any depth. One budget is threaded through `array` / `_dictionary` / `_direct_object`. An object is charged once it is built, so failed `alt` branches cost nothing, and an exhausted budget is a nom `Failure`.
- **Per object stream:** at most 1,000,000 index entries (cos's `/N` clamp), and the index list is no longer allocated from the whole block.
- **Per load:** at most 8,388,608 objects across all object streams, in an atomic `NodeBudget` shared by rayon workers. A member reserves up to its own byte length (every object takes at least one byte) and refunds what it doesn't use, so parallel members can't hold the budget between them. Once the budget is spent, the remaining members are skipped with a warning.
- **`convert` in `crates/render/src/structure.rs`:** the depth limit is now 128, one level per array or dictionary, matching cos's parser. Before, it was 100 with two levels per dictionary, so ~51 nested dictionaries alone forced the lopdf fallback.

Logged as lopdf patch (7) in `vendor/README.md`.

Fixes #5083

## How you verified it

`cargo fmt --check` on `pdfcraft-render` and `cargo clippy -p pdfcraft-render --all-targets -- -D warnings` (which compiles the vendored lopdf). Regression tests in `crates/render/src/inspect/tests.rs`, where lopdf patches are tested in-tree (the vendored lopdf's own tests need its missing `assets/example.pdf`):

- `object_stream_members_over_the_node_cap_are_skipped` (croquete1): a member that is one array of 4.3M elements is skipped at the per-object cap; a small member is kept.
- `object_stream_index_entries_past_the_clamp_are_ignored`: of 1,000,001 distinct members, the one past the 1,000,000-entry clamp is never built.
- `object_streams_of_one_load_share_their_node_budget`, `object_streams_loaded_in_parallel_share_their_node_budget` and `a_malformed_object_stream_member_refunds_its_reservation` (Harrison-Booth): a small shared `NodeBudget` bounds the members of several streams, serially and across threads, and a malformed member refunds what it didn't build. `NodeBudget` and `ObjectStream::new_within` are now public for this.

- [x] `cargo fmt --check`
- [x] clippy with `-D warnings` on the crates I changed
- [x] tests pass on the crates I changed (`cargo test -p pdfcraft-render --lib object_stream`: 9 passed, including the five new tests)

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests
- [x] No indexing or slicing with input-derived positions; the budget uses `checked_sub` and a `min`-bounded reservation; index entries and objects built are capped; nesting stays bounded (128 in `convert`)
- [x] No `unsafe`
- [x] The abort this fixes has synthetic regression tests (above)

## Provenance

- [x] No assets, fonts or copied code; the limits follow `pdfcraft_cos`'s own caps

## Security

- [x] No change to `--root`, MCP, the control channel or network access

## Parity and reach

- Not applicable: an internal robustness fix to the fallback loader, with no user-facing feature or parity entry. The vendored-patch log (`vendor/README.md`, lopdf (7)) is updated.

## Anything a reviewer should look at first

- `vendor/README.md` now lists the tests above for patch (7).
- Ordinary (not compressed) indirect objects are capped at 4M objects each but aren't charged to the per-load budget; their total is bounded only by file size.
- `get_compressed_object` still decodes and re-parses the whole stream per lookup (pre-existing); it now gets one object's budget.
- Objects nested 101–128 deep now reach the Inspector through the lazy reader rather than being skipped by the fallback. The Inspector's own walkers cap depth at 32 or less.


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
  * Added limits to PDF object parsing and object-stream processing. Loading now parses only selected members, while lookups parse only the requested member. Members that exceed available limits are skipped in a deterministic order.
  * Increased the supported nesting depth for dictionary and object conversion, allowing more deeply nested content to be processed.
  * Documented that conversion failures can trigger eager loading as a fallback.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Michael Higgins authored and GitHub committed 2026-11-11 07:48:14 +01:00
1 parent e317ccae44
commit f51ce3cfcc
7 files changed
+511 -90

No files matched your search

+166
View File
@@ -249,6 +249,8 @@ fn object_stream_member_extents_bound_owned_strings() {
assert!(!parsed.objects.contains_key(&(201, 0)));
}
/// Members are read at their indexed offsets, in any order and with any whitespace around
/// them; a number listed twice keeps its last entry.
#[test]
fn object_stream_member_extents_preserve_index_order_and_whitespace() {
let members = b" \n42\n /Name \n[true 7]\n << /Key (value) >>\n (last)";
@@ -262,6 +264,170 @@ fn object_stream_member_extents_preserve_index_order_and_whitespace() {
assert_eq!(parsed.objects.get(&(12, 0)).unwrap().as_dict().unwrap().get(b"Key").unwrap().as_str().unwrap(), b"value");
}
/// lopdf patch (7), #5083: a decoded object-stream member could build any number of objects
/// (`0 0 0 ...` inside the decompression limit built ~120M and aborted). A member now builds at
/// most the per-object node cap (1 << 22), so one array with more elements than that is skipped
/// while a small member is kept. Without the node charge in the vendored parser the oversize
/// array builds in full, so object 11 is present and the last assertion fails.
#[test]
fn object_stream_members_over_the_node_cap_are_skipped() {
let small = b"[ 1 2 3 ]";
let mut big = vec![b'['];
for _ in 0..4_300_000 {
big.extend_from_slice(b"0 ");
}
big.push(b']');
let mut members = small.to_vec();
let big_off = members.len();
members.extend_from_slice(&big);
let stream = indexed_object_stream(&[(10, 0), (11, big_off)], &members);
let parsed = lopdf::ObjectStream::new_with_limit(&stream, Some(16 << 20)).unwrap();
assert!(parsed.objects.contains_key(&(10, 0)), "the small member is kept");
assert!(!parsed.objects.contains_key(&(11, 0)), "the oversize member is skipped");
}
/// lopdf patch (7), #5083: an object stream reads at most 1,000,000 index entries (cos's `/N`
/// clamp), so a huge index can't allocate an entry list or parse a member per entry. Of
/// 1,000,001 distinct one-byte members, the last is never built.
#[test]
fn object_stream_index_entries_past_the_clamp_are_ignored() {
let count = 1_000_001_u32;
let mut members = Vec::with_capacity(2 * count as usize);
let pairs: Vec<(u32, usize)> = (1..=count)
.map(|id| {
let at = members.len();
members.extend_from_slice(b"0 ");
(id, at)
})
.collect();
let parsed = lopdf::ObjectStream::new_with_limit(&indexed_object_stream(&pairs, &members), None).unwrap();
assert_eq!(parsed.objects.len(), 1_000_000);
assert!(parsed.objects.contains_key(&(1_000_000, 0)));
assert!(!parsed.objects.contains_key(&(count, 0)), "the entry past the clamp is ignored");
}
/// Six object streams, each holding one nested member of seven objects.
fn nested_object_streams() -> Vec<lopdf::Stream> {
(0..6).map(|i| indexed_object_stream(&[(100 + i, 0)], b"<< /A [1 [2]] /B << /C 3 >> >>")).collect()
}
/// lopdf patch (7), #5083: one load's object streams share a single node budget (the load-wide
/// `MAX_LOAD_NODES`, here 12 nodes so the test stays small), so later streams are skipped once
/// earlier ones spent it. A stream given a budget of its own would load all six.
#[test]
fn object_streams_of_one_load_share_their_node_budget() {
let streams = nested_object_streams();
let budget = lopdf::NodeBudget::new(12);
let loaded: usize = streams.iter().map(|s| lopdf::ObjectStream::new_within(s, None, &budget).unwrap().objects.len()).sum();
assert!(loaded > 0);
assert!(loaded < streams.len(), "the budget is shared by all streams");
assert!(budget.spent());
}
/// The shared budget holds across threads too, as rayon's workers load object streams in
/// parallel: members reserve their share before parsing, so together they can't overshoot.
#[test]
fn object_streams_loaded_in_parallel_share_their_node_budget() {
let streams = nested_object_streams();
let budget = &lopdf::NodeBudget::new(12);
let loaded: usize = std::thread::scope(|scope| {
let workers: Vec<_> =
streams.iter().map(|s| scope.spawn(move || lopdf::ObjectStream::new_within(s, None, budget).unwrap().objects.len())).collect();
workers.into_iter().map(|w| w.join().unwrap()).sum()
});
assert!(loaded > 0);
assert!(loaded < streams.len(), "the budget is shared by all streams");
}
/// A member that fails to parse gives back the nodes it reserved and did not build, so a
/// malformed member doesn't use up the budget of the members after it.
#[test]
fn a_malformed_object_stream_member_refunds_its_reservation() {
let stream = indexed_object_stream(&[(10, 0), (11, 3)], b"[1 [2]");
let budget = lopdf::NodeBudget::new(5);
let parsed = lopdf::ObjectStream::new_within(&stream, None, &budget).unwrap();
assert!(!parsed.objects.contains_key(&(10, 0)));
assert!(parsed.objects.contains_key(&(11, 0)));
assert!(!budget.spent(), "unused reservation from the malformed member is refunded");
}
/// A budget too small for every member builds them in index order, so the members a spent
/// budget skips are the same on every load. Here the first member takes four of the five
/// nodes, the second the last one, and the third is skipped. Parsed in parallel from the shared
/// budget, the second and third could find it held by the first and be skipped as well.
#[test]
fn a_tight_budget_builds_object_stream_members_in_index_order() {
let stream = indexed_object_stream(&[(10, 0), (11, 8), (12, 10)], b"[1 2 3] 7 8");
let budget = lopdf::NodeBudget::new(5);
let parsed = lopdf::ObjectStream::new_within(&stream, None, &budget).unwrap();
assert!(parsed.objects.contains_key(&(10, 0)));
assert!(parsed.objects.contains_key(&(11, 0)), "the second member is built from what the first left");
assert!(!parsed.objects.contains_key(&(12, 0)), "the third member finds the budget spent");
assert!(budget.spent());
}
/// A PDF with a cross-reference stream whose Info dictionary (object 4) sits in object stream 3
/// after `first`, a member listed before it.
fn info_in_object_stream_pdf(first: &[u8]) -> Vec<u8> {
let info = b"<< /Title (Kept) >>";
let index = format!("5 0 4 {} ", first.len() + 1);
let mut data = index.clone().into_bytes();
data.extend_from_slice(first);
data.push(b' ');
data.extend_from_slice(info);
let mut pdf = b"%PDF-1.5\n".to_vec();
let mut offsets = [0_u32; 7];
let mut append = |pdf: &mut Vec<u8>, id: usize, head: &[u8], body: &[u8], tail: &[u8]| {
offsets[id] = pdf.len() as u32;
pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
pdf.extend_from_slice(head);
pdf.extend_from_slice(body);
pdf.extend_from_slice(tail);
pdf.extend_from_slice(b"\nendobj\n");
};
append(&mut pdf, 1, b"<< /Type /Catalog /Pages 2 0 R >>", b"", b"");
append(&mut pdf, 2, b"<< /Type /Pages /Kids [] /Count 0 >>", b"", b"");
let head = format!("<< /Type /ObjStm /N 2 /First {} /Length {} >>\nstream\n", index.len(), data.len());
append(&mut pdf, 3, head.as_bytes(), &data, b"\nendstream");
let xref_offset = pdf.len() as u32;
offsets[6] = xref_offset;
let mut records = Vec::new();
for (id, &offset) in offsets.iter().enumerate() {
let (kind, field, index) = match id {
0 => (0_u8, 0_u32, 0xffff_u16),
4 => (2, 3, 1),
5 => (2, 3, 0),
_ => (1, offset, 0),
};
records.push(kind);
records.extend_from_slice(&field.to_be_bytes());
records.extend_from_slice(&index.to_be_bytes());
}
let head = format!("<< /Type /XRef /Size 7 /Root 1 0 R /Info 4 0 R /W [1 4 2] /Length {} >>\nstream\n", records.len());
pdf.extend_from_slice(format!("6 0 obj\n{head}").as_bytes());
pdf.extend_from_slice(&records);
pdf.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes());
pdf
}
/// lopdf patch (7), #5083: a lookup in an object stream (lopdf's metadata reader, or an indirect
/// `/Length` read while loading) parses only the member it wants. It used to parse every member
/// from one object's budget, so a member before it of more than `MAX_OBJECT_NODES` objects spent
/// that budget and the wanted member was skipped: the Info dictionary read as missing.
#[test]
fn a_lookup_in_an_object_stream_parses_only_the_member_it_wants() {
let mut big = vec![b'['];
for _ in 0..4_300_000 {
big.extend_from_slice(b"0 ");
}
big.push(b']');
let metadata = Document::load_metadata_mem(&info_in_object_stream_pdf(&big)).unwrap();
assert_eq!(metadata.title.as_deref(), Some("Kept"));
// The fixture itself reads: with a small member before it, the Info dictionary was read before too.
let metadata = Document::load_metadata_mem(&info_in_object_stream_pdf(b"[1 2 3]")).unwrap();
assert_eq!(metadata.title.as_deref(), Some("Kept"));
}
#[test]
fn view_and_user_space_round_trip_for_every_rotation() {
for rotation in [0u16, 90, 180, 270] {
+15 -4
View File
@@ -166,6 +166,8 @@ impl Structure for LazyStructure {
fn encrypted(&self) -> bool {
self.source.security().is_some() || self.trailer.has(b"Encrypt")
}
/// The object `id`, read from the lazy source and converted once, then kept; a failed
/// conversion marks the structure so the caller can fall back to the eager loader.
fn get_object(&self, id: ObjectId) -> Result<&Object> {
let missing = || Error::ObjectNotFound(id);
let slot = self.objects.binary_search_by_key(&id.0, |(n, _)| *n).ok().and_then(|i| self.objects.get(i)).ok_or_else(missing)?;
@@ -185,8 +187,15 @@ impl Structure for LazyStructure {
}
}
/// Nesting `convert` accepts: the same as `pdfcraft_cos`'s parser (each array or dictionary
/// one level), so every object cos parsed converts. A lower limit would turn deep but valid
/// nesting into a lazy-reader failure and force the eager lopdf fallback.
const CONVERT_DEPTH: usize = 128;
/// Convert a cos dictionary to lopdf's, without `/PieceInfo`. `depth` is the nesting level of
/// the dictionary itself; its values sit one level deeper.
fn convert_dict(dict: &pdfcraft_cos::Dict, depth: usize) -> Result<Dictionary> {
if depth > 100 {
if depth > CONVERT_DEPTH {
return Err(Error::RecursionLimit);
}
dict.iter()
@@ -203,8 +212,10 @@ fn convert_dict(dict: &pdfcraft_cos::Dict, depth: usize) -> Result<Dictionary> {
/// untouched; this is the read-only view inspection walks.
const PRIVATE_DATA: &[u8] = b"PieceInfo";
/// Convert a cos object to lopdf's, failing past [`CONVERT_DEPTH`] levels of arrays and
/// dictionaries.
fn convert(object: &CosObject, depth: usize) -> Result<Object> {
if depth > 100 {
if depth > CONVERT_DEPTH {
return Err(Error::RecursionLimit);
}
Ok(match object {
@@ -218,8 +229,8 @@ fn convert(object: &CosObject, depth: usize) -> Result<Object> {
}
CosObject::Ref(value) => Object::Reference((value.num, value.generation)),
CosObject::Array(value) => Object::Array(value.iter().map(|o| convert(o, depth + 1)).collect::<Result<_>>()?),
CosObject::Dict(value) => Object::Dictionary(convert_dict(value, depth + 1)?),
CosObject::Stream(value) => Object::Stream(lopdf::Stream::new(convert_dict(&value.dict, depth + 1)?, value.raw.to_vec())),
CosObject::Dict(value) => Object::Dictionary(convert_dict(value, depth)?),
CosObject::Stream(value) => Object::Stream(lopdf::Stream::new(convert_dict(&value.dict, depth)?, value.raw.to_vec())),
})
}
+1 -1
View File
@@ -58,7 +58,7 @@ Other resource categories retain their existing parent-chain lookup.
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroLine truncated
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most as many symbol pixels per symbol dictionary as the largest page bitmap holds, 2^28 (a fuzzed dictionary decoded for minutes; each symbol now pays for its pixels out of the stream's decoding work and is held in the retained bitmaps, and at the earlier 2^26 the soft mask of a scanned drawing, one dictionary of 7,559 symbols, was refused: #6722), and a refusal by one of the decoder's limits is told apart from damaged data (`DecodeError::is_limit`, `OverflowError::BitmapLimit`); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and Line truncated
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365); (7) object parsing builds at most 4,194,304 objects (every array element and dictionary value at any depth, `parser::MAX_OBJECT_NODES`, the same cap as `pdfcraft_cos`) per top-level object, an object stream reads at most 1,000,000 index entries (cos's `/N` clamp), and one load builds at most 8,388,608 objects from all of its object streams together, shared across rayon workers (a decoded stream of `0 0 0 ...` inside the 256 MiB decompression limit built ~120M objects, 10+ GB, and aborted). A lookup parses only the member it wants, so it isn't skipped behind a large member, and a load parses only the members it would add: none its cross-reference table places in another stream (stale copies) and none already loaded as an ordinary object or from an earlier stream. Members the table doesn't list at all are still parsed (a rebuilt table lists no compressed objects) and share the budget, so they can spend it before listed members of the same stream; a load expands its object streams one at a time in object-number order, a stream's members in parallel only when the budget holds all of them and otherwise in index order, so a spent budget skips the same members on every load (#5083) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog`; (7) `inspect::tests::{object_stream_members_over_the_node_cap_are_skipped, object_stream_index_entries_past_the_clamp_are_ignored, object_streams_of_one_load_share_their_node_budget, object_streams_loaded_in_parallel_share_their_node_budget, a_malformed_object_stream_member_refunds_its_reservation, a_tight_budget_builds_object_stream_members_in_index_order, a_lookup_in_an_object_stream_parses_only_the_member_it_wants}` (pdfcraft-render; `NodeBudget` and `ObjectStream::new_within` are public so these can use a small budget) |
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure |
+1 -1
View File
@@ -47,7 +47,7 @@ pub use encryption::{EncryptionState, EncryptionVersion, Permissions};
pub use error::{DecompressError, Error, ParseError, Result};
pub use incremental_document::IncrementalDocument;
pub use load_options::{FilterFunc, LoadOptions};
pub use object_stream::{ObjectStream, ObjectStreamBuilder, ObjectStreamConfig};
pub use object_stream::{NodeBudget, ObjectStream, ObjectStreamBuilder, ObjectStreamConfig};
pub use outlines::Outline;
pub use reader::{PdfMetadata, Reader};
pub use save_options::{SaveOptions, SaveOptionsBuilder};
+163 -22
View File
@@ -1,13 +1,78 @@
use crate::parser;
use crate::{Document, Error, Object, ObjectId, Result, Stream};
use std::cell::Cell;
use std::collections::BTreeMap;
use std::num::TryFromIntError;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use log::warn;
#[cfg(feature = "rayon")]
use rayon::prelude::*;
/// PdfCraft patch: index entries read from one object stream (the same clamp `pdfcraft_cos`
/// applies to `/N`). Entries past it are ignored, so a huge index block cannot allocate an entry
/// list or parse a member per entry.
pub(crate) const MAX_OBJECT_STREAM_MEMBERS: usize = 1_000_000;
/// PdfCraft patch: objects (every member and everything nested in it) one load may build from
/// all of its object streams together, about one per object of the largest cross-reference
/// table `pdfcraft_cos` accepts (8,388,607). Each stream is bounded by the decompression limit,
/// but a file may hold many, and every two decoded bytes can be an object of a hundred bytes or
/// more; this keeps the worst case near a gigabyte instead of tens.
pub(crate) const MAX_LOAD_NODES: usize = 1 << 23;
/// PdfCraft patch: the objects parsing may still build, shared by every object stream one load
/// parses (and by rayon workers, hence atomic). Each member reserves its share before parsing
/// and refunds what it did not use, so concurrent members cannot overshoot the total. Public so
/// PdfCraft's tests can load object streams from a small budget.
///
/// The loaders parse their object streams one after another in object-number order, and a
/// stream whose members could run the budget out parses them in index order (see
/// [`ObjectStream::new_within`]), so the members skipped once it is spent are the same on every
/// load of a file.
pub struct NodeBudget(AtomicUsize);
impl NodeBudget {
/// A budget of `nodes` objects.
pub fn new(nodes: usize) -> Self {
Self(AtomicUsize::new(nodes))
}
/// Take up to `want` nodes and return how many were granted (0 once the budget is spent).
fn reserve(&self, want: usize) -> usize {
// A compare-exchange loop rather than `fetch_update`, which newer toolchains deprecate
// in favour of a `try_update` older than this crate's minimum Rust version.
let mut left = self.0.load(Ordering::Relaxed);
loop {
let take = left.min(want);
match self
.0
.compare_exchange_weak(left, left - take, Ordering::Relaxed, Ordering::Relaxed)
{
Ok(_) => return take,
Err(now) => left = now,
}
}
}
/// Give back nodes [`Self::reserve`] granted and parsing did not use. Refunds never exceed
/// what was taken, so the count stays within the starting budget and cannot overflow.
fn refund(&self, nodes: usize) {
self.0.fetch_add(nodes, Ordering::Relaxed);
}
/// The nodes not yet reserved.
fn left(&self) -> usize {
self.0.load(Ordering::Relaxed)
}
/// Whether nothing is left to build from.
pub fn spent(&self) -> bool {
self.left() == 0
}
}
#[derive(Debug)]
pub struct ObjectStream {
pub objects: BTreeMap<ObjectId, Object>,
@@ -50,7 +115,33 @@ impl ObjectStream {
/// Parse an existing object stream without modifying it, rejecting the
/// decoded content if it would exceed `max_decompressed_size` bytes. `None`
/// means no limit (the behavior of [`ObjectStream::new`]).
///
/// PdfCraft patch: members are built from a budget of `MAX_LOAD_NODES` objects of their own.
pub fn new_with_limit(stream: &Stream, max_decompressed_size: Option<usize>) -> Result<ObjectStream> {
Self::new_within(stream, max_decompressed_size, &NodeBudget::new(MAX_LOAD_NODES))
}
/// PdfCraft patch: [`ObjectStream::new_with_limit`], building members from `budget`, which a
/// load shares between all of its object streams. A member that would exceed its share, or
/// any member once the budget is spent, is skipped with a warning.
///
/// When the budget holds enough for every member, they are parsed in parallel from a share
/// reserved for this stream alone, which no member can run out; otherwise they are parsed in
/// index order from `budget`. Either way which members are built doesn't depend on the order
/// in which rayon's workers reach them.
pub fn new_within(
stream: &Stream, max_decompressed_size: Option<usize>, budget: &NodeBudget,
) -> Result<ObjectStream> {
Self::new_members_within(stream, max_decompressed_size, budget, |_| true)
}
/// PdfCraft patch: [`ObjectStream::new_within`], parsing only the members whose object
/// number `keep` accepts. The others are never parsed, so they spend nothing from `budget`:
/// a loader passes the members it would add (not placed in another stream by the
/// cross-reference table, and not already loaded), and a lookup the one member it wants.
pub(crate) fn new_members_within(
stream: &Stream, max_decompressed_size: Option<usize>, budget: &NodeBudget, keep: impl Fn(u32) -> bool,
) -> Result<ObjectStream> {
let content = match max_decompressed_size {
// Object streams are decoded while the document is loaded, so
// enforcing the limit here bounds the memory a single stream can use.
@@ -75,8 +166,10 @@ impl ObjectStream {
let index_block = content.get(..first_offset).ok_or(Error::InvalidOffset(first_offset))?;
let numbers_str = std::str::from_utf8(index_block).map_err(|e| Error::InvalidObjectStream(e.to_string()))?;
// PdfCraft patch: read at most `MAX_OBJECT_STREAM_MEMBERS` index entries.
let numbers: Vec<_> = numbers_str
.split_whitespace()
.take(2 * MAX_OBJECT_STREAM_MEMBERS)
.map(|number| u32::from_str(number).ok())
.collect();
let len = numbers.len() / 2 * 2; // Ensure only pairs.
@@ -85,6 +178,9 @@ impl ObjectStream {
if numbers.len().try_into().ok() != n.checked_mul(2) {
warn!("object stream: the object stream dictionary specifies a wrong number of objects")
}
if usize::try_from(n).is_ok_and(|n| n > MAX_OBJECT_STREAM_MEMBERS) {
warn!("object stream: /N {n} exceeds {MAX_OBJECT_STREAM_MEMBERS}; later members are ignored")
}
// PdfCraft patch: bound members by the next distinct offset and parse each offset
// only once, so overlapping or duplicate entries cannot amplify decoded content.
@@ -103,44 +199,89 @@ impl ObjectStream {
end = offset;
}
let chunks_filter_map = |(index, chunk): (usize, &[_])| {
let id = chunk[0]?;
let offset = first_offset.saturating_add(chunk[1]? as usize);
// PdfCraft patch: find each member's bytes first, in index order, so the members can be
// charged to the budget before any is parsed.
let mut members = Vec::new();
for (index, chunk) in numbers[..len].chunks(2).enumerate() {
let &[Some(id), Some(offset)] = chunk else { continue };
let offset = first_offset.saturating_add(offset as usize);
if offset >= content.len() {
warn!("out-of-bounds offset in object stream");
return None;
continue;
}
let &(first_index, extent_end) = extents.get(&offset)?;
let Some(&(first_index, extent_end)) = extents.get(&offset) else {
continue;
};
if index != first_index {
warn!("duplicate offset in object stream");
return None;
continue;
}
if !keep(id) {
continue;
}
// Skip leading whitespace — some PDFs emit newlines before objects in ObjStm
let mut start = offset;
while start < extent_end && content[start].is_ascii_whitespace() {
while start < extent_end && content.get(start).is_some_and(u8::is_ascii_whitespace) {
start += 1;
}
if start >= extent_end {
warn!("only whitespace after offset in object stream");
continue;
}
members.push((id, start, extent_end));
}
// PdfCraft patch: each member builds at most `MAX_OBJECT_NODES` objects, reserved from
// `from`; once that is spent the remaining members are skipped unparsed. Every object
// takes at least one byte, so a member reserves no more than its length.
let share = |&(_, start, end): &(u32, usize, usize)| parser::MAX_OBJECT_NODES.min(end - start);
let skipped = AtomicBool::new(false);
let parse_member = |from: &NodeBudget, member: &(u32, usize, usize)| -> Option<(ObjectId, Object)> {
let &(id, start, end) = member;
let granted = from.reserve(share(member));
if granted == 0 {
skipped.store(true, Ordering::Relaxed);
return None;
}
let object = parser::direct_object(&content[start..extent_end])?;
Some(((id, 0), object))
let nodes = Cell::new(granted);
let object = content
.get(start..end)
.and_then(|bytes| parser::direct_object_within(bytes, &nodes));
from.refund(nodes.get());
if object.is_none() && nodes.get() == 0 {
warn!("object stream: member {id} exceeds the object budget and was skipped");
}
Some(((id, 0), object?))
};
#[cfg(feature = "rayon")]
let objects = numbers[..len]
.par_chunks(2)
.enumerate()
.filter_map(chunks_filter_map)
.collect();
#[cfg(not(feature = "rayon"))]
let objects = numbers[..len]
.chunks(2)
.enumerate()
.filter_map(chunks_filter_map)
.collect();
let want = members.iter().map(&share).fold(0, usize::saturating_add);
let granted = budget.reserve(want);
let objects: BTreeMap<ObjectId, Object> = if granted == want {
// Every member fits, so they are parsed in parallel from this stream's own share:
// its members' reservations add up to it, so none is refused whatever the order.
let own = NodeBudget::new(granted);
#[cfg(feature = "rayon")]
let objects = members
.par_iter()
.filter_map(|member| parse_member(&own, member))
.collect();
#[cfg(not(feature = "rayon"))]
let objects = members.iter().filter_map(|member| parse_member(&own, member)).collect();
budget.refund(own.left());
objects
} else {
// The budget may run out part-way, so the members are parsed in index order and the
// ones skipped are the same on every load.
budget.refund(granted);
members
.iter()
.filter_map(|member| parse_member(budget, member))
.collect()
};
if skipped.load(Ordering::Relaxed) {
warn!("object stream: the object budget is spent; remaining members were skipped");
}
Ok(ObjectStream {
objects,
+82 -20
View File
@@ -3,6 +3,7 @@ use crate::Error;
use crate::content::*;
use crate::error;
use crate::xref::*;
use std::cell::Cell;
use std::collections::HashSet;
use std::str::{self, FromStr};
@@ -27,6 +28,19 @@ pub(crate) type NomError<'a> = nom::error::Error<ParserInput<'a>>;
pub(crate) type NomResult<'a, O, E = NomError<'a>> = IResult<ParserInput<'a>, O, E>;
/// PdfCraft patch: objects one top-level parse may build, counting every array element and
/// dictionary value at any depth (the same cap as `pdfcraft_cos`'s `MAX_NODES`). Each object
/// costs a hundred bytes or more, so a decoded stream of `0 0 0 ...` otherwise built one per
/// two input bytes: gigabytes from a stream inside the decompression limit. Real arrays (page
/// trees, parent trees, widths) stay far below.
pub(crate) const MAX_OBJECT_NODES: usize = 1 << 22;
/// PdfCraft patch: the budget of a container parsed outside `_direct_object` (an indirect
/// object's body, a content-stream operand, a CMap or inline-image dictionary). Its contents are
/// charged but the container itself isn't, so it starts one short and the whole object stays
/// within `MAX_OBJECT_NODES`. (`MAX_OBJECT_NODES` is a nonzero constant, so this can't underflow.)
const MAX_NESTED_NODES: usize = MAX_OBJECT_NODES - 1;
#[inline]
fn strip_nom<O>(r: NomResult<O>) -> Option<O> {
r.ok().map(|(_, o)| o)
@@ -270,33 +284,48 @@ fn boolean(input: ParserInput) -> NomResult<Object> {
.parse(input)
}
/// `null`.
fn null(input: ParserInput) -> NomResult<Object> {
map(tag(&b"null"[..]), |_| Object::Null).parse(input)
}
fn array(depth: usize) -> impl Fn(ParserInput) -> NomResult<Vec<Object>> {
/// An array, nested at most `depth` levels. PdfCraft patch: every element is charged to `nodes`
/// (see `_direct_object`), which bounds the element count of one array and of all arrays nested
/// in it.
fn array(depth: usize, nodes: &Cell<usize>) -> impl Fn(ParserInput) -> NomResult<Vec<Object>> {
move |input| {
delimited(
pair(tag(&b"["[..]), space),
many0(_direct_object(depth)),
many0(_direct_object(depth, nodes)),
tag(&b"]"[..]),
)
.parse(input)
}
}
/// A dictionary, from a node budget of its own (`MAX_NESTED_NODES`).
pub(crate) fn dictionary(input: ParserInput) -> NomResult<Dictionary> {
_dictionary(crate::reader::MAX_NESTING_DEPTH)(input)
let nodes = Cell::new(MAX_NESTED_NODES);
_dictionary(crate::reader::MAX_NESTING_DEPTH, &nodes)(input)
}
fn _dictionary(depth: usize) -> impl Fn(ParserInput) -> NomResult<Dictionary> {
move |input| delimited(pair(tag(&b"<<"[..]), space), inner_dictionary(depth), tag(&b">>"[..])).parse(input)
/// `<< ... >>`, nested at most `depth` levels, its values charged to `nodes`.
fn _dictionary(depth: usize, nodes: &Cell<usize>) -> impl Fn(ParserInput) -> NomResult<Dictionary> {
move |input| {
delimited(
pair(tag(&b"<<"[..]), space),
inner_dictionary(depth, nodes),
tag(&b">>"[..]),
)
.parse(input)
}
}
fn inner_dictionary(depth: usize) -> impl Fn(ParserInput) -> NomResult<Dictionary> {
/// A dictionary's key-value pairs, without its delimiters; each value is charged to `nodes`.
fn inner_dictionary(depth: usize, nodes: &Cell<usize>) -> impl Fn(ParserInput) -> NomResult<Dictionary> {
move |input| {
fold_many0(
pair(terminated(name, space), _direct_object(depth)),
pair(terminated(name, space), _direct_object(depth, nodes)),
Dictionary::new,
|mut dict, (key, value)| {
dict.set(key, value);
@@ -307,7 +336,9 @@ fn inner_dictionary(depth: usize) -> impl Fn(ParserInput) -> NomResult<Dictionar
}
}
/// A CMap's `N dict dup begin /Key value def ...` dictionary, from a node budget of its own.
pub(crate) fn dict_dup(input: ParserInput) -> NomResult<Dictionary> {
let nodes = Cell::new(MAX_NESTED_NODES);
delimited(
(
digit1,
@@ -323,7 +354,7 @@ pub(crate) fn dict_dup(input: ParserInput) -> NomResult<Dictionary> {
terminated(
pair(
terminated(name, space),
_direct_object(crate::reader::MAX_NESTING_DEPTH),
_direct_object(crate::reader::MAX_NESTING_DEPTH, &nodes),
),
pair(tag(&b"def"[..]), multispace1),
),
@@ -434,7 +465,8 @@ fn reference(input: ParserInput) -> NomResult<Object> {
map(terminated(object_id, tag(&b"R"[..])), Object::Reference).parse(input)
}
fn _direct_objects(depth: usize) -> impl Fn(ParserInput) -> NomResult<Object> {
/// Any direct object, its nested arrays and dictionaries at most `depth` levels deep.
fn _direct_objects(depth: usize, nodes: &Cell<usize>) -> impl Fn(ParserInput) -> NomResult<Object> {
move |input| {
alt((
null,
@@ -445,34 +477,55 @@ fn _direct_objects(depth: usize) -> impl Fn(ParserInput) -> NomResult<Object> {
map(name, Object::Name),
map(literal_string, Object::string_literal),
hexadecimal_string,
map(array(depth), Object::Array),
map(_dictionary(depth), Object::Dictionary),
map(array(depth, nodes), Object::Array),
map(_dictionary(depth, nodes), Object::Dictionary),
))
.parse(input)
}
}
fn _direct_object(depth: usize) -> impl Fn(ParserInput) -> NomResult<Object> {
/// A direct object and the whitespace after it, charged one node once built; a spent budget
/// or a depth of 0 is a nom `Failure`.
fn _direct_object(depth: usize, nodes: &Cell<usize>) -> impl Fn(ParserInput) -> NomResult<Object> {
move |input| {
if depth == 0 {
return Err(nom::Err::Failure(NomError::from_error_kind(input, ErrorKind::TooLarge)));
}
terminated(_direct_objects(depth - 1), space).parse(input)
let (rest, object) = terminated(_direct_objects(depth - 1, nodes), space).parse(input)?;
// PdfCraft patch: charge each object once it is built, so a failed alternative costs
// nothing; its children were charged as they were built. A spent budget is a Failure,
// which ends the whole parse instead of backtracking into another alternative.
let Some(left) = nodes.get().checked_sub(1) else {
return Err(nom::Err::Failure(NomError::from_error_kind(input, ErrorKind::TooLarge)));
};
nodes.set(left);
Ok((rest, object))
}
}
/// One direct object from a fresh node budget. PdfCraft patch: object streams now parse through
/// `direct_object_within`; only tests use this.
#[cfg(test)]
pub fn direct_object(input: ParserInput) -> Option<Object> {
strip_nom(_direct_object(crate::reader::MAX_NESTING_DEPTH)(input))
direct_object_within(input, &Cell::new(MAX_OBJECT_NODES))
}
/// PdfCraft patch: parse one direct object, building at most `nodes` objects (the object itself
/// and everything nested in it) and leaving the unspent count in `nodes`.
pub(crate) fn direct_object_within(input: ParserInput, nodes: &Cell<usize>) -> Option<Object> {
strip_nom(_direct_object(crate::reader::MAX_NESTING_DEPTH, nodes)(input))
}
/// An indirect object's body (a stream or a direct object), from a node budget of its own.
fn object<'a>(
input: ParserInput<'a>, reader: &Reader, already_seen: &mut HashSet<ObjectId>, recover_stream_length: bool,
recovery_bound: Option<usize>,
) -> NomResult<'a, Object> {
let nodes = Cell::new(MAX_NESTED_NODES);
terminated(
alt((
|input| stream(input, reader, already_seen, recover_stream_length, recovery_bound),
_direct_objects(crate::reader::MAX_NESTING_DEPTH),
_direct_objects(crate::reader::MAX_NESTING_DEPTH, &nodes),
)),
space,
)
@@ -689,7 +742,9 @@ fn operator(input: ParserInput) -> NomResult<String> {
.parse(input)
}
/// One content-stream operand, from a node budget of its own.
fn operand(input: ParserInput) -> NomResult<Object> {
let nodes = Cell::new(MAX_NESTED_NODES);
terminated(
alt((
null,
@@ -699,7 +754,7 @@ fn operand(input: ParserInput) -> NomResult<Object> {
map(name, Object::Name),
map(literal_string, Object::string_literal),
hexadecimal_string,
map(array(crate::reader::MAX_NESTING_DEPTH), Object::Array),
map(array(crate::reader::MAX_NESTING_DEPTH, &nodes), Object::Array),
map(dictionary, Object::Dictionary),
)),
content_space,
@@ -724,8 +779,10 @@ fn inline_image(input: ParserInput) -> NomResult<(Vec<Object>, String)> {
preceded(pair(tag(&b"BI"[..]), content_space), cut(inline_image_impl)).parse(input)
}
/// An inline image after `BI`: its dictionary (from a node budget of its own) and data.
fn inline_image_impl(input: ParserInput) -> NomResult<(Vec<Object>, String)> {
let (input, stream_dict) = inner_dictionary(crate::reader::MAX_NESTING_DEPTH).parse(input)?;
let nodes = Cell::new(MAX_NESTED_NODES);
let (input, stream_dict) = inner_dictionary(crate::reader::MAX_NESTING_DEPTH, &nodes).parse(input)?;
let (input, _) = pair(tag(&b"ID"[..]), content_space).parse(input)?;
match image_data_stream(input, stream_dict) {
Ok((input, stream)) => {
@@ -1299,6 +1356,7 @@ EI";
.unwrap();
}
/// Arrays nested past the depth limit are an error, not a stack overflow.
#[test]
fn deeply_nested_array_is_rejected() {
on_big_stack(|| {
@@ -1306,11 +1364,13 @@ EI";
let mut input = Vec::with_capacity(depth * 2);
input.extend(std::iter::repeat_n(b'[', depth));
input.extend(std::iter::repeat_n(b']', depth));
let result = _direct_object(crate::reader::MAX_NESTING_DEPTH)(input.as_slice());
let result =
_direct_object(crate::reader::MAX_NESTING_DEPTH, &Cell::new(MAX_OBJECT_NODES))(input.as_slice());
assert!(result.is_err());
});
}
/// Dictionaries nested past the depth limit are an error, not a stack overflow.
#[test]
fn deeply_nested_dictionary_is_rejected() {
on_big_stack(|| {
@@ -1322,15 +1382,17 @@ EI";
for _ in 0..depth {
input.extend_from_slice(b">>");
}
let result = _direct_object(crate::reader::MAX_NESTING_DEPTH)(input.as_slice());
let result =
_direct_object(crate::reader::MAX_NESTING_DEPTH, &Cell::new(MAX_OBJECT_NODES))(input.as_slice());
assert!(result.is_err());
});
}
/// Nesting well within the limit still parses.
#[test]
fn modestly_nested_array_still_parses() {
let input = b"[[[[[1]]]]]";
let obj = _direct_object(crate::reader::MAX_NESTING_DEPTH)(test_span(input));
let obj = _direct_object(crate::reader::MAX_NESTING_DEPTH, &Cell::new(MAX_OBJECT_NODES))(test_span(input));
assert!(obj.is_ok());
}
}
+83 -42
View File
@@ -1,13 +1,13 @@
use log::{error, warn};
use std::cmp;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::convert::TryInto;
#[cfg(not(feature = "async"))]
use std::fs::File;
#[cfg(not(feature = "async"))]
use std::io::Read;
use std::path::Path;
use std::sync::Mutex;
use std::sync::{Mutex, PoisonError};
#[cfg(feature = "rayon")]
use rayon::prelude::*;
@@ -22,7 +22,7 @@ use crate::common_data_structures;
use crate::encryption::{self, EncryptionState};
use crate::error::{ParseError, XrefError};
use crate::load_options::{FilterFunc, LoadOptions};
use crate::object_stream::ObjectStream;
use crate::object_stream::{MAX_LOAD_NODES, NodeBudget, ObjectStream};
use crate::parser;
use crate::xref::{Xref, XrefEntry, XrefType};
use crate::{Dictionary, Document, Error, IncrementalDocument, Object, ObjectId, Result};
@@ -838,6 +838,8 @@ impl Reader<'_> {
Ok(self.document)
}
/// Load an encrypted document: read every object's raw bytes first, then decrypt and parse
/// them, object streams from one shared node budget.
fn load_encrypted_document(&mut self, _filter_func: Option<FilterFunc>) -> Result<()> {
// First, extract all raw object bytes without parsing
let entries: Vec<_> = self
@@ -849,6 +851,8 @@ impl Reader<'_> {
.collect();
let mut object_streams = Vec::new();
// PdfCraft patch: one object budget for every object stream this load parses.
let node_budget = NodeBudget::new(MAX_LOAD_NODES);
for (obj_num, entry) in entries {
match entry {
@@ -894,8 +898,9 @@ impl Reader<'_> {
}
}
let mut streams_to_process: std::collections::HashMap<u32, Vec<(u32, u16)>> =
std::collections::HashMap::new();
// PdfCraft patch: object streams in object-number order, so the members a spent node
// budget skips are the same on every load.
let mut streams_to_process: BTreeMap<u32, Vec<(u32, u16)>> = BTreeMap::new();
for (obj_num, container_id, index) in object_streams {
streams_to_process
.entry(container_id)
@@ -907,7 +912,11 @@ impl Reader<'_> {
if let Some(container_obj) = self.document.objects.get(&(container_id, 0))
&& let Ok(stream) = container_obj.as_stream()
{
match ObjectStream::new_with_limit(stream, self.max_decompressed_size) {
// PdfCraft patch: parse only the members the table places in this stream, so
// the others spend nothing from the budget.
let listed: BTreeSet<u32> = objects_in_stream.iter().map(|&(obj_num, _)| obj_num).collect();
let keep = |obj_num: u32| listed.contains(&obj_num);
match ObjectStream::new_members_within(stream, self.max_decompressed_size, &node_budget, keep) {
Ok(object_stream) => {
for (obj_num, _index) in objects_in_stream {
let obj_id = (obj_num, 0);
@@ -960,10 +969,12 @@ impl Reader<'_> {
self.document.reference_table = xref;
}
/// Load every object in the cross-reference table, expanding object streams from one node
/// budget shared by the whole load.
fn load_objects_raw(&mut self, filter_func: Option<FilterFunc>) -> Result<()> {
let is_encrypted = self.document.trailer.get(b"Encrypt").is_ok();
let zero_length_streams = Mutex::new(vec![]);
let object_streams = Mutex::new(vec![]);
let object_stream_ids = Mutex::new(vec![]);
// Build a map of which container each compressed object belongs to
// according to the xref. This prevents stale ObjStm copies (e.g., from
@@ -1014,36 +1025,10 @@ impl Reader<'_> {
if let Ok(stream) = object.as_stream() {
if stream.dict.has_type(b"ObjStm") && !is_encrypted {
let obj_stream = match ObjectStream::new_with_limit(stream, self.max_decompressed_size) {
Ok(obj_stream) => obj_stream,
// Not an encryption-related loss, so it obeys the same
// strict-mode policy as any other load error.
Err(e) => {
error!("Object stream load error for {object_id:?}: {e:?}");
return if self.strict { Err(e) } else { Ok(None) };
}
};
let container_id = object_id.0;
let mut object_streams = object_streams.lock().unwrap();
if let Some(filter_func) = filter_func {
let objects: BTreeMap<(u32, u16), Object> = obj_stream
.objects
.into_iter()
.filter(|((obj_num, _), _)| {
compressed_obj_containers
.get(obj_num)
.is_none_or(|&c| c == container_id)
})
.filter_map(|(object_id, mut object)| filter_func(object_id, &mut object))
.collect();
object_streams.extend(objects);
} else {
object_streams.extend(obj_stream.objects.into_iter().filter(|((obj_num, _), _)| {
compressed_obj_containers
.get(obj_num)
.is_none_or(|&c| c == container_id)
}));
}
// PdfCraft patch: object streams are expanded after this parallel pass,
// one at a time in object-number order (below).
let mut object_stream_ids = object_stream_ids.lock().unwrap_or_else(PoisonError::into_inner);
object_stream_ids.push(object_id);
} else if stream.content.is_empty() {
let mut zero_length_streams = zero_length_streams.lock().unwrap();
zero_length_streams.push(object_id);
@@ -1079,9 +1064,59 @@ impl Reader<'_> {
.collect::<Result<BTreeMap<_, _>>>()?;
}
// Only add entries, but never replace entries
for (id, entry) in object_streams.into_inner().unwrap() {
self.document.objects.entry(id).or_insert(entry);
// PdfCraft patch: expand the object streams one at a time in object-number order, from one
// node budget for the whole load, so many streams, each inside the decompression limit,
// cannot together build billions of objects, and the members a spent budget skips are the
// same on every load. A stream parses only the members it would add: none the table
// places in another stream (stale copies), and none already loaded, as an ordinary object
// or from an earlier stream, since a member never replaces an object. Those spend nothing.
// Members the table doesn't list at all are still parsed (a rebuilt table lists no
// compressed objects) and share the budget.
let node_budget = NodeBudget::new(MAX_LOAD_NODES);
let mut object_stream_ids = object_stream_ids.into_inner().unwrap_or_else(PoisonError::into_inner);
object_stream_ids.sort_unstable();
object_stream_ids.dedup();
for object_id in object_stream_ids {
let container_id = object_id.0;
let loaded = &self.document.objects;
let keep = |obj_num: u32| {
compressed_obj_containers
.get(&obj_num)
.is_none_or(|&c| c == container_id)
&& !loaded.contains_key(&(obj_num, 0))
};
let parsed = match loaded.get(&object_id).map(Object::as_stream) {
Some(Ok(stream)) => {
ObjectStream::new_members_within(stream, self.max_decompressed_size, &node_budget, keep)
}
_ => continue,
};
match parsed {
Ok(obj_stream) => {
let members: BTreeMap<_, _> = match filter_func {
Some(filter_func) => obj_stream
.objects
.into_iter()
.filter_map(|(object_id, mut object)| filter_func(object_id, &mut object))
.collect(),
None => obj_stream.objects,
};
// Only add entries, but never replace entries
for (id, entry) in members {
self.document.objects.entry(id).or_insert(entry);
}
}
// Not an encryption-related loss, so it obeys the same strict-mode policy as
// any other load error; a lenient load drops the stream, as it drops any object
// that fails to load.
Err(e) => {
error!("Object stream load error for {object_id:?}: {e:?}");
if self.strict {
return Err(e);
}
self.document.objects.remove(&object_id);
}
}
}
for object_id in zero_length_streams.into_inner().unwrap() {
@@ -1174,8 +1209,14 @@ impl Reader<'_> {
let container_id = (container_id, 0);
let container_obj = self.get_object(container_id, already_seen)?;
let container_stream = container_obj.as_stream()?;
let object_stream = ObjectStream::new_with_limit(container_stream, self.max_decompressed_size)?;
object_stream.objects.get(&id).cloned().ok_or(Error::MissingXrefEntry)
// PdfCraft patch: a lookup parses only the member it wants, from one object's budget
// rather than a load's, so the members before it can't spend that budget first.
let budget = NodeBudget::new(parser::MAX_OBJECT_NODES);
let mut object_stream =
ObjectStream::new_members_within(container_stream, self.max_decompressed_size, &budget, |obj_num| {
obj_num == id.0
})?;
object_stream.objects.remove(&id).ok_or(Error::MissingXrefEntry)
}
pub fn get_object(&self, id: ObjectId, already_seen: &mut HashSet<ObjectId>) -> Result<Object> {