mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-04 09:39:45 +00:00
M2: a reference to a reference is what it names
`IndirectObject<f32>` read an object holding `6 0 R` as the number 6, so `/Decode [11 0 R 0]`, with 11 naming 6 and 6 holding 1, read as 6, and `/W` gave glyphs such widths. As anything but a number, such an object was lost. `XRef::get_with` is how every reference is read, to an object stored on its own or in an object stream, so it now follows such objects in a loop, up to 32 references as `Document::resolve` does in #5548. A loop takes no stack however long the chain, and a cycle runs out of references and reads as a missing object, as a reference to nothing does: the image with such a `/Decode` isn't drawn, as with `/Decode [99 0 R 0]`. An object stream isn't reached that way: it has to be a stream stored as that object, and following a reference to one stored inside another let a 1 KB file run out of stack. `XRef::objects` leaves such objects out, or a page came out once more for each one holding a reference to it, and a comment inside a reference counts as white space, as it does everywhere else. Reading an object stream's index now counts against the 64 nested loads, and reads its dictionary alone. That is older than this branch, which only made it slightly worse: a chain of object streams, each with a member of the next for its `/N`, `/First` or `/Length`, recursed with no limit, holding a copy of the chain at each, and aborted on 750 KB with an 8 MiB stack, or 250 KB with 2 MiB, in a test build. Parsing the stream read `/Length` as well as `/N`, two ways to the next stream's index, and a failed index isn't remembered, so the work doubled at each stream: 20 streams in a ring took 20 s on `main`. ISO 32000-2 7.5.7 keeps an object stream's `/Length` out of object streams, so no legal file has a `/Length` chain. Nothing forbids `/N` or `/First` by reference, though no writer I know of makes such a chain. Past the limit it reads as missing unless a stream within 64 of it has been read. `/W` and `/W2` with their list by reference are tested too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY
This commit is contained in:
1 parent
33d7a51301
commit
4303d49eea
6 files changed
+384
-22
No files matched your search
@@ -1093,13 +1093,74 @@ fn a_decode_array_with_references_in_it_is_read() {
|
||||
for decode in ["[6 0 R 0 1 0 1 0]", "[1 0 6 0 R 0 1 0]", "[1 0 1 0 6 0 R 0]", "[6 0 R 7 0 R 6 0 R 7 0 R 6 0 R 7 0 R]"] {
|
||||
assert_eq!(render("1", decode, "/DeviceRGB", "204060>"), rgb, "{decode}");
|
||||
}
|
||||
// A reference that only leads back to itself holds no number. The read ends, and the image is
|
||||
// drawn over the red under it.
|
||||
// A reference that only leads back to itself holds no number, and reads as one that names
|
||||
// nothing does.
|
||||
let missing = render("1", "[99 0 R 0]", "/DeviceGray", "40>");
|
||||
for decode in ["[8 0 R 0]", "[1 8 0 R]", "[9 0 R 0]", "[1 9 0 R]", "[8 0 R 9 0 R]"] {
|
||||
assert_ne!(render("1", decode, "/DeviceGray", "40>"), [255, 0, 0, 255], "{decode}");
|
||||
assert_eq!(render("1", decode, "/DeviceGray", "40>"), missing, "{decode}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An object that holds only a reference stands for what that names, stored on its own or in an
|
||||
/// object stream. Read as a number it was the reference's own object number: here 8 names 7, 7
|
||||
/// names 6 and 6 holds 1, and that read as 7, which drew white. A chain past the limit, and so a
|
||||
/// cycle, reads as a missing object does.
|
||||
#[test]
|
||||
fn a_reference_to_a_reference_is_what_it_names() {
|
||||
use super::*;
|
||||
let file = |decode: &str, objects: &str| -> Vec<u8> {
|
||||
let content = "1 0 0 rg 0 0 200 200 re f q 200 0 0 200 0 0 cm /Im Do Q";
|
||||
format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject << /Im 5 0 R >> >> /Contents 4 0 R >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
5 0 obj << /Type /XObject /Subtype /Image /Width 1 /Height 1 /BitsPerComponent 8 /ColorSpace /DeviceGray /Decode {decode} /Filter /ASCIIHexDecode /Length 3 >> stream\n40>\nendstream endobj\n\
|
||||
{objects}\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF",
|
||||
content.len()
|
||||
)
|
||||
.into_bytes()
|
||||
};
|
||||
let draw = |bytes: Vec<u8>| -> [u8; 4] {
|
||||
let page = PageRenderer::new(Arc::new(bytes), RenderConfig::default()).render(RenderRequest {
|
||||
page: 0,
|
||||
kind: RequestKind::Pixels,
|
||||
tile: None,
|
||||
scale: 1.0,
|
||||
tag: 0,
|
||||
preview: false,
|
||||
});
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
let start = (100 * page.width as usize + 100) * 4;
|
||||
let mut pixel = [0; 4];
|
||||
pixel.copy_from_slice(page.rgba.get(start..start + 4).expect("centre pixel"));
|
||||
pixel
|
||||
};
|
||||
let grey = draw(file("[1 0]", ""));
|
||||
assert_eq!(grey, [191, 191, 191, 255]);
|
||||
|
||||
let chain = "6 0 obj 1 endobj 7 0 obj 6 0 R endobj 8 0 obj 7 0 R endobj";
|
||||
assert_eq!(draw(file("[8 0 R 0]", chain)), grey, "stored on their own");
|
||||
let doc = pdfcraft_cos::Document::open(Arc::new(file("[8 0 R 0]", chain))).unwrap();
|
||||
let packed = pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap();
|
||||
assert!(packed.windows(7).any(|w| w == b"/ObjStm"), "the save packs them");
|
||||
assert_eq!(draw(packed), grey, "stored in an object stream");
|
||||
assert_eq!(draw(file("9 0 R", "9 0 obj 10 0 R endobj 10 0 obj [1 0] endobj")), grey, "not only numbers");
|
||||
let commented = "6 0 obj 1 endobj 7 0 obj 6 %c\n0 R endobj 8 0 obj 7 0 %c\nR endobj";
|
||||
assert_eq!(draw(file("[8 %c\n0 R 0]", commented)), grey, "a comment counts as white space");
|
||||
|
||||
let links = |n: usize| -> String {
|
||||
let links: String = (0..n).map(|i| format!("{} 0 obj {} 0 R endobj\n", 10 + i, 11 + i)).collect();
|
||||
format!("{links}{} 0 obj 1 endobj", 10 + n)
|
||||
};
|
||||
let missing = draw(file("[99 0 R 0]", ""));
|
||||
assert_ne!(missing, grey);
|
||||
assert_eq!(draw(file("[10 0 R 0]", &links(32))), grey, "32 references are followed");
|
||||
assert_eq!(draw(file("[10 0 R 0]", &links(33))), missing, "33 aren't");
|
||||
assert_eq!(draw(file("[6 0 R 0]", "6 0 obj 6 0 R endobj")), missing, "nor is a cycle");
|
||||
}
|
||||
|
||||
/// A function's `/Encode`, `/Decode`, `/Domain` and `/Range` are read a pair at a time too, so they
|
||||
/// lost a reference at the start of a pair the same way, and the array with it. Each form is compared
|
||||
/// with the direct one, which differs from the identity so the array is shown to count.
|
||||
|
||||
Vendored
+1
-1
@@ -43,7 +43,7 @@ Other resource categories retain their existing parent-chain lookup.
|
||||
| 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, 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, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at 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); (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 stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of thLine truncated
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (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) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) |
|
||||
| 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` |
|
||||
| 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
|
||||
| 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 |
|
||||
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate |
|
||||
|
||||
+12
-3
@@ -713,6 +713,7 @@ mod width_tests {
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >> endobj\n\
|
||||
4 0 obj 20 endobj\n5 0 obj {array} endobj\n6 0 obj 22 endobj\n\
|
||||
7 0 obj 7 0 R endobj\n8 0 obj 9 0 R endobj\n9 0 obj 8 0 R endobj\n\
|
||||
10 0 obj 4 0 R endobj\n11 0 obj [500 600] endobj\n12 0 obj [-1000 500 880] endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF\n"
|
||||
);
|
||||
Pdf::new(pdf.into_bytes()).unwrap()
|
||||
@@ -752,12 +753,20 @@ mod width_tests {
|
||||
assert_eq!(vertical("[20 22 -900 400 800]"), by_range);
|
||||
assert_eq!(vertical("[4 0 R 22 -900 400 800]"), by_range);
|
||||
|
||||
// A reference that only leads back to itself holds no number. The reads end.
|
||||
// A group's list can be given by reference too, and a reference to a reference is what it
|
||||
// names.
|
||||
let by_list = vec![(20, 500.0), (21, 600.0)];
|
||||
assert_eq!(widths("[20 11 0 R]"), by_list);
|
||||
assert_eq!(widths("[10 0 R [500 600]]"), by_list);
|
||||
assert_eq!(widths("[10 0 R 11 0 R]"), by_list);
|
||||
assert_eq!(vertical("[20 12 0 R]"), vec![(20, [-1000.0, 500.0, 880.0])]);
|
||||
|
||||
// A reference that only leads back to itself holds no number, so those glyphs keep `/DW`.
|
||||
for array in ["[7 0 R [500 600]]", "[8 0 R [500 600]]", "[20 7 0 R 700]", "[7 0 R 8 0 R 700]", "[20 [7 0 R 600]]"] {
|
||||
widths(array);
|
||||
assert!(widths(array).is_empty(), "{array}");
|
||||
}
|
||||
for array in ["[7 0 R [-1000 500 880]]", "[8 0 R 22 -900 400 800]", "[20 [7 0 R 500 880]]"] {
|
||||
vertical(array);
|
||||
assert!(vertical(array).is_empty(), "{array}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+9
-3
@@ -1,5 +1,4 @@
|
||||
use crate::object::ObjectIdentifier;
|
||||
use crate::object::Stream;
|
||||
use crate::reader::ReaderContext;
|
||||
use crate::sync::HashMap;
|
||||
use crate::sync::{Arc, Mutex, MutexExt};
|
||||
@@ -92,6 +91,12 @@ impl Data {
|
||||
&self.data
|
||||
}
|
||||
|
||||
/// PdfCraft patch: (hayro-syntax (33)) enter the gate for what an object stream's index depends
|
||||
/// on, once its data is read and [`Self::get_with`] has let go of it.
|
||||
pub(crate) fn enter_loading(&self, id: ObjectIdentifier) -> Option<LoadGuard<'_>> {
|
||||
self.loading.enter(id)
|
||||
}
|
||||
|
||||
/// Get access to the data of a decoded object stream.
|
||||
pub(crate) fn get_with(&self, id: ObjectIdentifier, ctx: &ReaderContext<'_>) -> Option<&[u8]> {
|
||||
// PdfCraft patch: (#307, see vendor/README.md hayro-syntax (10)) register exactly once:
|
||||
@@ -110,7 +115,8 @@ impl Data {
|
||||
let _loading = self.loading.enter(id)?;
|
||||
self.decoded
|
||||
.get_or_init(idx, || {
|
||||
let stream = ctx.xref().get_with::<Stream<'_>>(id, ctx)?;
|
||||
// PdfCraft patch: (hayro-syntax (33)) only ever an object stream.
|
||||
let stream = ctx.xref().object_stream(id, ctx)?;
|
||||
stream.decoded().ok().map(Cow::into_owned)
|
||||
})?
|
||||
.as_deref()
|
||||
@@ -244,7 +250,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadGuard<'a>(&'a LoadGate);
|
||||
pub(crate) struct LoadGuard<'a>(&'a LoadGate);
|
||||
|
||||
impl Drop for LoadGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
|
||||
+5
-4
@@ -39,10 +39,11 @@ impl From<ObjectIdentifier> for ObjRef {
|
||||
|
||||
impl Skippable for ObjRef {
|
||||
fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> {
|
||||
// PdfCraft patch: (hayro-syntax (33)) a comment counts as white space, here too.
|
||||
r.skip::<i32>(false)?;
|
||||
r.skip_white_spaces();
|
||||
r.skip_white_spaces_and_comments();
|
||||
r.skip::<i32>(false)?;
|
||||
r.skip_white_spaces();
|
||||
r.skip_white_spaces_and_comments();
|
||||
r.forward_tag(b"R")?;
|
||||
|
||||
Some(())
|
||||
@@ -52,9 +53,9 @@ impl Skippable for ObjRef {
|
||||
impl Readable<'_> for ObjRef {
|
||||
fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option<Self> {
|
||||
let obj_ref = r.read_without_context::<i32>()?;
|
||||
r.skip_white_spaces();
|
||||
r.skip_white_spaces_and_comments();
|
||||
let gen_num = r.read_without_context::<i32>()?;
|
||||
r.skip_white_spaces();
|
||||
r.skip_white_spaces_and_comments();
|
||||
r.forward_tag(b"R")?;
|
||||
|
||||
Some(Self::new(obj_ref, gen_num))
|
||||
|
||||
Vendored
+293
-8
@@ -12,7 +12,7 @@ use crate::object::dict::keys::{
|
||||
};
|
||||
use crate::object::dict::{DictCache, probe_dict};
|
||||
use crate::object::indirect::IndirectObject;
|
||||
use crate::object::{Array, MaybeRef};
|
||||
use crate::object::{Array, MaybeRef, ObjRef};
|
||||
use crate::object::{DateTime, Dict};
|
||||
use crate::object::{Object, ObjectLike};
|
||||
use crate::pdf::PdfVersion;
|
||||
@@ -31,6 +31,17 @@ use core::ops::Deref;
|
||||
|
||||
pub(crate) const XREF_ENTRY_LEN: usize = 20;
|
||||
|
||||
/// PdfCraft patch: (hayro-syntax (33)) how many references a read follows through objects that hold
|
||||
/// nothing else. Past it, as any cycle goes, the object reads as a missing one.
|
||||
const MAX_REFERENCE_HOPS: usize = 32;
|
||||
|
||||
/// PdfCraft patch: (hayro-syntax (33)) what [`XRef::fetch`] found at an object's place.
|
||||
enum Fetched<T> {
|
||||
Object(T),
|
||||
/// All the object holds is a reference to this one.
|
||||
Reference(ObjectIdentifier),
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(crate) enum XRefError {
|
||||
Unknown,
|
||||
@@ -492,7 +503,11 @@ impl XRef {
|
||||
|
||||
iter::from_fn(move || {
|
||||
for next in iter.by_ref() {
|
||||
if let Some(obj) = self.get_with(next.0, &ReaderContext::new(self, false)) {
|
||||
// PdfCraft patch: (hayro-syntax (33)) an object that only refers to another
|
||||
// isn't one of its own: followed, that one came out once more for each.
|
||||
if let Some(Fetched::Object(obj)) =
|
||||
self.fetch(next.0, &ReaderContext::new(self, false))
|
||||
{
|
||||
return Some(obj);
|
||||
} else {
|
||||
// Skip invalid objects.
|
||||
@@ -563,12 +578,48 @@ impl XRef {
|
||||
}
|
||||
|
||||
/// Return the object with the given identifier.
|
||||
///
|
||||
/// PdfCraft patch: (hayro-syntax (33)) an object that holds only a reference stands for what
|
||||
/// that names. Read as a number it was the reference's own object number, and as anything else
|
||||
/// it was lost. This is a loop, so a long chain takes no stack.
|
||||
#[allow(private_bounds)]
|
||||
pub(crate) fn get_with<'a, T>(
|
||||
&'a self,
|
||||
id: ObjectIdentifier,
|
||||
ctx: &ReaderContext<'a>,
|
||||
) -> Option<T>
|
||||
where
|
||||
T: ObjectLike<'a>,
|
||||
{
|
||||
let mut id = id;
|
||||
for _ in 0..=MAX_REFERENCE_HOPS {
|
||||
match self.fetch::<T>(id, ctx)? {
|
||||
Fetched::Object(object) => return Some(object),
|
||||
Fetched::Reference(next) => id = next,
|
||||
}
|
||||
}
|
||||
warn!("references lead on past the limit, or in a cycle: {id:?}");
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// PdfCraft patch: (hayro-syntax (33)) the object stream `id`. It has to be a stream stored as
|
||||
/// that object (ISO 32000-2 7.5.7), so this follows no reference: the check of where it is stored
|
||||
/// is of that object, and one reached through a reference could be a stream stored inside
|
||||
/// another.
|
||||
pub(crate) fn object_stream<'a>(
|
||||
&'a self,
|
||||
id: ObjectIdentifier,
|
||||
ctx: &ReaderContext<'a>,
|
||||
) -> Option<Stream<'a>> {
|
||||
match self.fetch::<Stream<'a>>(id, ctx)? {
|
||||
Fetched::Object(stream) => Some(stream),
|
||||
Fetched::Reference(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What is stored at the object with the given identifier.
|
||||
fn fetch<'a, T>(&'a self, id: ObjectIdentifier, ctx: &ReaderContext<'a>) -> Option<Fetched<T>>
|
||||
where
|
||||
T: ObjectLike<'a>,
|
||||
{
|
||||
@@ -597,9 +648,13 @@ impl XRef {
|
||||
ctx.set_in_object_stream(false);
|
||||
r.jump(offset);
|
||||
|
||||
if let Some(next) = held_reference(r.clone(), id) {
|
||||
return Some(Fetched::Reference(next));
|
||||
}
|
||||
|
||||
if let Some(object) = r.read_with_context::<IndirectObject<T>>(&ctx) {
|
||||
if object.id() == &id {
|
||||
return Some(object.get());
|
||||
return Some(Fetched::Object(object.get()));
|
||||
}
|
||||
} else {
|
||||
// There is a valid object at the offset, it's just not of the type the caller
|
||||
@@ -622,7 +677,7 @@ impl XRef {
|
||||
self.repair();
|
||||
|
||||
// Now try reading again.
|
||||
self.get_with::<T>(id, &ctx)
|
||||
self.fetch::<T>(id, &ctx)
|
||||
}
|
||||
}
|
||||
EntryType::ObjStream(obj_stram_gen_num, index) => {
|
||||
@@ -657,11 +712,20 @@ impl XRef {
|
||||
// A stream whose pairs don't parse stays unreadable, as it was.
|
||||
Some(offsets) => offsets?,
|
||||
None => {
|
||||
let stream = self.get_with::<Stream<'_>>(obj_stream_id, &ctx)?;
|
||||
// PdfCraft patch: (hayro-syntax (33)) this read can reach another object
|
||||
// stream, whose `/N` or `/First` can be a member of the next: the gate's
|
||||
// limit holds here too, or a chain of them ran out of stack. It reads the
|
||||
// dictionary, which is all it needs: parsing the stream reads `/Length`
|
||||
// too, a second way to the next stream's index, which doubled at each.
|
||||
let _loading = repr.data.enter_loading(obj_stream_id)?;
|
||||
let Fetched::Object(dict) = self.fetch::<Dict<'_>>(obj_stream_id, &ctx)?
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
// `/N` and `/First` may be references that can't be followed while
|
||||
// another stream loads: reading them fails without being remembered.
|
||||
let num_objects = stream.dict().get::<usize>(N)?;
|
||||
let first_offset = stream.dict().get::<usize>(FIRST)?;
|
||||
let num_objects = dict.get::<usize>(N)?;
|
||||
let first_offset = dict.get::<usize>(FIRST)?;
|
||||
let parsed =
|
||||
read_object_stream_index(num_objects, first_offset, data).map(Arc::new);
|
||||
self.with_object_stream_indexes(|indexes| {
|
||||
@@ -673,7 +737,12 @@ impl XRef {
|
||||
.unwrap_or(parsed)?
|
||||
}
|
||||
};
|
||||
ObjectStream::with_offsets(data, &ctx, offsets).get(index)
|
||||
let stream = ObjectStream::with_offsets(data, &ctx, offsets);
|
||||
if let Some(next) = stream.reference(index) {
|
||||
return Some(Fetched::Reference(next));
|
||||
}
|
||||
|
||||
stream.get(index).map(Fetched::Object)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1232,6 +1301,28 @@ impl<'a> ObjectStream<'a> {
|
||||
|
||||
r.read_with_context::<T>(&self.ctx)
|
||||
}
|
||||
|
||||
/// PdfCraft patch: (hayro-syntax (33)) what the object at `index` refers to, when a reference is
|
||||
/// all it holds.
|
||||
fn reference(&self, index: u32) -> Option<ObjectIdentifier> {
|
||||
let offset = self.offsets.get(index as usize)?.1;
|
||||
let mut r = Reader::new(self.data);
|
||||
r.jump(offset);
|
||||
r.skip_white_spaces_and_comments();
|
||||
|
||||
Some(r.read_without_context::<ObjRef>()?.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch: (hayro-syntax (33)) what the indirect object `id` at `r` refers to, when a
|
||||
/// reference is all it holds.
|
||||
fn held_reference(mut r: Reader<'_>, id: ObjectIdentifier) -> Option<ObjectIdentifier> {
|
||||
if r.read_without_context::<ObjectIdentifier>()? != id {
|
||||
return None;
|
||||
}
|
||||
r.skip_white_spaces_and_comments();
|
||||
|
||||
Some(r.read_without_context::<ObjRef>()?.into())
|
||||
}
|
||||
|
||||
fn parse_metadata(info_dict: &Dict<'_>) -> Metadata {
|
||||
@@ -1266,6 +1357,200 @@ fn parse_metadata(info_dict: &Dict<'_>) -> Metadata {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Pdf;
|
||||
|
||||
/// A file with an xref stream: `stored` are objects on their own, as they would follow
|
||||
/// `n 0 obj`, and `packed` says of each object in an object stream which stream and place.
|
||||
fn with_xref_stream(stored: &[(u32, Vec<u8>)], packed: &[(u32, u32, u16)]) -> Vec<u8> {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = alloc::collections::BTreeMap::new();
|
||||
for (num, body) in stored {
|
||||
offsets.insert(*num, out.len());
|
||||
out.extend_from_slice(alloc::format!("{num} 0 obj ").as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let last = stored.iter().map(|o| o.0).chain(packed.iter().map(|o| o.0)).max().unwrap_or(0);
|
||||
let (xref, size) = (last + 1, last + 2);
|
||||
let at = out.len();
|
||||
offsets.insert(xref, at);
|
||||
let packed: alloc::collections::BTreeMap<u32, (u32, u16)> = packed.iter().map(|o| (o.0, (o.1, o.2))).collect();
|
||||
let mut rows = Vec::new();
|
||||
for num in 0..size {
|
||||
if let Some(offset) = offsets.get(&num) {
|
||||
rows.push(1);
|
||||
rows.extend_from_slice(&(*offset as u32).to_be_bytes());
|
||||
rows.extend_from_slice(&[0, 0]);
|
||||
} else if let Some((stream, index)) = packed.get(&num) {
|
||||
rows.push(2);
|
||||
rows.extend_from_slice(&stream.to_be_bytes());
|
||||
rows.extend_from_slice(&index.to_be_bytes());
|
||||
} else {
|
||||
rows.extend_from_slice(&[0; 7]);
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(
|
||||
alloc::format!(
|
||||
"{xref} 0 obj << /Type /XRef /Size {size} /W [1 4 2] /Root 1 0 R /Length {} >> stream\n",
|
||||
rows.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
out.extend_from_slice(&rows);
|
||||
out.extend_from_slice(alloc::format!("\nendstream endobj\nstartxref\n{at}\n%%EOF\n").as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// `/Type /ObjStm` around `members`, each stored at its offset, and `entries` of its own.
|
||||
fn object_stream_of(members: &[(u32, &[u8])], entries: &str) -> Vec<u8> {
|
||||
let (mut head, mut body) = (alloc::string::String::new(), Vec::new());
|
||||
for (num, member) in members {
|
||||
head.push_str(&alloc::format!("{num} {} ", body.len()));
|
||||
body.extend_from_slice(member);
|
||||
body.push(b'\n');
|
||||
}
|
||||
head.push('\n');
|
||||
let dict = alloc::format!(
|
||||
"<< /Type /ObjStm /N {} /First {} /Length {} {entries} >> stream\n",
|
||||
members.len(),
|
||||
head.len(),
|
||||
head.len() + body.len()
|
||||
);
|
||||
let mut out = dict.into_bytes();
|
||||
out.extend_from_slice(head.as_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
out.extend_from_slice(b"\nendstream");
|
||||
out
|
||||
}
|
||||
|
||||
fn page_objects() -> Vec<(u32, Vec<u8>)> {
|
||||
vec![
|
||||
(1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
|
||||
(2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
|
||||
(3, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_vec()),
|
||||
]
|
||||
}
|
||||
|
||||
/// An object stream is a stream stored as that object, however many references lead to one.
|
||||
/// Object 10 holds a reference to 11, a stream stored inside object stream 12, and 31 claims to
|
||||
/// be in 10, with 11's `/N`, `/First` or `/Length` being 31: reading it recursed until the
|
||||
/// stack ran out. It reads as missing, and so does a member of such a stream.
|
||||
#[test]
|
||||
fn an_object_stream_isnt_reached_through_a_reference() {
|
||||
for key in ["N", "First", "Length"] {
|
||||
let inner = alloc::format!("<< /Type /ObjStm /{key} 31 0 R >> stream\n31 0 1\n\nendstream");
|
||||
let mut stored = page_objects();
|
||||
stored.push((10, b"11 0 R".to_vec()));
|
||||
stored.push((12, object_stream_of(&[(11, inner.as_bytes())], "")));
|
||||
let pdf = Pdf::new(with_xref_stream(&stored, &[(11, 12, 0), (31, 10, 0)])).unwrap();
|
||||
assert_eq!(pdf.xref().get::<i32>(ObjectIdentifier::new(31, 0)), None, "{key}");
|
||||
}
|
||||
let inner = b"<< /Type /ObjStm /N 1 /First 5 /Length 8 >> stream\n20 0 7\n\nendstream";
|
||||
let mut stored = page_objects();
|
||||
stored.push((10, b"11 0 R".to_vec()));
|
||||
stored.push((12, object_stream_of(&[(11, inner)], "")));
|
||||
let pdf = Pdf::new(with_xref_stream(&stored, &[(11, 12, 0), (20, 10, 0)])).unwrap();
|
||||
assert_eq!(pdf.xref().get::<i32>(ObjectIdentifier::new(20, 0)), None);
|
||||
}
|
||||
|
||||
/// `count` object streams stored as themselves, the `keys` of each a member of the next, or
|
||||
/// with `ring` of the first after the last. Reading the first member reads them all, and it is
|
||||
/// `count + 100` to tell.
|
||||
fn chain_of_object_streams(count: u32, keys: &[&str], ring: bool) -> Vec<u8> {
|
||||
let mut stored = page_objects();
|
||||
let mut packed = Vec::new();
|
||||
for i in 0..count {
|
||||
let (stream, member) = (100 + 2 * i, 101 + 2 * i);
|
||||
let value = if i == 0 { count + 100 } else { 1 };
|
||||
let data = alloc::format!("{member} 0 \n{value}\n");
|
||||
let (first, length) = (alloc::format!("{}", alloc::format!("{member} 0 \n").len()), alloc::format!("{}", data.len()));
|
||||
let next = match (i + 1 == count, ring) {
|
||||
(true, true) => "101 0 R".into(),
|
||||
(true, false) => "1".into(),
|
||||
_ => alloc::format!("{} 0 R", member + 2),
|
||||
};
|
||||
let entry = |key, own: &'_ str| if keys.contains(&key) { next.clone() } else { own.into() };
|
||||
let (n, first, length): (alloc::string::String, alloc::string::String, alloc::string::String) =
|
||||
(entry("N", "1"), entry("First", &first), entry("Length", &length));
|
||||
let body = alloc::format!("<< /Type /ObjStm /N {n} /First {first} /Length {length} >> stream\n{data}\nendstream");
|
||||
stored.push((stream, body.into_bytes()));
|
||||
packed.push((member, stream, 0));
|
||||
}
|
||||
with_xref_stream(&stored, &packed)
|
||||
}
|
||||
|
||||
/// A chain of object streams, each with a member of the next for its `/N`, `/First` or
|
||||
/// `/Length`, had no limit: one read recursed through all of them, holding a copy of the chain
|
||||
/// at each, and 50,000 ran out of an 8 MiB stack. It stops at the gate's limit, on half the stack
|
||||
/// of a render worker. Past that `/N` and `/First` can't be read, so the member reads as missing,
|
||||
/// and a `/Length` that can't be read falls back on `endstream`, so it reads. A short chain reads.
|
||||
#[test]
|
||||
fn a_chain_of_object_streams_ends_at_the_limit_of_nested_loads() {
|
||||
for key in ["N", "First", "Length"] {
|
||||
let pdf = chain_of_object_streams(50_000, &[key], false);
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1 << 20)
|
||||
.spawn(move || {
|
||||
let pdf = Pdf::new(pdf).unwrap();
|
||||
let read = pdf.xref().get::<i32>(ObjectIdentifier::new(101, 0));
|
||||
assert_eq!(read, (key == "Length").then_some(50_100), "{key}");
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
let pdf = Pdf::new(chain_of_object_streams(10, &["N"], false)).unwrap();
|
||||
assert_eq!(pdf.xref().get::<i32>(ObjectIdentifier::new(101, 0)), Some(110));
|
||||
}
|
||||
|
||||
/// `/Length` and `/N` or `/First` both by reference were two ways to the next stream's index,
|
||||
/// and an index that fails isn't remembered, so the work doubled at each stream: 65 streams, one
|
||||
/// past the limit, in 8 KB, didn't finish, and other threads waited at the gate. The index reads
|
||||
/// the dictionary alone now. Without that this doesn't end, so the time allowed can't fail it.
|
||||
#[test]
|
||||
fn a_chain_of_object_streams_takes_no_more_work_for_two_ways_on() {
|
||||
for (count, ring) in [(65, false), (20, true), (5_000, false)] {
|
||||
for keys in [&["Length", "N"][..], &["Length", "First"]] {
|
||||
let pdf = chain_of_object_streams(count, keys, ring);
|
||||
let (done, finished) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.stack_size(1 << 20)
|
||||
.spawn(move || {
|
||||
let pdf = Pdf::new(pdf).unwrap();
|
||||
let _ = pdf.xref().get::<i32>(ObjectIdentifier::new(101, 0));
|
||||
let _ = done.send(());
|
||||
})
|
||||
.unwrap();
|
||||
assert!(finished.recv_timeout(std::time::Duration::from_secs(120)).is_ok(), "{keys:?} of {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Object 5, a member of a real object stream, holds a reference to object 6 stored on its own,
|
||||
/// and 7, stored on its own, to 8, a member: each reads as what it names.
|
||||
#[test]
|
||||
fn a_reference_held_in_either_storage_is_followed() {
|
||||
let mut stored = page_objects();
|
||||
stored.push((6, b"42".to_vec()));
|
||||
stored.push((7, b"8 0 R".to_vec()));
|
||||
stored.push((9, object_stream_of(&[(5, b"6 0 R"), (8, b"43")], "")));
|
||||
let pdf = Pdf::new(with_xref_stream(&stored, &[(5, 9, 0), (8, 9, 1)])).unwrap();
|
||||
assert_eq!(pdf.xref().get::<i32>(ObjectIdentifier::new(5, 0)), Some(42));
|
||||
assert_eq!(pdf.xref().get::<i32>(ObjectIdentifier::new(7, 0)), Some(43));
|
||||
}
|
||||
|
||||
/// With no page tree, every page object is a page, and one that another object only refers to
|
||||
/// is one page, not two.
|
||||
#[test]
|
||||
fn a_page_a_reference_is_held_to_is_found_once() {
|
||||
let mut stored = page_objects();
|
||||
stored[0].1 = b"<< /Type /Catalog /Pages 99 0 R >>".to_vec();
|
||||
stored[2].1 = b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Contents 4 0 R >>".to_vec();
|
||||
stored.push((4, b"<< /Length 0 >> stream\n\nendstream".to_vec()));
|
||||
stored.push((12, b"3 0 R".to_vec()));
|
||||
let pdf = Pdf::new(with_xref_stream(&stored, &[])).unwrap();
|
||||
assert_eq!(pdf.pages().len(), 1);
|
||||
}
|
||||
|
||||
// PdfCraft patch tests (ported from craft-libs): xref stream entries are bounded by the
|
||||
// decoded data, and the type field is read at its full width.
|
||||
|
||||
Reference in new issue
Block a user