fix(render): a JBIG2 page's segments are bounded in what they hold and refer to (hayro-jbig2 patches 5 to 9, hayro-syntax 29)

Each JBIG2 bitmap was bounded on its own, but a few kilobytes could still exhaust memory:
nothing bounded what a page's segments hold for later ones, or how far one segment could
multiply them. Measured on black-box streams, peak memory before and after:

- intermediate regions, 16 in 774 bytes: 514 MiB, now 98 MiB;
- an 8 MiB symbol exported 1,200 times, a 2,989-byte PDF: killed at 8 GiB, now 79 MB;
- dictionaries of zero-width symbols: 781 MB, now 72 MB;
- dictionaries retaining their coding contexts, 1.1 MB: 2.89 GB, now 71 MB;
- 65,535 references to one dictionary, 78 KB: about 17 GB, now 6 MB;
- a halftone grid of 16,384 cells a side, 98 bytes: 1.1 GB, now 2.4 MB;
- a pattern dictionary of 65,535 patterns, 48 bytes: 539 MB, now 15 MB, and it still draws;
- a custom Huffman table behind nested Flate, a 1,297-byte PDF: killed at 8 GiB, now 278 MB,
  which is mostly the decoded stream;
- 11-byte segments behind nested Flate in a stream and its globals, a 4,765-byte PDF: 5 GB, now
  602 MB, which is mostly the two decoded streams;
- an Indexed image whose page header claims 2^20 a side, a 743-byte PDF: aborted asking for
  137 GB, now 23 MB;
- a chain of 4,000 /JBIG2Globals streams that are JBIG2 themselves, on a 2 MiB stack: overflowed
  it and aborted, now 24 MB.

So PageState counts what it stores: regions, pattern and symbol dictionaries and Huffman
tables, with bitmap headers, retained contexts and a charge per item, up to 64 MiB, two square
bitmaps of 16,384 a side. A dictionary's new and exported symbols count against what is left as they are
made, not once it is stored. A segment may refer to at most 2^20 symbols, checked before any are
collected. A halftone grid has at most 2^25 cells. 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. 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. A
page past the bounds on a bitmap is refused when the stream is opened, since callers size their
output from its header before the page bitmap is made. And in hayro-syntax, a /JBIG2Globals
stream that is itself JBIG2 isn't decoded: globals are raw segments, so it reads as globals that
can't be decoded.

An image past a bound isn't drawn, as with the other caps, and the rest of the page is. This
bounds memory, not time: decoding work has no total yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmsdeUCdTaD72jkDw2pJKY
This commit is contained in:
Grzegorz MartensandClaude Opus 5.5 committed 2026-10-30 23:43:50 +01:00
1 parent fa5f9f8c3b
commit 85c1005148
12 files changed
+805 -58

No files matched your search

+496
View File
@@ -3527,6 +3527,502 @@ fn jbig2_regions_of_billions_of_pixels_are_refused() {
assert_eq!(&page.rgba[((38 * 40 + 1) * 4)..][..4], &[255, 0, 0, 255], "the rest of the page draws");
}
/// One embedded JBIG2 segment (ISO 14492 §7.2) of page 1. More than four references take the long
/// form, whose retention flags are left clear.
fn jbig2_segment(out: &mut Vec<u8>, number: u32, kind: u8, refs: &[u8], data: &[u8]) {
out.extend_from_slice(&number.to_be_bytes());
out.push(kind);
if refs.len() <= 4 {
out.push(u8::try_from(refs.len()).unwrap() << 5);
} else {
out.extend_from_slice(&(0xE000_0000u32 | u32::try_from(refs.len()).unwrap()).to_be_bytes());
out.extend(std::iter::repeat_n(0u8, (refs.len() + 1).div_ceil(8)));
}
out.extend_from_slice(refs);
out.push(1);
out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
out.extend_from_slice(data);
}
/// The page information of a 16 × 2 JBIG2 page whose default pixel is black, so that the image, if
/// it decodes, draws black whatever its other segments hold.
fn black_jbig2_page() -> Vec<u8> {
let mut page = Vec::new();
page.extend_from_slice(&16u32.to_be_bytes());
page.extend_from_slice(&2u32.to_be_bytes());
page.extend_from_slice(&[0; 8]); // resolution
page.extend_from_slice(&[4, 0, 0]); // flags (default pixel black), striping
let mut stream = Vec::new();
jbig2_segment(&mut stream, 0, 48, &[], &page);
stream
}
/// A region's information field, at the page's corner.
fn jbig2_region_info(width: u32, height: u32) -> Vec<u8> {
let mut region = Vec::new();
region.extend_from_slice(&width.to_be_bytes());
region.extend_from_slice(&height.to_be_bytes());
region.extend_from_slice(&[0; 9]); // x, y, combination operator
region
}
/// Whether a 16 × 2 JBIG2 image decodes: drawn at 5..25 both ways, it draws black, and refused it
/// leaves the page white. The red square beside it shows the rest of the page drew either way.
fn jbig2_image_draws(stream: &[u8]) -> bool {
jbig2_image_draws_in(stream, "/DeviceGray")
}
/// [`jbig2_image_draws`], for an image in colour space `space`.
fn jbig2_image_draws_in(stream: &[u8], space: &str) -> bool {
jbig2_image_draws_with(stream, space, "", b"")
}
/// [`jbig2_image_draws_in`], with entries for the image's dictionary and more objects, from 6 up.
fn jbig2_image_draws_with(stream: &[u8], space: &str, entries: &str, objects: &[u8]) -> bool {
let content = b"q 20 0 0 20 5 5 cm /Im1 Do Q 1 0 0 rg 0 0 4 4 re f";
let mut pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /XObject << /Im1 5 0 R >> >> >> endobj\n".to_vec();
pdf.extend_from_slice(format!("4 0 obj << /Length {} >> stream\n", content.len()).as_bytes());
pdf.extend_from_slice(content);
pdf.extend_from_slice(b"\nendstream endobj\n");
pdf.extend_from_slice(
format!("5 0 obj << /Type /XObject /Subtype /Image /Width 16 /Height 2 /BitsPerComponent 1 /ColorSpace {space} {entries} /Filter /JBIG2Decode /Length {} >> stream\n", stream.len())
.as_bytes(),
);
pdf.extend_from_slice(stream);
pdf.extend_from_slice(b"\nendstream endobj\n");
pdf.extend_from_slice(objects);
pdf.extend_from_slice(b"trailer << /Root 1 0 R >>\n%%EOF\n");
let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, ..Default::default() });
assert!(page.error.is_none(), "{:?}", page.error);
assert_eq!(&page.rgba[((38 * 40 + 1) * 4)..][..4], &[255, 0, 0, 255], "the rest of the page draws");
// Inside the image: top-down rows 15..35.
match &page.rgba[((25 * 40 + 15) * 4)..][..4] {
[0, 0, 0, 255] => true,
[255, 255, 255, 255] => false,
other => panic!("neither the image nor the page: {other:?}"),
}
}
/// Bits written from the top of each byte, as JBIG2's Huffman-coded data is.
#[derive(Default)]
struct Bits {
bytes: Vec<u8>,
used: u32,
}
impl Bits {
fn put(&mut self, value: u32, count: u32) {
for i in (0..count).rev() {
if self.used.is_multiple_of(8) {
self.bytes.push(0);
}
if (value >> i) & 1 != 0 {
*self.bytes.last_mut().unwrap() |= 0x80 >> (self.used % 8);
}
self.used += 1;
}
}
fn align(&mut self) {
self.used = self.used.div_ceil(8) * 8;
}
/// `value` in table B.1 (ISO 14492 Annex B).
fn table_b1(&mut self, value: u32) {
match value {
0..=15 => {
self.put(0, 1);
self.put(value, 4);
}
16..=271 => {
self.put(0b10, 2);
self.put(value - 16, 8);
}
272..=65807 => {
self.put(0b110, 3);
self.put(value - 272, 16);
}
_ => {
self.put(0b111, 3);
self.put(value - 65808, 32);
}
}
}
}
/// A Huffman-coded symbol dictionary of `symbols` symbols of width 0 and height 1, exported or not:
/// each holds no pixels, and costs a bitmap's header all the same.
fn zero_width_jbig2_dictionary(symbols: u32, exported: bool) -> Vec<u8> {
let mut dictionary = vec![0x00, 0x01]; // Huffman, tables B.4, B.2, B.1, B.1
dictionary.extend_from_slice(&(if exported { symbols } else { 0 }).to_be_bytes());
dictionary.extend_from_slice(&symbols.to_be_bytes()); // new
let mut bits = Bits::default();
bits.put(0, 1); // height class delta 1 (B.4)
for _ in 0..symbols {
bits.put(0, 1); // width delta 0 (B.2)
}
bits.put(0b111111, 6); // end of the class (B.2)
bits.put(0, 5); // BMSIZE 0, uncompressed (B.1)
bits.align();
if exported {
bits.table_b1(0); // the first export run isn't exported
}
bits.table_b1(symbols);
dictionary.extend_from_slice(&bits.bytes);
dictionary
}
/// A Huffman-coded symbol dictionary of `symbols` white symbols of width 1 and `height` rows, none
/// exported, for `height` from 76 up.
fn narrow_jbig2_dictionary(symbols: u32, height: u32) -> Vec<u8> {
let mut bits = Bits::default();
bits.put(0b11111, 5); // height class delta, the upper line of table B.4
bits.put(height - 76, 32);
bits.put(0b10, 2); // width delta 1 (B.2)
for _ in 1..symbols {
bits.put(0, 1); // width delta 0 (B.2)
}
bits.put(0b111111, 6); // end of the class (B.2)
let rows = height.div_ceil(8) + 1; // an MMR-coded white bitmap: one bit a row
bits.table_b1(rows); // BMSIZE (B.1)
bits.align();
for _ in 0..rows {
bits.put(0xFF, 8);
}
bits.table_b1(symbols); // the first export run, not exported, is all of them
let mut dictionary = vec![0x00, 0x01]; // Huffman, tables B.4, B.2, B.1, B.1
dictionary.extend_from_slice(&0u32.to_be_bytes()); // exported
dictionary.extend_from_slice(&symbols.to_be_bytes()); // new
dictionary.extend_from_slice(&bits.bytes);
dictionary
}
/// An intermediate generic region, white, every row typical: it decodes in a few bytes however
/// large it is.
fn jbig2_white_region(width: u32, height: u32) -> Vec<u8> {
let mut region = jbig2_region_info(width, height);
region.push(0x08); // arithmetic coding, template 0, typical prediction
region.extend_from_slice(&[3, 0xff, 0xfd, 0xff, 2, 0xfe, 0xfe, 0xfe]); // AT pixels
// Every row typical, the first white: pdfcraft-filters' coding of a white 16,384 square.
region.extend_from_slice(&[0xb6, 0xc2, 0x1f, 0xff, 0x7f, 0xff, 0xac]);
region
}
/// A pattern dictionary of `patterns` patterns of width 1 and `height` rows, with nothing coded.
fn jbig2_pattern_dictionary(height: u8, patterns: u32) -> Vec<u8> {
let mut dictionary = vec![0, 1, height];
dictionary.extend_from_slice(&(patterns - 1).to_be_bytes());
dictionary
}
/// A 1 × 1 halftone region over a grid of `width` × `height` cells, all at the region's corner,
/// coded by MMR or arithmetically.
fn jbig2_halftone(width: u32, height: u32, mmr: bool) -> Vec<u8> {
let mut halftone = jbig2_region_info(1, 1);
halftone.push(u8::from(mmr)); // template 0
halftone.extend_from_slice(&width.to_be_bytes());
halftone.extend_from_slice(&height.to_be_bytes());
halftone.extend_from_slice(&[0; 12]); // grid offset and vector
halftone
}
/// Each JBIG2 segment's bitmaps are bounded, but nothing bounded what a page's segments hold for
/// later ones: a stream of a few dozen bytes an intermediate region (16,384 samples a side, every
/// row typical) held 33 MB each, so a few kilobytes could exhaust memory. Vendored hayro-jbig2
/// patch: what regions, dictionaries and tables hold is at most 64 MiB (`MAX_RETAINED_WORDS`), two
/// such squares, which are exactly the bound.
#[test]
fn jbig2_regions_held_past_a_pages_bound_are_refused() {
let stream = |regions: u32| {
let mut stream = black_jbig2_page();
for number in 1..=regions {
jbig2_segment(&mut stream, number, 36, &[], &jbig2_white_region(16384, 16384));
}
stream
};
assert!(jbig2_image_draws(&stream(2)), "two such squares fit");
assert!(!jbig2_image_draws(&stream(3)), "a third doesn't");
}
/// A symbol of width 0 holds no pixels, and still costs a bitmap's header: 5 KB of dictionaries of
/// them held 781 MB, with the bound counting pixels only.
#[test]
fn jbig2_symbols_without_pixels_count_towards_a_pages_bound() {
let stream = |dictionaries: u32| {
let mut stream = black_jbig2_page();
let dictionary = zero_width_jbig2_dictionary(32767, true);
for number in 1..=dictionaries {
jbig2_segment(&mut stream, number, 0, &[], &dictionary);
}
stream
};
assert!(jbig2_image_draws(&stream(1)), "one dictionary fits");
assert!(!jbig2_image_draws(&stream(44)), "44 × 32,767 headers are past the bound");
}
/// A symbol dictionary may retain its coding contexts for a later one, 73,728 bytes each time, and
/// 1.1 MB of dictionaries with no symbols, 103 KB behind Flate, held 2.89 GB.
#[test]
fn jbig2_retained_contexts_count_towards_a_pages_bound() {
let stream = |dictionaries: u32| {
let mut dictionary = vec![0x02, 0x00]; // arithmetic coding, contexts retained
dictionary.extend_from_slice(&[3, 0xff, 0xfd, 0xff, 2, 0xfe, 0xfe, 0xfe]); // AT pixels
dictionary.extend_from_slice(&[0; 8]); // exported, new
let mut stream = black_jbig2_page();
for number in 1..=dictionaries {
jbig2_segment(&mut stream, number, 0, &[], &dictionary);
}
stream
};
assert!(jbig2_image_draws(&stream(1)), "one dictionary fits");
assert!(!jbig2_image_draws(&stream(1000)), "a thousand don't");
}
/// Huffman tables are held for later segments too, each taking some 586 bytes however small it
/// is, so 200,000 of them are past the bound, and they were held to it at 4 times that.
#[test]
fn jbig2_huffman_tables_count_towards_a_pages_bound() {
let stream = |tables: u32| {
// One-bit prefix and range lengths, values 0 to 1: a table line, then the lower range.
let mut table = vec![0];
table.extend_from_slice(&0i32.to_be_bytes());
table.extend_from_slice(&1i32.to_be_bytes());
table.push(0b1010_0000);
let mut stream = black_jbig2_page();
for number in 1..=tables {
jbig2_segment(&mut stream, number, 53, &[], &table);
}
stream
};
assert!(jbig2_image_draws(&stream(1)), "one table fits");
assert!(!jbig2_image_draws(&stream(200_000)), "200,000 don't");
}
/// New symbols count as they are decoded, whatever the dictionary exports: rows take a word at
/// least, so symbols of one column held 270 MiB within the bound on a dictionary's pixels, and
/// exporting none of them they were never counted at all.
#[test]
fn jbig2_new_symbols_count_towards_a_pages_bound() {
let stream = |height: u32| {
let mut stream = black_jbig2_page();
jbig2_segment(&mut stream, 1, 0, &[], &narrow_jbig2_dictionary(65534, height));
stream
};
assert!(jbig2_image_draws(&stream(100)), "65,534 symbols of 100 rows fit");
assert!(!jbig2_image_draws(&stream(300)), "of 300 rows they don't");
}
/// New symbols are held to what the page has left, headers included, not to the whole bound. These
/// two regions leave it 512 words, and the dictionary after them exports nothing, so only that
/// check can refuse it.
#[test]
fn jbig2_new_symbols_are_held_to_what_a_page_has_left() {
let stream = |dictionary: &[u8]| {
let mut stream = black_jbig2_page();
jbig2_segment(&mut stream, 1, 36, &[], &jbig2_white_region(16384, 16384));
jbig2_segment(&mut stream, 2, 36, &[], &jbig2_white_region(16384, 16383));
jbig2_segment(&mut stream, 3, 0, &[], dictionary);
stream
};
assert!(jbig2_image_draws(&stream(&narrow_jbig2_dictionary(1, 100))), "100 rows fit");
assert!(!jbig2_image_draws(&stream(&narrow_jbig2_dictionary(1, 1000))), "1,000 rows don't");
assert!(jbig2_image_draws(&stream(&zero_width_jbig2_dictionary(10, false))), "10 headers fit");
assert!(!jbig2_image_draws(&stream(&zero_width_jbig2_dictionary(100, false))), "100 headers don't");
}
/// Pattern dictionaries count towards the bound, with no shifted copies to do it for them: at 44
/// words a pattern, 6 of these are past it.
#[test]
fn jbig2_pattern_dictionaries_count_towards_a_pages_bound() {
let stream = |dictionaries: u32| {
let mut stream = black_jbig2_page();
for number in 1..=dictionaries {
jbig2_segment(&mut stream, number, 16, &[], &jbig2_pattern_dictionary(32, 65535));
}
stream
};
assert!(jbig2_image_draws(&stream(5)), "5 fit");
assert!(!jbig2_image_draws(&stream(6)), "6 don't");
}
/// Shifted copies are only a speed-up, so they are never what gets an image refused: each of these
/// tables is within its own limit, and the fourth won't fit what the page has left, so it is left
/// out, where counting it refused the image.
#[test]
fn jbig2_shifted_patterns_never_refuse_an_image() {
let mut stream = black_jbig2_page();
for number in 1..=4 {
jbig2_segment(&mut stream, number, 16, &[], &jbig2_pattern_dictionary(32, 2048));
}
assert!(jbig2_image_draws(&stream));
}
/// Ordinary globals still reach the decoder, with a filter on them or without: here they hold the
/// page information, so the image draws only if they are read.
#[test]
fn jbig2_globals_are_read() {
let globals = black_jbig2_page();
let hex: String = globals.iter().map(|b| format!("{b:02x}")).collect();
let mut stream = Vec::new();
jbig2_segment(&mut stream, 1, 62, &[], &[]); // an extension, which decoders skip
for (filter, data) in [("", globals.clone()), ("/Filter /ASCIIHexDecode", hex.into_bytes())] {
let mut objects = format!("6 0 obj << {filter} /Length {} >> stream\n", data.len()).into_bytes();
objects.extend_from_slice(&data);
objects.extend_from_slice(b"\nendstream endobj\n");
assert!(jbig2_image_draws_with(&stream, "/DeviceGray", "/DecodeParms << /JBIG2Globals 6 0 R >>", &objects), "{filter}");
}
}
/// Globals are raw segments, but a `/JBIG2Globals` stream could itself be JBIG2, naming the next
/// such stream, and each read decoded the next: 4,000 of them, here on a test thread's 2 MiB stack,
/// overflowed it, which aborts the process. Vendored hayro-syntax patch: such a stream reads as
/// globals that can't be decoded, so the image decodes without them.
#[test]
fn jbig2_globals_that_are_jbig2_themselves_are_not_decoded() {
let links = 4000;
let mut objects = Vec::new();
for number in 0..links {
let link = 6 + number;
let next = link + 1;
let parms = if number + 1 < links { format!("/DecodeParms << /JBIG2Globals {next} 0 R >>") } else { String::new() };
objects.extend_from_slice(format!("{link} 0 obj << /Filter /JBIG2Decode {parms} /Length 0 >> stream\n\nendstream endobj\n").as_bytes());
}
assert!(jbig2_image_draws_with(&black_jbig2_page(), "/DeviceGray", "/DecodeParms << /JBIG2Globals 6 0 R >>", &objects));
}
/// An image's page header can claim any size, and the Indexed path reserves its output from it
/// before the page bitmap is sized: a 743-byte PDF asked for 137 GB, which aborts the process.
/// Vendored hayro-jbig2 patch: a page past the bounds is refused when the stream is opened.
#[test]
fn jbig2_pages_past_the_bounds_are_refused_before_anything_is_sized_from_them() {
let indexed = "[/Indexed /DeviceGray 1 <00FF>]";
assert!(jbig2_image_draws_in(&black_jbig2_page(), indexed), "a page within the bounds");
let mut page = Vec::new();
page.extend_from_slice(&(1u32 << 20).to_be_bytes());
page.extend_from_slice(&(1u32 << 20).to_be_bytes());
page.extend_from_slice(&[0; 11]); // resolution, flags, striping
let mut stream = Vec::new();
jbig2_segment(&mut stream, 0, 48, &[], &page);
assert!(!jbig2_image_draws_in(&stream, indexed), "the page draws without it");
}
/// One custom Huffman table could grow without bound as it was read, before anything counted it:
/// a line takes 2 bits of input and 8 bytes here, so 250 MiB behind nested Flate, in a 1,297-byte
/// PDF, was killed at 8 GiB. Vendored hayro-jbig2 patch: at most 2^16 lines.
#[test]
fn jbig2_huffman_tables_of_too_many_lines_are_refused() {
let stream = |lines: i32| {
// One-bit prefix and range lengths, all zero: a line per value.
let mut table = vec![0];
table.extend_from_slice(&0i32.to_be_bytes());
table.extend_from_slice(&lines.to_be_bytes());
table.resize(table.len() + usize::try_from(lines).unwrap().div_ceil(4) + 1, 0);
let mut stream = black_jbig2_page();
jbig2_segment(&mut stream, 1, 53, &[], &table);
stream
};
assert!(jbig2_image_draws(&stream(1 << 16)), "2^16 lines are allowed");
assert!(!jbig2_image_draws(&stream((1 << 16) + 1)), "one more isn't");
}
/// A stream's segments are all parsed and sorted before the first is decoded: 11 bytes of input took
/// 64 here, so behind nested Flate a 4,765-byte PDF reached 5 GB, and failed only afterwards.
/// Vendored hayro-jbig2 patch: at most 2^20 segments.
#[test]
fn jbig2_streams_of_too_many_segments_are_refused() {
let stream = |segments: u32| {
let mut stream = black_jbig2_page();
for number in 1..segments {
jbig2_segment(&mut stream, number, 62, &[], &[]); // an extension, which decoders skip
}
stream
};
assert!(jbig2_image_draws(&stream(1 << 20)), "2^20 segments are allowed");
assert!(!jbig2_image_draws(&stream((1 << 20) + 1)), "one more isn't");
}
/// References take 4 bytes each for 1 of input, a stream's total as much as a segment's.
/// Vendored hayro-jbig2 patch: at most 2^22 in a stream, which is 64 × 65,535 + 64.
#[test]
fn jbig2_streams_of_too_many_references_are_refused() {
let stream = |last: usize| {
let mut stream = black_jbig2_page();
for number in 1..=64 {
jbig2_segment(&mut stream, number, 62, &vec![0u8; 65535], &[]);
}
jbig2_segment(&mut stream, 65, 62, &vec![0u8; last], &[]);
stream
};
assert!(jbig2_image_draws(&stream(64)), "2^22 references are allowed");
assert!(!jbig2_image_draws(&stream(65)), "one more isn't");
}
/// One segment may refer to the same dictionary again and again, and collecting its symbols took a
/// pointer each: 65,535 references to a dictionary of 32,767 symbols, in a 78 KB stream, asked for
/// 17 GB. Vendored hayro-jbig2 patch: at most 2^20 symbols per segment, and 32 × 32,767 + 32 is
/// exactly that. All three segment kinds that take symbols are held to it: the text regions, whether
/// immediate or intermediate, and a dictionary that refers to others.
#[test]
fn jbig2_segments_referring_to_too_many_symbols_are_refused() {
let mut text = jbig2_region_info(1, 1);
text.extend_from_slice(&[0, 0]); // arithmetic coding, no refinement
text.extend_from_slice(&[0; 4]); // no instances
// A dictionary of no symbols of its own, exporting none of those it refers to.
let dictionary = |symbols: u32| {
let mut dictionary = vec![0x00, 0x01]; // Huffman, tables B.4, B.2, B.1, B.1
dictionary.extend_from_slice(&[0; 8]); // exported, new
let mut bits = Bits::default();
bits.table_b1(symbols); // the first export run, not exported, is all of them
dictionary.extend_from_slice(&bits.bytes);
dictionary
};
let stream = |kind: u8, small: usize, data: &[u8]| {
let mut stream = black_jbig2_page();
jbig2_segment(&mut stream, 1, 0, &[], &zero_width_jbig2_dictionary(32767, true));
jbig2_segment(&mut stream, 2, 0, &[], &zero_width_jbig2_dictionary(32, true));
let mut refs = vec![1u8; 32];
refs.extend(std::iter::repeat_n(2u8, small));
jbig2_segment(&mut stream, 3, kind, &refs, data);
stream
};
let limit = 1 << 20;
for (what, kind, allowed, past) in [
("immediate text region", 6, text.clone(), text.clone()),
("intermediate text region", 4, text.clone(), text.clone()),
("symbol dictionary", 0, dictionary(limit), dictionary(limit + 32)),
] {
assert!(jbig2_image_draws(&stream(kind, 1, &allowed)), "{what}: 2^20 symbols are allowed");
assert!(!jbig2_image_draws(&stream(kind, 2, &past)), "{what}: 32 more aren't");
}
}
/// A halftone grid takes a 4-byte value per cell while it decodes, so the bound of 2^28 cells let a
/// 98-byte segment take 1 GiB. Vendored hayro-jbig2 patch: at most 2^25 cells, however it's coded.
#[test]
fn jbig2_halftone_grids_past_their_bound_are_refused() {
let stream = |width: u32, height: u32, mmr: bool| {
let mut stream = black_jbig2_page();
jbig2_segment(&mut stream, 1, 16, &[], &jbig2_pattern_dictionary(1, 2));
jbig2_segment(&mut stream, 2, 22, &[1], &jbig2_halftone(width, height, mmr));
stream
};
assert!(jbig2_image_draws(&stream(8192, 4096, false)), "2^25 cells are allowed");
assert!(!jbig2_image_draws(&stream(8193, 4096, false)), "one more column isn't");
assert!(!jbig2_image_draws(&stream(8193, 4096, true)), "nor when it is MMR-coded");
}
/// A pattern dictionary's shifted copies only speed up drawing, and 48 bytes could ask for 539 MB
/// of them, past what a page may hold. Vendored hayro-jbig2 patch: past 16 MiB they are left out,
/// so such a dictionary is drawn the slow way rather than refused.
#[test]
fn jbig2_pattern_dictionaries_too_large_to_shift_still_draw() {
let mut stream = black_jbig2_page();
jbig2_segment(&mut stream, 1, 16, &[], &jbig2_pattern_dictionary(32, 65535));
jbig2_segment(&mut stream, 2, 22, &[1], &jbig2_halftone(1, 1, false));
assert!(jbig2_image_draws(&stream));
}
/// From `cargo xtask fuzz`: one changed byte in a symbol dictionary's arithmetic-coded data
/// hung the renderer. Two of its loops can stop advancing: an export run of length 0, and a
/// height class whose first width is already the end-of-class marker. Past the end of its
+2 -2
View File
@@ -41,9 +41,9 @@ 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, 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`) |
| 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 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); (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 | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`, `raster::tests::jbig2_halftone_grids_past_their_bound_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`); (5) `raster::tests::jbig2_regions_held_past_a_pages_bound_are_refused`, `jbig2_symbols_without_pixels_count_towards_a_pages_bound`, `jbig2_retained_contexts_count_towards_a_pages_bound`, `jbig2_huffman_tables_count_towards_a_pages_bound`, `jbig2_new_symbols_count_towards_a_pages_bound`, `jbig2_new_symbols_are_held_to_what_a_page_has_left`, `jbig2_pattern_dictionaries_count_towards_a_pages_bound`, and in the crate (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) `decode::symbol::tests::exported_symbols_are_counted_before_they_are_copied`, `tests::the_room_left_shrinks_as_segments_are_stored`; (6) `raster::tests::jbig2_segments_referring_to_too_many_symbols_are_refused`; (7) `raster::tests::jbig2_pattern_dictionaries_too_large_to_shift_still_draw`, `jbig2_shifted_patterns_never_refuse_an_image`; (8) `raster::tests::jbig2_huffman_tables_of_too_many_lines_are_refused`, `jbig2_streams_of_too_many_segments_are_refused`, `jbig2_streams_of_too_many_references_are_refused`, and in the crate `tests::the_segments_of_a_stream_and_its_globals_count_together`; (9) `raster::tests::jbig2_pages_past_the_bounds_are_refused_before_anything_is_sized_from_them`, `tests::a_page_past_the_bounds_is_refused_when_opened` |
| 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 |
+28 -7
View File
@@ -19,6 +19,11 @@ pub(crate) const MAX_DIMENSION: u32 = u16::MAX as u32;
/// pixels, decoded one by one.
pub(crate) const MAX_PIXELS: u64 = 1 << 28;
/// PdfCraft patch: the most cells a halftone grid may have, which still gives the largest page
/// (see [`MAX_PIXELS`]) cells of 3 × 3, unrotated. Each cell takes a 4-byte value while the grid decodes, so
/// the pixel bound alone let a 98-byte segment take 1 GiB; this one leaves 128 MiB.
pub(crate) const MAX_GRID_CELLS: u64 = 1 << 25;
/// The underlying word type for packed pixel storage.
/// Change this to `u32` to switch back to 32-bit words.
pub(crate) type Word = u32;
@@ -26,6 +31,23 @@ pub(crate) type Word = u32;
pub(crate) const WORD_BITS: u32 = Word::BITS;
pub(crate) const WORD_SHIFT: u32 = WORD_BITS - 1;
/// PdfCraft patch: the words a [`Bitmap`] takes before its pixels. A symbol of width 0 has no
/// pixels and still costs this: 5 KB of zero-width dictionaries held 781 MB.
pub(crate) const BITMAP_WORDS: usize = size_of::<Bitmap>() / size_of::<Word>();
/// PdfCraft patch: refuse a page past the bounds on a bitmap (see `MAX_PIXELS`). A stream is held
/// to this when it is opened as well as when its page bitmap is sized: a caller sizes its own
/// output from the page header in between, and a 743-byte PDF's Indexed image asked for 137 GB.
pub(crate) fn check_page_size(width: u32, height: u32) -> Result<()> {
if width > MAX_DIMENSION || height > MAX_DIMENSION {
return Err(OverflowError::BitmapDimension.into());
}
if u64::from(width) * u64::from(height) > MAX_PIXELS {
return Err(OverflowError::BitmapDimension.into());
}
Ok(())
}
/// A decoded bitmap with position information.
///
/// "Pixels decoded by the MMR decoder having the value 'black' shall be treated
@@ -51,6 +73,11 @@ pub(crate) struct Bitmap {
}
impl Bitmap {
/// PdfCraft patch: the words this bitmap holds, its header included.
pub(crate) fn words(&self) -> usize {
self.data.len().saturating_add(BITMAP_WORDS)
}
/// Create a new bitmap filled with white pixels (false).
///
/// The bitmap is positioned at (0, 0).
@@ -93,13 +120,7 @@ impl Bitmap {
height: u32,
default_pixel: bool,
) -> Result<()> {
if width > MAX_DIMENSION || height > MAX_DIMENSION {
return Err(OverflowError::BitmapDimension.into());
}
// PdfCraft patch: see `MAX_PIXELS` (the page bitmap is sized here).
if u64::from(width) * u64::from(height) > MAX_PIXELS {
return Err(OverflowError::BitmapDimension.into());
}
check_page_size(width, height)?;
let stride = width.div_ceil(WORD_BITS);
let default_word: Word = if default_pixel { !0 } else { 0 };
+2 -2
View File
@@ -97,8 +97,8 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result<HalftoneRegionHeader<
if grid_width > MAX_DIMENSION || grid_height > MAX_DIMENSION {
bail!(OverflowError::GridDimension);
}
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_PIXELS`).
if u64::from(grid_width) * u64::from(grid_height) > crate::bitmap::MAX_PIXELS {
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_GRID_CELLS`).
if u64::from(grid_width) * u64::from(grid_height) > crate::bitmap::MAX_GRID_CELLS {
bail!(OverflowError::GridDimension);
}
+23 -1
View File
@@ -8,10 +8,15 @@ use crate::error::{OverflowError, ParseError, Result};
use crate::reader::Reader;
use alloc::vec::Vec;
/// PdfCraft patch: the most words of shifted copies a dictionary keeps, 16 MiB, where 256 patterns
/// of 32 rows take 2 MiB. A 48-byte dictionary of 65,535 such patterns asked for 539 MB.
const MAX_SHIFTED_WORDS: u64 = 1 << 22;
/// Decode a pattern dictionary segment (7.4.4.2, 6.7).
pub(crate) fn decode(
header: &PatternDictionaryHeader<'_>,
scratch: &mut ScratchBuffers,
room: u64,
) -> Result<PatternDictionary> {
let pattern_width = header.pattern_width as u32;
let pattern_height = header.pattern_height as u32;
@@ -133,7 +138,19 @@ pub(crate) fn decode(
// for all possible 32-bit alignments, which later on allows us to
// very easily blit it into the backdrop, significantly speeding up
// the whole process.
let shifted_patterns = if pattern_width <= WORD_BITS && pattern_height <= WORD_BITS {
//
// PdfCraft patch: only when the table is small, and fits what the page may still hold
// (`room`), so that a speed-up never gets an image refused. It can be left out:
// `shifted_pattern` then returns `None` and the patterns are combined the slow way.
let shifted_words = (patterns.len() as u64)
.saturating_mul(32 * 2)
.saturating_mul(u64::from(pattern_height));
let pattern_words = patterns.iter().map(|p| p.words() as u64).fold(0, u64::saturating_add);
let shifted_patterns = if pattern_width <= WORD_BITS
&& pattern_height <= WORD_BITS
&& shifted_words <= MAX_SHIFTED_WORDS
&& shifted_words.saturating_add(pattern_words) <= room
{
let h = pattern_height as usize;
let mut data = Vec::with_capacity(patterns.len() * 32 * h * 2);
for pattern in &patterns {
@@ -180,6 +197,11 @@ impl PatternDictionary {
let start = (pattern_idx * 32 + bit_offset as usize) * len;
self.shifted_patterns.get(start..start + len)
}
/// PdfCraft patch: the words the dictionary holds, its patterns and their shifted copies.
pub(crate) fn words(&self) -> usize {
self.patterns.iter().map(Bitmap::words).fold(self.shifted_patterns.len(), usize::saturating_add)
}
}
/// Parsed pattern dictionary segment header (7.4.4.1).
+59 -4
View File
@@ -4,7 +4,7 @@ use alloc::vec;
use alloc::vec::Vec;
use crate::arithmetic_decoder::{ArithmeticDecoder, ArithmeticDecoderContext};
use crate::bitmap::{Bitmap, WORD_BITS};
use crate::bitmap::{BITMAP_WORDS, Bitmap, WORD_BITS, Word};
use crate::decode::generic::{decode_bitmap_mmr, parse_adaptive_template_pixels};
use crate::decode::text::{
DecodeContext, ReferenceCorner, TextRegionContexts, TextRegionFlags, TextRegionHeader,
@@ -45,6 +45,7 @@ pub(crate) fn decode(
referred_tables: &[HuffmanTable],
standard_tables: &StandardHuffmanTables,
input_contexts: Option<&RetainedContexts>,
room: u64,
) -> Result<SymbolDictionary> {
let num_new_symbols = header.num_new_symbols;
@@ -58,6 +59,8 @@ pub(crate) fn decode(
total_width: 0,
height_class_height: 0,
pixels: 0,
new_words: 0,
room,
header,
standard_tables,
};
@@ -130,6 +133,13 @@ pub(crate) fn decode(
if ctx.pixels > MAX_DICTIONARY_PIXELS {
bail!(OverflowError::BitmapDimension);
}
// PdfCraft patch: see `room`. Rows take a word at least, so symbols of one column
// held 270 MiB within the pixel bound, however few the dictionary exported.
let rows = u64::from(symbol_width.div_ceil(WORD_BITS)) * u64::from(ctx.height_class_height);
ctx.new_words = ctx.new_words.saturating_add(rows).saturating_add(BITMAP_WORDS as u64);
if ctx.new_words > ctx.room {
bail!(OverflowError::RetainedBitmaps);
}
match (ctx.header.flags.use_huffman, ctx.header.flags.use_refagg) {
(false, false) => {
@@ -202,6 +212,18 @@ pub(crate) struct SymbolDictionary {
pub(crate) retained_contexts: Option<RetainedContexts>,
}
impl SymbolDictionary {
/// PdfCraft patch: the words the dictionary holds, its retained contexts included. Those are
/// a byte each, and 1.1 MB of dictionaries that retain them, 103 KB behind Flate, held 2.89 GB.
pub(crate) fn words(&self) -> usize {
let contexts = self.retained_contexts.as_ref().map_or(0, |contexts| {
let bytes = contexts.generic_region.len().saturating_add(contexts.refinement_region.len());
bytes.saturating_mul(size_of::<ArithmeticDecoderContext>()) / size_of::<Word>()
});
self.exported_symbols.iter().map(Bitmap::words).fold(contexts, usize::saturating_add)
}
}
/// Decode a symbol bitmap using refinement/aggregate coding (6.5.8.2).
fn decode_refinement_aggregation_bitmap(
ctx: &mut SymbolDecodeContext<'_>,
@@ -463,6 +485,12 @@ struct SymbolDecodeContext<'a> {
symbols_decoded_count: u32,
total_width: u32,
height_class_height: u32,
/// PdfCraft patch: the words the page may still hold, which neither the new symbols nor the
/// exported ones may pass. They are counted as they are made: counted only once the
/// dictionary was stored, 8 MiB symbols exported again and again killed the process.
room: u64,
/// PdfCraft patch: the words of the new symbols so far (see `room`).
new_words: u64,
/// PdfCraft patch: symbol pixels decoded so far (see `MAX_DICTIONARY_PIXELS`).
pixels: u64,
}
@@ -708,6 +736,7 @@ fn export_symbols(ctx: &mut SymbolDecodeContext<'_>) -> Result<Vec<Bitmap>> {
u32::try_from(value).map_err(|_| HuffmanError::InvalidCode.into())
};
let mut exported = Vec::with_capacity(ctx.header.num_exported_symbols as usize);
let mut exported_words: u64 = 0;
let mut index: u32 = 0;
let mut should_export = false;
// PdfCraft patch: see `EXTRA_EMPTY_STEPS`.
@@ -730,9 +759,13 @@ fn export_symbols(ctx: &mut SymbolDecodeContext<'_>) -> Result<Vec<Bitmap>> {
let symbol = ctx
.symbols
.get(symbol_idx as usize)
.ok_or(SymbolError::OutOfRange)?
.clone();
exported.push(symbol);
.ok_or(SymbolError::OutOfRange)?;
// PdfCraft patch: see `room`.
exported_words = exported_words.saturating_add(symbol.words() as u64);
if exported_words > ctx.room {
bail!(OverflowError::RetainedBitmaps);
}
exported.push(symbol.clone());
}
}
@@ -864,3 +897,25 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result<SymbolDictionaryHeade
data,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// A dictionary may export what it refers to, and may refer to one symbol again and again, so
/// its exports are counted against what the page may still hold before each is copied.
/// Refused only once stored, the copies are already made, which a render test can't see.
#[test]
fn exported_symbols_are_counted_before_they_are_copied() {
// Huffman coding, 1,000 exported and no new symbols; export runs of 0 and 1,000 (B.1).
let data = [0x00, 0x01, 0, 0, 0x03, 0xE8, 0, 0, 0, 0, 0x06, 0x02, 0xD8];
let header = parse(&mut Reader::new(&data)).unwrap();
let symbol = Bitmap::new(32, 32).unwrap();
let input = vec![&symbol; 1000];
let tables = StandardHuffmanTables::new();
let words = symbol.words() as u64 * 1000;
let decoded = decode(&header, &input, &[], &tables, None, words).unwrap();
assert_eq!(decoded.exported_symbols.len(), 1000);
assert!(decode(&header, &input, &[], &tables, None, words - 1).is_err());
}
}
+8 -2
View File
@@ -133,8 +133,12 @@ pub enum OverflowError {
ReferenceOffset,
/// Index computation overflowed.
Index,
/// A symbol dictionary has too many symbols.
/// A symbol dictionary has too many symbols, or a segment refers to too many.
SymbolCount,
/// PdfCraft patch: the segments retain more bitmaps than a page may hold.
RetainedBitmaps,
/// PdfCraft patch: a stream has more segments, or references, than it may.
SegmentCount,
}
impl fmt::Display for DecodeError {
@@ -161,7 +165,9 @@ impl fmt::Display for OverflowError {
Self::ReferenceOffset => write!(f, "overflow in reference offset computation"),
Self::Index => write!(f, "overflow in index computation"),
Self::GridDimension => write!(f, "overflow in grid dimension computation"),
Self::SymbolCount => write!(f, "a symbol dictionary has too many symbols"),
Self::SymbolCount => write!(f, "too many symbols in a dictionary or referred to"),
Self::RetainedBitmaps => write!(f, "the segments retain too many bitmaps"),
Self::SegmentCount => write!(f, "too many segments or references in a stream"),
}
}
}
+35 -2
View File
@@ -5,12 +5,39 @@
use alloc::vec::Vec;
use crate::error::{FormatError, ParseError, Result, bail};
use crate::error::{FormatError, OverflowError, ParseError, Result, bail};
use crate::reader::Reader;
use crate::segment::{
Segment, SegmentType, parse_segment, parse_segment_data, parse_segment_header,
};
/// PdfCraft patch: the most segments a stream, with its globals, may have. They are all parsed and
/// sorted before the first is decoded, at about 64 bytes for 11 of input, so behind nested Flate a
/// 4,765-byte PDF reached 5 GB and failed only afterwards.
const MAX_SEGMENTS: usize = 1 << 20;
/// PdfCraft patch: the most references those segments may make, 4 bytes each for 1 of input.
const MAX_REFERENCES: usize = 1 << 22;
/// PdfCraft patch: the segments of a stream so far (see [`MAX_SEGMENTS`], [`MAX_REFERENCES`]).
#[derive(Default)]
pub(crate) struct SegmentCount {
segments: usize,
references: usize,
}
impl SegmentCount {
/// Count one more segment, making `references` references.
fn add(&mut self, references: usize) -> Result<()> {
self.segments = self.segments.saturating_add(1);
self.references = self.references.saturating_add(references);
if self.segments > MAX_SEGMENTS || self.references > MAX_REFERENCES {
bail!(OverflowError::SegmentCount);
}
Ok(())
}
}
/// "There are two standalone file organizations possible for a JBIG2 bitstream."
/// (Annex D)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -140,7 +167,9 @@ fn parse_segments<'a>(
let mut segments = Vec::new();
match organization {
FileOrganization::Sequential => parse_segments_sequential(reader, &mut segments)?,
FileOrganization::Sequential => {
parse_segments_sequential(reader, &mut segments, &mut SegmentCount::default())?;
}
FileOrganization::RandomAccess => parse_segments_random_access(reader, &mut segments)?,
}
@@ -155,6 +184,7 @@ fn parse_segments<'a>(
pub(crate) fn parse_segments_sequential<'a>(
reader: &mut Reader<'a>,
segments: &mut Vec<Segment<'a>>,
count: &mut SegmentCount,
) -> Result<()> {
loop {
if reader.at_end() {
@@ -162,6 +192,7 @@ pub(crate) fn parse_segments_sequential<'a>(
}
let segment = parse_segment(reader)?;
count.add(segment.header.referred_to_segments.len())?;
// "If a file contains an end of file segment, it must be the last segment."
// (7.4.11)
@@ -187,6 +218,7 @@ fn parse_segments_random_access<'a>(
segments: &mut Vec<Segment<'a>>,
) -> Result<()> {
let mut headers = Vec::new();
let mut count = SegmentCount::default();
loop {
if reader.at_end() {
@@ -194,6 +226,7 @@ fn parse_segments_random_access<'a>(
}
let header = parse_segment_header(reader)?;
count.add(header.referred_to_segments.len())?;
// "If a file contains an end of file segment, it must be the last segment."
// (7.4.11)
+2 -2
View File
@@ -83,8 +83,8 @@ fn decode_arithmetic(
if width > MAX_DIMENSION || height > MAX_DIMENSION {
bail!(OverflowError::BitmapDimension);
}
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_PIXELS`).
if u64::from(width) * u64::from(height) > crate::bitmap::MAX_PIXELS {
// PdfCraft patch: the product is bounded too (see `bitmap::MAX_GRID_CELLS`).
if u64::from(width) * u64::from(height) > crate::bitmap::MAX_GRID_CELLS {
bail!(OverflowError::BitmapDimension);
}
+19
View File
@@ -14,11 +14,27 @@ include!("huffman_tables_generated.rs");
/// Maximum number of nodes in an inline Huffman table.
const INLINE_TABLE_SIZE: usize = 43;
/// PdfCraft patch: the most lines a custom table may have. A line takes 2 bits of input at least
/// and 8 bytes here, so a table reading 250 MiB behind nested Flate, a 1,297-byte PDF, was killed
/// at 8 GiB before it could be counted.
const MAX_TABLE_LINES: usize = 1 << 16;
/// A queryable Huffman table.
#[derive(Debug, Clone)]
pub(crate) struct HuffmanTable(Rc<InnerHuffmanTable>);
impl HuffmanTable {
/// PdfCraft patch: the words this table holds. Every table takes the room of the inline
/// variant, however few nodes it has, and a dynamic one its nodes besides.
pub(crate) fn words(&self) -> usize {
let nodes = match &*self.0 {
InnerHuffmanTable::Inline { .. } => 0,
InnerHuffmanTable::Dynamic { nodes } => nodes.len(),
};
let bytes = nodes.saturating_mul(size_of::<HuffmanNode>());
bytes.saturating_add(size_of::<InnerHuffmanTable>()) / size_of::<u32>()
}
/// Create a new inline Huffman table from a fixed-size node array.
fn from_inline(nodes: [HuffmanNode; INLINE_TABLE_SIZE]) -> Self {
Self(Rc::new(InnerHuffmanTable::Inline { nodes }))
@@ -219,6 +235,9 @@ impl HuffmanTable {
// 5) "Decode each table line as follows:"
// d) "If CURRANGELOW ≥ HTHIGH then proceed to step 6."
while current_range_low < maximum_value {
if lines.len() >= MAX_TABLE_LINES {
bail!(HuffmanError::InvalidCode);
}
// a) "Read HTPS bits. Set PREFLEN[NTEMP] to the value decoded."
let prefix_length = reader
.read_bits(prefix_length_bits)
+126 -36
View File
@@ -75,7 +75,7 @@ pub use error::{
SegmentError, SymbolError, TemplateError,
};
use crate::file::parse_segments_sequential;
use crate::file::{SegmentCount, parse_segments_sequential};
use bitmap::Bitmap;
use decode::CombinationOperator;
use decode::generic;
@@ -120,13 +120,14 @@ impl<'a> Image<'a> {
/// Annex D.3.
pub fn new_embedded(data: &'a [u8], globals: Option<&'a [u8]>) -> Result<Self> {
let mut segments = Vec::new();
let mut count = SegmentCount::default();
if let Some(globals_data) = globals {
let mut reader = Reader::new(globals_data);
parse_segments_sequential(&mut reader, &mut segments)?;
parse_segments_sequential(&mut reader, &mut segments, &mut count)?;
};
let mut reader = Reader::new(data);
parse_segments_sequential(&mut reader, &mut segments)?;
parse_segments_sequential(&mut reader, &mut segments, &mut count)?;
segments.sort_by_key(|seg| seg.header.segment_number);
@@ -162,6 +163,7 @@ impl<'a> Image<'a> {
if page_info.width == 0 || height == 0 {
bail!(FormatError::EmptyPage);
}
bitmap::check_page_size(page_info.width, height)?;
Ok(Self {
segments,
@@ -311,24 +313,18 @@ fn decode_segments(
// Intermediate segments cannot have unknown length.
let header = generic::parse(&mut reader, false)?;
let region = generic::decode(&header, scratch_buffers)?;
page_state.store_region(seg.header.segment_number, region.bitmap);
page_state.store_region(seg.header.segment_number, region.bitmap)?;
}
SegmentType::PatternDictionary => {
let header = pattern::parse(&mut reader)?;
let dictionary = pattern::decode(&header, scratch_buffers)?;
page_state.store_pattern_dictionary(seg.header.segment_number, dictionary);
let dictionary = pattern::decode(&header, scratch_buffers, page_state.retained_room())?;
page_state.store_pattern_dictionary(seg.header.segment_number, dictionary)?;
}
SegmentType::SymbolDictionary => {
// "1) Concatenate all the input symbol dictionaries to form SDINSYMS."
// (6.5.5, step 1)
// Collect references to avoid cloning; symbols are only cloned if re-exported.
let input_symbols: Vec<&Bitmap> = seg
.header
.referred_to_segments
.iter()
.filter_map(|&num| page_state.get_symbol_dictionary(num))
.flat_map(|dict| dict.exported_symbols.iter())
.collect();
let input_symbols = page_state.referred_symbols(&seg.header.referred_to_segments)?;
// Collect Huffman tables from referred table segments.
let referred_tables: Vec<HuffmanTable> = seg
@@ -354,18 +350,13 @@ fn decode_segments(
&referred_tables,
&page_state.standard_tables,
retained_contexts,
page_state.retained_room(),
)?;
page_state.store_symbol_dictionary(seg.header.segment_number, dictionary);
page_state.store_symbol_dictionary(seg.header.segment_number, dictionary)?;
}
SegmentType::ImmediateTextRegion | SegmentType::ImmediateLosslessTextRegion => {
// Collect symbols from referred symbol dictionaries (SBSYMS).
let symbols: Vec<&Bitmap> = seg
.header
.referred_to_segments
.iter()
.filter_map(|&num| page_state.get_symbol_dictionary(num))
.flat_map(|dict| dict.exported_symbols.iter())
.collect();
let symbols = page_state.referred_symbols(&seg.header.referred_to_segments)?;
// Collect Huffman tables from referred table segments.
// "These user-supplied Huffman decoding tables may be supplied either
@@ -412,13 +403,7 @@ fn decode_segments(
}
SegmentType::IntermediateTextRegion => {
// Collect symbols from referred symbol dictionaries (SBSYMS).
let symbols: Vec<&Bitmap> = seg
.header
.referred_to_segments
.iter()
.filter_map(|&num| page_state.get_symbol_dictionary(num))
.flat_map(|dict| dict.exported_symbols.iter())
.collect();
let symbols = page_state.referred_symbols(&seg.header.referred_to_segments)?;
// Collect Huffman tables from referred table segments.
let referred_tables: Vec<HuffmanTable> = seg
@@ -437,7 +422,7 @@ fn decode_segments(
&page_state.standard_tables,
scratch_buffers,
)?;
page_state.store_region(seg.header.segment_number, region.bitmap);
page_state.store_region(seg.header.segment_number, region.bitmap)?;
}
SegmentType::ImmediateHalftoneRegion | SegmentType::ImmediateLosslessHalftoneRegion => {
let pattern_dict = seg
@@ -476,7 +461,7 @@ fn decode_segments(
let header = halftone::parse(&mut reader)?;
let region = halftone::decode(&header, pattern_dict, scratch_buffers)?;
page_state.store_region(seg.header.segment_number, region.bitmap);
page_state.store_region(seg.header.segment_number, region.bitmap)?;
}
SegmentType::IntermediateGenericRefinementRegion => {
// Same logic as immediate refinement, but store result instead of combining.
@@ -489,7 +474,7 @@ fn decode_segments(
let header = generic_refinement::parse(&mut reader)?;
let region = generic_refinement::decode(&header, reference, scratch_buffers)?;
page_state.store_region(seg.header.segment_number, region.bitmap);
page_state.store_region(seg.header.segment_number, region.bitmap)?;
}
SegmentType::ImmediateGenericRefinementRegion
| SegmentType::ImmediateLosslessGenericRefinementRegion => {
@@ -532,7 +517,7 @@ fn decode_segments(
// "This segment contains data which defines one or more user-supplied
// Huffman coding tables." (7.4.13)
let table = HuffmanTable::read_custom(&mut reader)?;
page_state.store_huffman_table(seg.header.segment_number, table);
page_state.store_huffman_table(seg.header.segment_number, table)?;
}
SegmentType::EndOfPage | SegmentType::EndOfFile => {
break;
@@ -545,6 +530,23 @@ fn decode_segments(
Ok(())
}
/// PdfCraft patch: the words a stored item costs in its list, at least, apart from what it holds.
const ENTRY_WORDS: u64 = 32;
/// PdfCraft patch: the most words a page's segments may hold for later ones, 64 MiB: two square
/// bitmaps of 16,384 a side (`bitmap::MAX_PIXELS`). Each stored item is bounded on its own, but without a
/// bound on all of them a stream of a few dozen bytes a segment held 33 MB each (a 16,384-sample
/// square region of typical rows), and a few kilobytes could exhaust memory. A segment being
/// decoded takes more for a while, within its own bounds: the page bitmap isn't counted, nor is
/// what a region or a grid uses until it is stored or freed.
const MAX_RETAINED_WORDS: u64 =
2 * (bitmap::MAX_PIXELS / bitmap::WORD_BITS as u64 + bitmap::BITMAP_WORDS as u64 + ENTRY_WORDS);
/// PdfCraft patch: the most symbols one segment may refer to, 2^20, far beyond the 65,535 a
/// dictionary may export. References may repeat, so each names the same symbols again: without
/// this, 65,535 references to one dictionary in a 78 KB stream collected 17 GB of pointers.
const MAX_REFERRED_SYMBOLS: u64 = 1 << 20;
/// Page-level decoding state for a JBIG2 page.
#[derive(Default)]
pub(crate) struct PageState {
@@ -561,6 +563,9 @@ pub(crate) struct PageState {
/// Decoded Huffman tables from table segments, stored as (`segment_number`, table) pairs.
/// "Tables – see 7.4.13." (type 53)
pub(crate) huffman_tables: Vec<(u32, HuffmanTable)>,
/// PdfCraft patch: the words the regions, dictionaries and tables above hold, at most
/// [`MAX_RETAINED_WORDS`].
pub(crate) retained_words: u64,
/// Standard Huffman tables (`TABLE_A` through `TABLE_O`).
pub(crate) standard_tables: StandardHuffmanTables,
}
@@ -573,6 +578,7 @@ impl PageState {
self.pattern_dictionaries.clear();
self.symbol_dictionaries.clear();
self.huffman_tables.clear();
self.retained_words = 0;
// Standard tables are lazily built and reused across images.
}
@@ -610,9 +616,26 @@ impl PageState {
}
}
/// PdfCraft patch: the words the page may still hold for later segments.
fn retained_room(&self) -> u64 {
MAX_RETAINED_WORDS.saturating_sub(self.retained_words)
}
/// PdfCraft patch: count a stored item holding `words` for later segments, refusing past
/// [`MAX_RETAINED_WORDS`].
fn retain(&mut self, words: usize) -> Result<()> {
self.retained_words = self.retained_words.saturating_add(words as u64).saturating_add(ENTRY_WORDS);
if self.retained_words > MAX_RETAINED_WORDS {
bail!(OverflowError::RetainedBitmaps);
}
Ok(())
}
/// Store a decoded region for later reference.
fn store_region(&mut self, segment_number: u32, region: Bitmap) {
fn store_region(&mut self, segment_number: u32, region: Bitmap) -> Result<()> {
self.retain(region.words())?;
self.referred_segments.push((segment_number, region));
Ok(())
}
/// Look up a referred segment by number.
@@ -624,8 +647,10 @@ impl PageState {
}
/// Store a decoded pattern dictionary for later reference.
fn store_pattern_dictionary(&mut self, segment_number: u32, dictionary: PatternDictionary) {
fn store_pattern_dictionary(&mut self, segment_number: u32, dictionary: PatternDictionary) -> Result<()> {
self.retain(dictionary.words())?;
self.pattern_dictionaries.push((segment_number, dictionary));
Ok(())
}
/// Look up a pattern dictionary by segment number.
@@ -637,8 +662,23 @@ impl PageState {
}
/// Store a decoded symbol dictionary for later reference.
fn store_symbol_dictionary(&mut self, segment_number: u32, dictionary: SymbolDictionary) {
fn store_symbol_dictionary(&mut self, segment_number: u32, dictionary: SymbolDictionary) -> Result<()> {
self.retain(dictionary.words())?;
self.symbol_dictionaries.push((segment_number, dictionary));
Ok(())
}
/// PdfCraft patch: the symbols of the dictionaries in `segments`, in order, refusing past
/// [`MAX_REFERRED_SYMBOLS`] before anything is collected.
fn referred_symbols(&self, segments: &[u32]) -> Result<Vec<&Bitmap>> {
let dictionaries = || segments.iter().filter_map(|&num| self.get_symbol_dictionary(num));
let count = dictionaries()
.map(|dictionary| dictionary.exported_symbols.len() as u64)
.fold(0, u64::saturating_add);
if count > MAX_REFERRED_SYMBOLS {
bail!(OverflowError::SymbolCount);
}
Ok(dictionaries().flat_map(|dictionary| dictionary.exported_symbols.iter()).collect())
}
/// Look up a symbol dictionary by segment number.
@@ -650,8 +690,10 @@ impl PageState {
}
/// Store a decoded Huffman table for later reference.
fn store_huffman_table(&mut self, segment_number: u32, table: HuffmanTable) {
fn store_huffman_table(&mut self, segment_number: u32, table: HuffmanTable) -> Result<()> {
self.retain(table.words())?;
self.huffman_tables.push((segment_number, table));
Ok(())
}
/// Look up a Huffman table by segment number.
@@ -690,3 +732,51 @@ fn init_page(
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// A page past the bounds is refused when the stream is opened, since callers size their
/// output from it before decoding starts. 16,384 squared is exactly the bound on pixels.
#[test]
fn a_page_past_the_bounds_is_refused_when_opened() {
let stream = |width: u32, height: u32| {
let mut stream = vec![0, 0, 0, 0, 48, 0, 1, 0, 0, 0, 19];
stream.extend_from_slice(&width.to_be_bytes());
stream.extend_from_slice(&height.to_be_bytes());
stream.extend_from_slice(&[0; 11]); // resolution, flags, striping
stream
};
assert!(Image::new_embedded(&stream(16384, 16384), None).is_ok());
assert!(Image::new_embedded(&stream(16385, 16384), None).is_err());
assert!(Image::new_embedded(&stream(65536, 1), None).is_err(), "too wide, though few pixels");
assert!(Image::new_embedded(&stream(1 << 20, 1 << 20), None).is_err());
}
/// A stream and its globals are one stream of segments, so they have one count.
#[test]
fn the_segments_of_a_stream_and_its_globals_count_together() {
let segment: &[u8] = &[0, 0, 0, 0, 62, 0, 1, 0, 0, 0, 0]; // an empty extension
let half = segment.repeat(1 << 19);
let more = segment.repeat((1 << 19) + 1);
let refused = |data: &[u8]| {
let error = Image::new_embedded(data, Some(&half)).err().map(|e| e.to_string());
error.as_deref() == Some("too many segments or references in a stream")
};
assert!(!refused(&half), "2^20 segments are allowed");
assert!(refused(&more), "one more isn't");
}
/// A dictionary being decoded has what the page may still hold, not all of it: refused only
/// once it is stored, its copies would already have been made.
#[test]
fn the_room_left_shrinks_as_segments_are_stored() {
let mut page = PageState::default();
assert_eq!(page.retained_room(), MAX_RETAINED_WORDS);
page.retain(1000).unwrap();
assert_eq!(page.retained_room(), MAX_RETAINED_WORDS - 1000 - ENTRY_WORDS);
page.retained_words = MAX_RETAINED_WORDS;
assert_eq!(page.retained_room(), 0);
}
}
+5
View File
@@ -1,4 +1,5 @@
use crate::bit_reader::BitWriter;
use crate::filter::Filter;
use crate::object::Dict;
use crate::object::Stream;
use crate::object::dict::keys::JBIG2_GLOBALS;
@@ -17,8 +18,12 @@ pub(crate) fn decode(
params: &Dict<'_>,
image_params: &ImageDecodeParams,
) -> Option<FilterResult<'static>> {
// PdfCraft patch: globals are raw segments, so JBIG2 inside them means nothing, and decoding
// it reads its own globals in turn: a chain of 16,000 such streams overflowed the stack, which
// aborts the process. Such a stream reads as globals that can't be decoded.
let globals = params
.get::<Stream<'_>>(JBIG2_GLOBALS)
.filter(|g| !g.filters().iter().any(|f| matches!(f, Filter::Jbig2Decode)))
.and_then(|g| g.decoded().ok());
let image = hayro_jbig2::Image::new_embedded(data, globals.as_deref()).ok()?;