mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-10 13:01:29 +00:00
M2: an Indexed image whose lookup table is too short is skipped with a warning, not drawn black (ISO 32000-2 8.6.6.3)
An image in [/Indexed /DeviceRGB 7 <FF0000 00FF00>] was drawn entirely black, indices 0 and 1 included. The interpreter rejected the colour space when the table ran out, and the image fell back to DeviceGray, so its index values were painted as near-black grey levels. ISO 32000-2 8.6.6.3 says hival "shall be an integer", no greater than 255, and the table "shall be m x (hival + 1) bytes long". An image whose Indexed space breaks this (hival not an integer in 0..=255, or a lookup missing or shorter than needed) is now not drawn, and the render reports RenderWarning::MalformedIndexedImage once per page; pdfcraft-cli render prints it. A longer table is still fine. Inline images, including one naming such a space as a resource, are skipped the same way. Fill and stroke colours in such a space go through a different path and are unchanged. Vendored hayro-interpret patch (60), recorded in vendor/README.md. Tests: crates/render/tests/it/indexed_lookup.rs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC
This commit is contained in:
1 parent
3517d05b47
commit
7734556137
8 files changed
+243
-2
No files matched your search
@@ -407,6 +407,9 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
|
||||
let _ =
|
||||
writeln!(std::io::stderr().lock(), "warning: page {page}: a colour that could not be computed was painted in a fallback colour");
|
||||
}
|
||||
pdfcraft_render::RenderWarning::MalformedIndexedImage => {
|
||||
let _ = writeln!(std::io::stderr().lock(), "warning: page {page}: an image with a malformed Indexed colour table was not drawn");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -230,6 +230,10 @@ pub enum RenderWarning {
|
||||
/// A colour could not be computed (a colour space that cannot be read, or a Separation or
|
||||
/// DeviceN tint transform that cannot be evaluated) and was painted in a fallback colour.
|
||||
ColourFallback,
|
||||
/// An image was not drawn because its `/Indexed` colour space is malformed (ISO 32000-2
|
||||
/// §8.6.6.3): `hival` not an integer in 0..=255, or a lookup table shorter than
|
||||
/// m × (hival + 1) bytes. Reported once per page however many images it affects.
|
||||
MalformedIndexedImage,
|
||||
}
|
||||
|
||||
/// Counters for work performed by a renderer or render pool.
|
||||
@@ -412,10 +416,12 @@ fn warning_settings(settings: &InterpreterSettings, warnings: Arc<Mutex<Vec<Rend
|
||||
InterpreterSettings {
|
||||
warning_sink: Arc::new(move |warning| {
|
||||
// Nested forms, Type 3 glyphs and patterns are interpreted again and each reports the
|
||||
// exhausted budget, or the colours that fell back: once per page is enough.
|
||||
// exhausted budget, or the colours that fell back, and several images can share one
|
||||
// malformed colour space: each warning is recorded once per page.
|
||||
let warning = match warning {
|
||||
InterpreterWarning::ContentTruncated => RenderWarning::ContentTruncated,
|
||||
InterpreterWarning::ColorFallback => RenderWarning::ColourFallback,
|
||||
InterpreterWarning::MalformedIndexedImage => RenderWarning::MalformedIndexedImage,
|
||||
InterpreterWarning::UnsupportedFont | InterpreterWarning::ImageDecodeFailure => return,
|
||||
};
|
||||
let mut warnings = lock(&target);
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! An `/Indexed` image whose colour space ISO 32000-2 §8.6.6.3 rules out (a lookup table
|
||||
//! shorter than m × (hival + 1) bytes, or a `hival` that is not an integer in 0..=255) is not
|
||||
//! drawn, and the render reports `RenderWarning::MalformedIndexedImage`. It used to fall back to
|
||||
//! DeviceGray and paint its indices as near-black, even indices whose entries were present.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RenderWarning, RenderedPage, RequestKind};
|
||||
|
||||
/// A 200 × 200 page whose `/Im` image is two samples wide (indices 0 and 1) and covers the page,
|
||||
/// with `/P` naming `colour_space` as a resource. `extra` objects are numbered from 6.
|
||||
fn pdf(colour_space: &str, content: &str, extra: &[&[u8]]) -> Vec<u8> {
|
||||
let mut objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R \
|
||||
/Resources << /XObject << /Im 5 0 R >> /ColorSpace << /P {colour_space} >> >> >>"
|
||||
)
|
||||
.into_bytes(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()).into_bytes(),
|
||||
format!(
|
||||
"<< /Type /XObject /Subtype /Image /Width 2 /Height 1 /BitsPerComponent 8 \
|
||||
/ColorSpace {colour_space} /Filter /ASCIIHexDecode /Length 5 >>\nstream\n0001>\nendstream"
|
||||
)
|
||||
.into_bytes(),
|
||||
];
|
||||
objs.extend(extra.iter().map(|o| o.to_vec()));
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
let size = objs.len() + 1;
|
||||
out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
|
||||
for off in offsets {
|
||||
out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn render(bytes: Vec<u8>) -> RenderedPage {
|
||||
let page = PageRenderer::new(Arc::new(bytes), RenderConfig::default()).render(RenderRequest {
|
||||
page: 0,
|
||||
kind: RequestKind::Pixels,
|
||||
tile: None,
|
||||
scale: 1.0,
|
||||
tag: 0,
|
||||
preview: false,
|
||||
});
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (200, 200));
|
||||
page
|
||||
}
|
||||
|
||||
/// The left (index 0) and right (index 1) halves' centre pixels, RGB.
|
||||
fn halves(page: &RenderedPage) -> [[u8; 3]; 2] {
|
||||
[50usize, 150].map(|x| {
|
||||
let at = (100 * page.width as usize + x) * 4;
|
||||
let px = page.rgba.get(at..at + 3).expect("pixel inside the page");
|
||||
[px[0], px[1], px[2]]
|
||||
})
|
||||
}
|
||||
|
||||
const WHITE: [[u8; 3]; 2] = [[255, 255, 255], [255, 255, 255]];
|
||||
const RED_GREEN: [[u8; 3]; 2] = [[255, 0, 0], [0, 255, 0]];
|
||||
const DRAW_IMAGE: &str = "q 200 0 0 200 0 0 cm /Im Do Q";
|
||||
|
||||
fn assert_skipped(colour_space: &str, extra: &[&[u8]]) {
|
||||
let page = render(pdf(colour_space, DRAW_IMAGE, extra));
|
||||
assert_eq!(halves(&page), WHITE, "{colour_space}: the image must not be drawn");
|
||||
assert_eq!(page.warnings, vec![RenderWarning::MalformedIndexedImage], "{colour_space}: the skip is reported");
|
||||
}
|
||||
|
||||
fn assert_drawn(colour_space: &str, extra: &[&[u8]]) {
|
||||
let page = render(pdf(colour_space, DRAW_IMAGE, extra));
|
||||
assert_eq!(halves(&page), RED_GREEN, "{colour_space}: palette entries 0 and 1");
|
||||
assert!(page.warnings.is_empty(), "{colour_space}: {:?}", page.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_shorter_than_hival_needs_skips_the_image_with_a_warning() {
|
||||
// hival 7 over DeviceRGB needs 24 bytes; 6 are given. Indices 0 and 1 used to draw black.
|
||||
assert_skipped("[/Indexed /DeviceRGB 7 <FF0000 00FF00>]", &[]);
|
||||
// One byte short of two entries.
|
||||
assert_skipped("[/Indexed /DeviceRGB 1 <FF0000 00FF>]", &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_lookup_draws_its_colours() {
|
||||
assert_drawn("[/Indexed /DeviceRGB 1 <FF0000 00FF00>]", &[]);
|
||||
assert_drawn("[/Indexed /DeviceRGB 7 <FF0000 00FF00 000000 000000 000000 000000 000000 000000>]", &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_longer_than_needed_uses_its_first_entries() {
|
||||
assert_drawn("[/Indexed /DeviceRGB 1 <FF0000 00FF00 0000FF FFFF00>]", &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hival_outside_0_to_255_or_not_an_integer_skips_the_image() {
|
||||
let long = format!("<FF0000 00FF00{}>", "00".repeat(3 * 300));
|
||||
assert_skipped(&format!("[/Indexed /DeviceRGB 300 {long}]"), &[]);
|
||||
assert_skipped("[/Indexed /DeviceRGB -1 <FF0000 00FF00>]", &[]);
|
||||
assert_skipped("[/Indexed /DeviceRGB 1.5 <FF0000 00FF00 0000FF>]", &[]);
|
||||
assert_skipped("[/Indexed /DeviceRGB /One <FF0000 00FF00>]", &[]);
|
||||
// 255, the largest hival, with a full table still draws.
|
||||
assert_drawn(&format!("[/Indexed /DeviceRGB 255 <FF0000 00FF00{}>]", "00".repeat(3 * 254)), &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_or_missing_lookup_skips_the_image_without_panicking() {
|
||||
assert_skipped("[/Indexed /DeviceRGB 1 <>]", &[]);
|
||||
assert_skipped("[/Indexed /DeviceRGB 1 ()]", &[]);
|
||||
assert_skipped("[/Indexed /DeviceRGB 1]", &[]);
|
||||
assert_skipped("[/Indexed /DeviceRGB 0 null]", &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_stream_is_measured_after_decoding() {
|
||||
let short: &[u8] = b"<< /Length 14 /Filter /ASCIIHexDecode >>\nstream\nFF0000 00FF00>\nendstream";
|
||||
assert_skipped("[/Indexed /DeviceRGB 7 6 0 R]", &[short]);
|
||||
assert_drawn("[/Indexed /DeviceRGB 1 6 0 R]", &[short]);
|
||||
let empty: &[u8] = b"<< /Length 0 >>\nstream\n\nendstream";
|
||||
assert_skipped("[/Indexed /DeviceRGB 1 6 0 R]", &[empty]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_images_with_a_short_lookup_are_skipped_too() {
|
||||
let inline = |cs: &str| format!("q 200 0 0 200 0 0 cm BI /W 2 /H 1 /BPC 8 /CS {cs} /F /AHx ID 0001> EI Q");
|
||||
// Named through the page's resources.
|
||||
let page = render(pdf("[/Indexed /DeviceRGB 7 <FF0000 00FF00>]", &inline("/P"), &[]));
|
||||
assert_eq!(halves(&page), WHITE);
|
||||
assert_eq!(page.warnings, vec![RenderWarning::MalformedIndexedImage]);
|
||||
// Given in place, with the inline abbreviations.
|
||||
let page = render(pdf("/DeviceRGB", &inline("[/I /RGB 7 <FF0000 00FF00>]"), &[]));
|
||||
assert_eq!(halves(&page), WHITE);
|
||||
assert_eq!(page.warnings, vec![RenderWarning::MalformedIndexedImage]);
|
||||
// And a well-formed one still draws.
|
||||
let page = render(pdf("[/Indexed /DeviceRGB 1 <FF0000 00FF00>]", &inline("/P"), &[]));
|
||||
assert_eq!(halves(&page), RED_GREEN);
|
||||
assert!(page.warnings.is_empty(), "{:?}", page.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_with_several_malformed_images_reports_the_warning_once_and_draws_the_rest() {
|
||||
let content = format!("{DRAW_IMAGE} {DRAW_IMAGE} 0 0 1 rg 0 0 10 10 re f");
|
||||
let page = render(pdf("[/Indexed /DeviceRGB 7 <FF0000 00FF00>]", &content, &[]));
|
||||
assert_eq!(page.warnings, vec![RenderWarning::MalformedIndexedImage]);
|
||||
let at = (195 * page.width as usize + 5) * 4;
|
||||
assert_eq!(page.rgba.get(at..at + 3), Some(&[0u8, 0, 255][..]), "content after the skipped images still draws");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod cid_fallback_query;
|
||||
mod indexed_lookup;
|
||||
mod inline_image_ei;
|
||||
mod jbig2_invariants;
|
||||
mod knockout_backdrop;
|
||||
|
||||
Vendored
+1
-1
@@ -39,7 +39,7 @@ Other resource categories retain their existing parent-chain lookup.
|
||||
|
||||
| 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`; 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-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`) |
|
||||
| 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` |
|
||||
|
||||
Vendored
+47
@@ -1033,6 +1033,53 @@ impl Indexed {
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (60): whether `object` is an `/Indexed` colour space that ISO 32000-2
|
||||
/// §8.6.6.3 rules out: `hival` is not an integer in 0..=255, or the lookup table is missing or
|
||||
/// shorter than m × (hival + 1) bytes for a base space of m components. A longer table is fine
|
||||
/// (its first bytes are used). An Indexed space whose base cannot be read is not judged here,
|
||||
/// so its existing handling is unchanged.
|
||||
///
|
||||
/// Upstream treated such a space as unreadable, and an image that named it then fell back to
|
||||
/// DeviceGray: its indices were drawn as near-black grey levels, even indices whose entries
|
||||
/// were present. The image path uses this to skip the image with a warning instead.
|
||||
pub(crate) fn is_malformed_indexed(object: &Object<'_>, cache: &Cache) -> bool {
|
||||
let Object::Array(array) = object else {
|
||||
return false;
|
||||
};
|
||||
let mut iter = array.flex_iter();
|
||||
let Some(family) = iter.next::<Name<'_>>() else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(family.deref(), INDEXED | I) {
|
||||
return false;
|
||||
}
|
||||
let Some(base) = iter
|
||||
.next::<Object<'_>>()
|
||||
.and_then(|o| ColorSpace::new(o, cache))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(hival) = iter.next::<object::Number>().and_then(|n| {
|
||||
let value = n.as_f64();
|
||||
// A real with a fraction, a negative number or one past 255 is not a usable `hival`.
|
||||
(value.fract() == 0.0 && (0.0..=255.0).contains(&value)).then(|| n.as_i64())
|
||||
}) else {
|
||||
return true;
|
||||
};
|
||||
let Some(needed) = usize::try_from(hival)
|
||||
.ok()
|
||||
.and_then(|h| h.checked_add(1))
|
||||
.and_then(|entries| entries.checked_mul(usize::from(base.num_components())))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let lookup_len = iter
|
||||
.next::<Stream<'_>>()
|
||||
.and_then(|s| s.decoded().ok().map(|d| d.len()))
|
||||
.or_else(|| iter.next::<object::String<'_>>().map(|s| s.as_bytes().len()));
|
||||
lookup_len.is_none_or(|len| len < needed)
|
||||
}
|
||||
|
||||
impl ToRgb for Indexed {
|
||||
fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {
|
||||
let mut indexed = vec![0.0; input.len() * self.base.num_components() as usize];
|
||||
|
||||
+17
@@ -161,6 +161,10 @@ pub enum InterpreterWarning {
|
||||
/// read, or a Separation or DeviceN tint transform that cannot be evaluated) and was painted
|
||||
/// in a fallback colour. Reported at most once per content stream.
|
||||
ColorFallback,
|
||||
/// PdfCraft patch (60): an image was not drawn because its `/Indexed` colour space is
|
||||
/// malformed (ISO 32000-2 §8.6.6.3): `hival` not an integer in 0..=255, or a lookup table
|
||||
/// shorter than its entries need.
|
||||
MalformedIndexedImage,
|
||||
}
|
||||
|
||||
/// interpret the contents of the page and render them into the device.
|
||||
@@ -927,6 +931,19 @@ fn interpret_window<'a>(
|
||||
let warning_sink = context.settings.warning_sink.clone();
|
||||
let transfer_function = context.get().graphics_state.transfer_function.clone();
|
||||
let cache = context.interpreter_cache.object_cache.clone();
|
||||
// PdfCraft patch (60): an inline image naming a resource colour space that is a
|
||||
// malformed Indexed space is skipped with a warning, as `ImageXObject::new` does
|
||||
// for one given in place.
|
||||
let inline_dict = i.0.dict();
|
||||
if inline_dict
|
||||
.get::<hayro_syntax::object::Name<'_>>(hayro_syntax::object::dict::keys::CS)
|
||||
.or_else(|| inline_dict.get::<hayro_syntax::object::Name<'_>>(hayro_syntax::object::dict::keys::COLORSPACE))
|
||||
.and_then(|name| resources.get_color_space(&name))
|
||||
.is_some_and(|cs| crate::color::is_malformed_indexed(&cs, &cache))
|
||||
{
|
||||
warning_sink(InterpreterWarning::MalformedIndexedImage);
|
||||
continue;
|
||||
}
|
||||
// PdfCraft patch: inline images are not cached (see `DecodedImageKey`).
|
||||
// PdfCraft patch (38): an inline image in a device space, named directly or by a
|
||||
// resource, draws in its default.
|
||||
|
||||
+10
@@ -524,6 +524,16 @@ impl<'a> ImageXObject<'a> {
|
||||
if let Some((space, key)) = default {
|
||||
default_space = Some(key);
|
||||
Some(space)
|
||||
} else if cs_obj
|
||||
.as_ref()
|
||||
.is_some_and(|c| crate::color::is_malformed_indexed(c, cache))
|
||||
{
|
||||
// PdfCraft patch (60): an Indexed space that ISO 32000-2 §8.6.6.3 rules out
|
||||
// (a short lookup table, an unusable `hival`) leaves no colour for some or all
|
||||
// samples. The image is not drawn, and the caller is told, rather than falling
|
||||
// back to DeviceGray and painting its indices as near-black.
|
||||
warning_sink(InterpreterWarning::MalformedIndexedImage);
|
||||
return None;
|
||||
} else {
|
||||
cs_obj
|
||||
.clone()
|
||||
|
||||
Reference in new issue
Block a user