PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Never crash: mesh shadings can't exhaust memory or run for minutes (#412)
jcl-bitf5c99ce05956
diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rsindex 9ab0aaab2..08fa39069 100644--- a/crates/render/src/raster.rs+++ b/crates/render/src/raster.rs@@ -2053,6 +2053,193 @@ trailer << /Root 1 0 R >>assert_eq!(&page.rgba[((38 * 40 + 1) * 4)..][..4], &[255, 0, 0, 255], "the rest of the page draws");}+ /// From `cargo xtask fuzz`: a mesh shading whose points lie far off the page (a 147-byte+ /// Coons patch stream decoded onto ±40000) was sampled pixel by pixel over its whole+ /// bounding box, up to 65536 × 65536 entries: a synthetic page passed 6 GB in six seconds.+ /// Vendored hayro-interpret patch: mesh shadings are sampled only where they are drawn,+ /// within eight visits per pixel of that area plus four per triangle in it.+ #[test]+ fn mesh_shadings_far_off_the_page_render() {+ let render = |shading: Vec<u8>| {+ let content = b"/Sh0 sh 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 << /Shading << /Sh0 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\n5 0 obj ");+ pdf.extend_from_slice(&shading);+ pdf.extend_from_slice(b" endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());+ let _ = tx.send(r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }));+ });+ let page = rx.recv_timeout(std::time::Duration::from_secs(60)).expect("a mesh shading must not stall the renderer");+ assert!(page.error.is_none(), "{:?}", page.error);+ page+ };+ let stream = |dict: &str, data: &[u8]| {+ let mut s = format!("<< {dict} /Length {} >> stream\n", data.len()).into_bytes();+ s.extend_from_slice(data);+ s.extend_from_slice(b"\nendstream");+ s+ };+ // One Coons patch (flag, 12 points, 4 colours) with 8-bit coordinates around its square.+ let mut coons = vec![0u8];+ for p in [(0, 0), (0, 85), (0, 170), (0, 255), (85, 255), (170, 255), (255, 255), (255, 170), (255, 85), (255, 0), (170, 0), (85, 0)] {+ coons.extend_from_slice(&[p.0, p.1]);+ }+ coons.extend_from_slice(&[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0]);+ // A free-form triangle mesh: three vertices (flag, x, y, colour).+ let triangles = [0u8, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255];+ let mesh = "/ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8";+ let far = "/Decode [-40000 40000 -40000 40000 0 1 0 1 0 1]";+ for (what, shading) in [+ ("a Coons patch", stream(&format!("/ShadingType 6 {mesh} {far}"), &coons)),+ ("a triangle mesh", stream(&format!("/ShadingType 4 {mesh} {far}"), &triangles)),+ ] {+ let page = render(shading);+ assert_eq!(&page.rgba[((38 * 40 + 1) * 4)..][..4], &[255, 0, 0, 255], "{what} far off the page: the rest of the page draws");+ }+ // A patch on the page, and the part of the huge one that covers it, are still shaded:+ // the centre is neither white nor transparent.+ for (what, decode) in [("on the page", "[0 40 0 40 0 1 0 1 0 1]"), ("covering the page", "[-40000 40000 -40000 40000 0 1 0 1 0 1]")] {+ let page = render(stream(&format!("/ShadingType 6 {mesh} /Decode {decode}"), &coons));+ let centre = &page.rgba[((20 * 40 + 20) * 4)..][..4];+ assert!(centre != [255, 255, 255, 255] && centre[3] == 255, "a patch {what} is shaded: {centre:?}");+ }+ // A patch filling a 4 × 4 pt rectangle as a pattern is 722 triangles of a fraction of a+ // pixel each: far more visits than its 16 pixels give, which the per-triangle allowance+ // covers. The rectangle's middle is shaded.+ let content = b"/Pattern cs /P0 scn 10 10 4 4 re f";+ let shading = stream(&format!("/ShadingType 6 {mesh} /Decode [10 14 10 14 0 1 0 1 0 1]"), &coons);+ let mut pdf = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /Pattern << /P0 << /PatternType 2 /Shading 5 0 R >> >> >> >> endobj+".to_vec();+ pdf.extend_from_slice(+ format!(+ "4 0 obj << /Length {} >> stream+",+ content.len()+ )+ .as_bytes(),+ );+ pdf.extend_from_slice(content);+ pdf.extend_from_slice(+ b"+endstream endobj+5 0 obj ",+ );+ pdf.extend_from_slice(&shading);+ pdf.extend_from_slice(+ b" endobj+trailer << /Root 1 0 R >>+%%EOF+",+ );+ 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 });+ assert!(page.error.is_none(), "{:?}", page.error);+ let middle = &page.rgba[((28 * 40 + 12) * 4)..][..4];+ assert!(middle != [255, 255, 255, 255] && middle[3] == 255, "a small patch is shaded: {middle:?}");+ }++ /// The other half of the mesh-shading patch: ten thousand triangles that each cover half+ /// of this 1000 × 1000 canvas walked their bounding boxes ten thousand times over (ten+ /// billion visits). The visit budget stops that work at eight per pixel plus four per+ /// triangle.+ #[test]+ fn many_overlapping_mesh_triangles_finish() {+ // Each triangle: three vertices of flag, x, y, red, green, blue; half of the page.+ let one = [0u8, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255];+ let triangles = one.repeat(10_000);+ let content = b"/Sh0 sh";+ let mut pdf = b"%PDF-1.7+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /Shading << /Sh0 5 0 R >> >> >> endobj+"+ .to_vec();+ pdf.extend_from_slice(+ format!(+ "4 0 obj << /Length {} >> stream+",+ content.len()+ )+ .as_bytes(),+ );+ pdf.extend_from_slice(content);+ pdf.extend_from_slice(+ format!("+endstream endobj+5 0 obj << /ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 40 0 40 0 1 0 1 0 1] /Length {} >> stream+", triangles.len())+ .as_bytes(),+ );+ pdf.extend_from_slice(&triangles);+ pdf.extend_from_slice(+ b"+endstream endobj+trailer << /Root 1 0 R >>+%%EOF+",+ );+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());+ let _ = tx.send(r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 25.0, tag: 0 }));+ });+ let page = rx.recv_timeout(std::time::Duration::from_secs(60)).expect("overlapping mesh triangles must not stall the renderer");+ assert!(page.error.is_none(), "{:?}", page.error);+ assert_eq!((page.width, page.height), (1000, 1000));+ // The triangles cover the lower left half: a pixel there is shaded.+ let p = &page.rgba[((900 * 1000 + 100) * 4)..][..4];+ assert!(p != [255, 255, 255, 255] && p[3] == 255, "the triangles are drawn: {p:?}");+ }++ /// Review of the mesh-shading patch: every patch was cut into 722 triangles before anything+ /// limited them (about 150 KB per patch), and a lattice mesh with `/VerticesPerRow 0` pushed+ /// empty rows for ever. Vendored hayro-interpret patch: patches are triangulated one at a+ /// time, meshes hold at most `MAX_MESH_PATCHES` patches and `MAX_MESH_TRIANGLES` triangles,+ /// and a lattice needs two vertices per row.+ #[test]+ fn mesh_shadings_with_many_patches_or_no_rows_finish() {+ let render = |shading: Vec<u8>| {+ let content = b"/Sh0 sh 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 << /Shading << /Sh0 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\n5 0 obj ");+ pdf.extend_from_slice(&shading);+ pdf.extend_from_slice(b" endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());+ let _ = tx.send(r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }));+ });+ let page = rx.recv_timeout(std::time::Duration::from_secs(60)).expect("a mesh shading must not stall the renderer");+ 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");+ };+ let stream = |dict: &str, data: &[u8]| {+ let mut s = format!("<< {dict} /Length {} >> stream\n", data.len()).into_bytes();+ s.extend_from_slice(data);+ s.extend_from_slice(b"\nendstream");+ s+ };+ let mesh = "/ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8";+ // Forty thousand Coons patches beside the page: 6 GB of triangles if collected first.+ let mut coons = vec![0u8];+ for p in [(0, 0), (0, 85), (0, 170), (0, 255), (85, 255), (170, 255), (255, 255), (255, 170), (255, 85), (255, 0), (170, 0), (85, 0)] {+ coons.extend_from_slice(&[p.0, p.1]);+ }+ coons.extend_from_slice(&[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0]);+ render(stream(&format!("/ShadingType 6 {mesh} /BitsPerFlag 8 /Decode [100 140 100 140 0 1 0 1 0 1]"), &coons.repeat(40_000)));+ // A lattice with no vertices per row.+ render(stream(&format!("/ShadingType 5 {mesh} /VerticesPerRow 0 /Decode [0 40 0 40 0 1 0 1 0 1]"), &[0u8; 64]));+ }+/// From the nightly `cargo xtask fuzz`: an embedded Type 1 font program holding a long run of/// integers. read-fonts 0.39 (through skrifa 0.42) looked ahead after every integer by/// parsing the next token, which looked ahead again, recursing through the whole run: a longdiff --git a/vendor/README.md b/vendor/README.mdindex e719d4da3..eb708e414 100644--- a/vendor/README.md+++ b/vendor/README.md@@ -7,7 +7,7 @@ the fix. Vendoring copyleft code is never allowed (plan/adr/0001).| Crate | Version | Licence | Patches | Test ||---|---|---|---|---|-| 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`; 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) | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied`; (6) `raster::tests::self_referencing_tiling_pattern_terminates`, `raster::tests::self_referencing_type3_glyph_terminates`; (7) `raster::tests::huge_cid_width_ranges_terminate`; (8) `raster::tests::hiding_comments_keeps_fields`; (9) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (10) `raster::tests::type3_glyphs_that_fan_out_into_themselves_finish`; (11) `raster::tests::type1_font_programs_with_long_runs_of_numbers_load_quickly`; (12) `raster::tests::degenerate_annotation_appearances_are_skipped`; (13) `raster::tests::highlights_without_an_appearance_are_drawn`; (14) `raster::tests::malformed_simple_font_widths_keep_later_widths_and_the_font`, `raster::tests::huge_simple_font_first_char_terminates`; (15) `raster::tests::annotation_appearance_box_maps_onto_rect`; (16) `raster::tests::clipping_path_applies_after_any_painting_operator`; (17) `raster::tests::dropping_the_pool_cancels_its_renders`, `raster::tests::the_watchdog_stops_the_render_it_gives_up_on`; (18) `raster::tests::page_contents_and_nested_forms_share_one_budget`, `raster::tests::content_painted_again_and_again_keeps_drawing`, `raster::tests::sampled_functions_with_billions_of_samples_are_refused` |+| 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`; 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 | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied`; (6) `raster::tests::self_referencing_tiling_pattern_terminates`, `raster::tests::self_referencing_type3_glyph_terminates`; (7) `raster::tests::huge_cid_width_ranges_terminate`; (8) `raster::tests::hiding_comments_keeps_fields`; (9) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (10) `raster::tests::type3_glyphs_that_fan_out_into_themselves_finish`; (11) `raster::tests::type1_font_programs_with_long_runs_of_numbers_load_quickly`; (12) `raster::tests::degenerate_annotation_appearances_are_skipped`; (13) `raster::tests::highlights_without_an_appearance_are_drawn`; (14) `raster::tests::malformed_simple_font_widths_keep_later_widths_and_the_font`, `raster::tests::huge_simple_font_first_char_terminates`; (15) `raster::tests::annotation_appearance_box_maps_onto_rect`; (16) `raster::tests::clipping_path_applies_after_any_painting_operator`; (17) `raster::tests::dropping_the_pool_cancels_its_renders`, `raster::tests::the_watchdog_stops_the_render_it_gives_up_on`; (18) `raster::tests::page_contents_and_nested_forms_share_one_budget`, `raster::tests::content_painted_again_and_again_keeps_drawing`, `raster::tests::sampled_functions_with_billions_of_samples_are_refused`; (19) `raster::tests::mesh_shadings_far_off_the_page_render`, `raster::tests::many_overlapping_mesh_triangles_finish`, `raster::tests::mesh_shadings_with_many_patches_or_no_rows_finish` || 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 | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over` || 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) | (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` |diff --git a/vendor/hayro-interpret/src/context.rs b/vendor/hayro-interpret/src/context.rsindex b21dc5f8d..222f74b45 100644--- a/vendor/hayro-interpret/src/context.rs+++ b/vendor/hayro-interpret/src/context.rs@@ -158,6 +158,7 @@ impl<'a> Context<'a> {// PdfCraft patch: a page (or other top-level content) starts with fresh budgets.NESTED_PAINTS.with(|n| n.set(0));CONTENT_LEFT.with(|c| c.set(MAX_PAGE_CONTENT));+ crate::encode::reset_mesh_budget();Self::new_with(initial_transform, bbox, cache, xref, settings, state, 0)}diff --git a/vendor/hayro-interpret/src/encode.rs b/vendor/hayro-interpret/src/encode.rsindex d6b943ec0..498ed909c 100644--- a/vendor/hayro-interpret/src/encode.rs+++ b/vendor/hayro-interpret/src/encode.rs@@ -43,6 +43,12 @@ impl EncodedShadingPattern {impl ShadingPattern {/// Encode the shading pattern.pub fn encode(&self) -> EncodedShadingPattern {+ self.encode_within(None)+ }++ /// PdfCraft patch: encode the shading pattern for drawing inside `area` (device space) only.+ /// Mesh shadings are sampled pixel by pixel, and only there (see `TriangleSampler`).+ pub fn encode_within(&self, area: Option<kurbo::Rect>) -> EncodedShadingPattern {let base_transform;let shading_type = match self.shading.shading_type.as_ref() {@@ -73,7 +79,9 @@ impl ShadingPattern {function,} => {let full_transform = self.matrix;- let samples = sample_triangles(triangles, full_transform);+ let mut sampler = TriangleSampler::new(area);+ sampler.sample(triangles, full_transform);+ let samples = sampler.map;base_transform = Affine::IDENTITY;@@ -83,13 +91,22 @@ impl ShadingPattern {}}ShadingType::CoonsPatchMesh { patches, function } => {+ // PdfCraft patch: one patch's triangles at a time (each is 722); collecting all+ // of them first held 150 KB per patch before any limit applied.+ let full_transform = self.matrix;+ let mut sampler = TriangleSampler::new(area);let mut triangles = vec![];for patch in patches {+ if !mesh_budget_left() {+ break;+ }+ triangles.clear();patch.to_triangles(&mut triangles);+ if !sampler.sample(&triangles, full_transform) {+ break;+ }}-- let full_transform = self.matrix;- let samples = sample_triangles(&triangles, full_transform);+ let samples = sampler.map;base_transform = Affine::IDENTITY;@@ -99,13 +116,21 @@ impl ShadingPattern {}}ShadingType::TensorProductPatchMesh { patches, function } => {+ // PdfCraft patch: one patch's triangles at a time, as for Coons patches.+ let full_transform = self.matrix;+ let mut sampler = TriangleSampler::new(area);let mut triangles = vec![];for patch in patches {+ if !mesh_budget_left() {+ break;+ }+ triangles.clear();patch.to_triangles(&mut triangles);+ if !sampler.sample(&triangles, full_transform) {+ break;+ }}-- let full_transform = self.matrix;- let samples = sample_triangles(&triangles, full_transform);+ let samples = sampler.map;base_transform = Affine::IDENTITY;@@ -185,41 +210,110 @@ fn encode_axial_shading()}-fn sample_triangles(- triangles: &[Triangle],- transform: Affine,-) -> FxHashMap<(u16, u16), ColorComponents> {- let mut map = FxHashMap::default();-- for t in triangles {- let t = {- let p0 = transform * t.p0.point;- let p1 = transform * t.p1.point;- let p2 = transform * t.p2.point;-- let mut v0 = t.p0.clone();- v0.point = p0;- let mut v1 = t.p1.clone();- v1.point = p1;- let mut v2 = t.p2.clone();- v2.point = p2;-- Triangle::new(v0, v1, v2)+/// PdfCraft patch: pixel visits one mesh shading may make, per pixel of the area it is drawn in+/// and per triangle. Sampling walks each triangle's bounding box (rounded out to whole pixels),+/// so triangles far off the page (a fuzzed patch decoded onto ±40000) asked for 65536 × 65536+/// samples, and many triangles covering the same pixels repeat the work. A triangle's box is+/// about twice its area, and a sub-pixel triangle's box is at most 2 × 2 pixels.+const MESH_VISITS_PER_PIXEL: u64 = 8;+const MESH_VISITS_PER_TRIANGLE: u64 = 4;++/// PdfCraft patch: the visits allowed when no area is given (the public `encode`).+const MESH_VISITS_WITHOUT_AREA: u64 = 1 << 24;++/// PdfCraft patch: mesh triangles one page may sample in all, across every shading painted on+/// it. A shading is triangulated again each time it is painted (2^16 patches are 47 million+/// triangles, several seconds), so painting one a thousand times took hours. A 200 × 200+/// gradient mesh is 29 million triangles.+const MAX_PAGE_MESH_TRIANGLES: u64 = 1 << 25;++std::thread_local! {+ static MESH_TRIANGLES_LEFT: core::cell::Cell<u64> =+ const { core::cell::Cell::new(MAX_PAGE_MESH_TRIANGLES) };+}++/// PdfCraft patch: a page starts with a fresh mesh triangle budget (called from+/// `Context::new`).+pub(crate) fn reset_mesh_budget() {+ MESH_TRIANGLES_LEFT.with(|n| n.set(MAX_PAGE_MESH_TRIANGLES));+}++/// PdfCraft patch: `false` once this page's mesh triangle budget is spent.+fn mesh_budget_left() -> bool {+ MESH_TRIANGLES_LEFT.with(|n| n.get() > 0)+}++/// PdfCraft patch: samples mesh triangles into a map with one entry per pixel, only inside+/// `area` (device space), within the visit budget above.+struct TriangleSampler {+ map: FxHashMap<(u16, u16), ColorComponents>,+ area: kurbo::Rect,+ visits_left: u64,+}++impl TriangleSampler {+ fn new(area: Option<kurbo::Rect>) -> Self {+ let visits_left = match area {+ Some(a) => (a.width().max(0.0).ceil() as u64)+ .saturating_mul(a.height().max(0.0).ceil() as u64)+ .saturating_mul(MESH_VISITS_PER_PIXEL),+ None => MESH_VISITS_WITHOUT_AREA,};+ Self {+ map: FxHashMap::default(),+ area: area.unwrap_or(kurbo::Rect::new(0.0, 0.0, 65536.0, 65536.0)),+ visits_left,+ }+ }- let bbox = t.bounding_box();+ /// Sample `triangles`; `false` once a budget is spent (the rest is left unsampled).+ fn sample(&mut self, triangles: &[Triangle], transform: Affine) -> bool {+ let page_left = MESH_TRIANGLES_LEFT.with(core::cell::Cell::get);+ if page_left < triangles.len() as u64 {+ MESH_TRIANGLES_LEFT.with(|n| n.set(0));+ warn!("page mesh triangle budget exceeded; the rest of the shading is not drawn");+ return false;+ }+ MESH_TRIANGLES_LEFT.with(|n| n.set(page_left - triangles.len() as u64));+ for t in triangles {+ let t = {+ let p0 = transform * t.p0.point;+ let p1 = transform * t.p1.point;+ let p2 = transform * t.p2.point;++ let mut v0 = t.p0.clone();+ v0.point = p0;+ let mut v1 = t.p1.clone();+ v1.point = p1;+ let mut v2 = t.p2.clone();+ v2.point = p2;++ Triangle::new(v0, v1, v2)+ };++ // Only the part of the triangle inside `area`; only such triangles add visits.+ let bbox = t.bounding_box().intersect(self.area);+ if bbox.width() <= 0.0 || bbox.height() <= 0.0 {+ continue;+ }+ self.visits_left = self.visits_left.saturating_add(MESH_VISITS_PER_TRIANGLE);- for y in (bbox.y0.floor() as u16)..(bbox.y1.ceil() as u16) {- for x in (bbox.x0.floor() as u16)..(bbox.x1.ceil() as u16) {- let point = Point::new(x as f64, y as f64);- if t.contains_point(point) {- map.insert((x, y), t.interpolate(point));+ for y in (bbox.y0.floor() as u16)..(bbox.y1.ceil() as u16) {+ for x in (bbox.x0.floor() as u16)..(bbox.x1.ceil() as u16) {+ if self.visits_left == 0 {+ warn!("mesh shading visit budget exceeded; the rest is not drawn");+ return false;+ }+ self.visits_left -= 1;+ let point = Point::new(x as f64, y as f64);+ if t.contains_point(point) {+ self.map.insert((x, y), t.interpolate(point));+ }}}}+ true}-- map}fn encode_function_shading(domain: &[f32; 4], function: &ShadingFunction) -> EncodedShadingType {diff --git a/vendor/hayro-interpret/src/shading.rs b/vendor/hayro-interpret/src/shading.rsindex 1e29c5e94..74aaa8011 100644--- a/vendor/hayro-interpret/src/shading.rs+++ b/vendor/hayro-interpret/src/shading.rs@@ -545,6 +545,13 @@ impl TensorProductPatch {}}+/// PdfCraft patch: the most triangles a free-form or lattice mesh, and the most patches a+/// patch mesh, may hold. Each was read without limit: a patch can be 19 bits, a triangle 216+/// bytes in memory, so a small stream made gigabytes. Real meshes are far smaller (a 200 × 200+/// gradient mesh is 40 thousand patches).+const MAX_MESH_TRIANGLES: usize = 1 << 20;+const MAX_MESH_PATCHES: usize = 1 << 16;+fn read_free_form_triangles(data: &[u8],bpf: u8,@@ -594,6 +601,11 @@ fn read_free_form_triangles(continue;}+ // PdfCraft patch: see `MAX_MESH_TRIANGLES`.+ if triangles.len() >= MAX_MESH_TRIANGLES {+ warn!("free-form mesh has over {MAX_MESH_TRIANGLES} triangles; the rest is not drawn");+ break;+ }triangles.push(Triangle::new(a.clone()?, b.clone()?, c.clone()?));}@@ -787,6 +799,15 @@ fn read_lattice_triangles(vertices_per_row: u32,decode: &[f32],) -> Option<Vec<Triangle>> {+ // PdfCraft patch: ISO 32000-2 8.7.4.5.6 requires at least two vertices per row; with none,+ // the loop below pushed empty rows for ever, and one row of 4294967295 read the whole stream+ // into memory before any cap (see `MAX_MESH_TRIANGLES`).+ if !(2..=(MAX_MESH_TRIANGLES / 2) as u32).contains(&vertices_per_row) {+ warn!("lattice-form mesh with {vertices_per_row} vertices per row");++ return None;+ }+let mut lattices = vec![];let ([x_min, x_max, y_min, y_max], decode) = split_decode(decode)?;@@ -806,6 +827,11 @@ fn read_lattice_triangles(};'outer: loop {+ // PdfCraft patch: see `MAX_MESH_TRIANGLES` (two triangles per vertex at most).+ if lattices.len().saturating_mul(vertices_per_row as usize) >= MAX_MESH_TRIANGLES / 2 {+ warn!("lattice-form mesh has too many vertices; the rest is not drawn");+ break;+ }let mut single_row = vec![];for _ in 0..vertices_per_row {@@ -895,6 +921,11 @@ wherelet mut patches = vec![];while let Some(flag) = reader.read(bpf) {+ // PdfCraft patch: see `MAX_MESH_PATCHES`.+ if patches.len() >= MAX_MESH_PATCHES {+ warn!("patch mesh has over {MAX_MESH_PATCHES} patches; the rest is not drawn");+ break;+ }let mut control_points = vec![Point::ZERO; 16]; // Always allocate 16, use subset as needed.let mut colors = [smallvec![], smallvec![], smallvec![], smallvec![]];diff --git a/vendor/hayro/src/renderer.rs b/vendor/hayro/src/renderer.rsindex ebf3cdc57..89982c48a 100644--- a/vendor/hayro/src/renderer.rs+++ b/vendor/hayro/src/renderer.rs@@ -549,7 +549,9 @@ impl Renderer {self.ctx.height() as f64,));- let encoded = s.encode();+ // PdfCraft patch: mesh shadings are sampled only inside `bbox` (and a+ // pixel around it: texels at a fractional edge look one pixel further).+ let encoded = s.encode_within(Some(bbox.inflate(1.0, 1.0)));let (image, width, height, transform, may_have_transparency) =render_shading_texture(bbox, &encoded);let may_have_transparency =