mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-09 20:43:12 +00:00
M1: numbered glyph names read as their codes only in fonts where every one does (create.text-extraction)
The previous commit read a glyph name that only numbers its glyph (`C70`, `MT72`, `G4E`) as its code's Latin-1 character whenever the number, in decimal or hexadecimal, was that code. In fonts whose names number something else (`/Differences [1 /C70 /C105 ...]`, a subset's order), a name can match its code by coincidence: `/MT40` at 0x40 read `@` where the page draws `(` (PDFBOX-1078), `/C39` at 0x39 read `9` (PDFBOX-1783). The rule now applies only in a Type 1 font where every numbered name in its encoding names its own code (`numbered_names_name_their_codes`, worked out once per font). `/C1` at 233 beside `/C70` at 70, the review counterexample on #3239, turns the whole font back to nothing, and #3239's test font (`c251` at 97, `C1` at 233 beside `C39` at 39) reads exactly as #3239 expected again. Codes 128-255 read as Latin-1 (`C174` = `®`), as pdftotext, PDFium, MuPDF and Acrobat read them. Vendor ledger: hayro-interpret patch 99. Test: text::tests::numbered_glyph_names_read_as_their_own_code (fails with the guard switched off, and with the fallback switched off). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Pq7HyCHD1R3rywQBPCHXZA
This commit is contained in:
1 parent
1ad2638460
commit
218fbcf1b5
4 files changed
+152
-70
No files matched your search
@@ -464,10 +464,10 @@ fn the_annex_d2_alias_codes_read_as_an_ordinary_hyphen_and_space() {
|
||||
/// (`f_i`) and suffixed (`hyphen.case`) names go by the glyph list specification's full
|
||||
/// mapping. A name that only numbers the glyph reads as nothing, not as a guess from the code
|
||||
/// (review on #3239: with `/C1` at 233, StandardEncoding's 233 would read `Ø` for a glyph drawn
|
||||
/// as `é`), unless its number is its own code: `c251` at 97 and `C39.sc` at 61 read as nothing,
|
||||
/// `C39` at 39 and `C174` at 174 as `'` and `®` (see
|
||||
/// `numbered_glyph_names_read_as_their_own_code`). A ZapfDingbats name (`a12`) and a name with
|
||||
/// no meaning left (`foo`) read as nothing.
|
||||
/// as `é`). `C39` at 39 and `C174` at 174 name their own codes, but this font's other numbered
|
||||
/// names (`c251` at 97, `C39.sc` at 61, `C1` at 233, `a12` at 88) don't, so they read as
|
||||
/// nothing too (see `numbered_glyph_names_read_as_their_own_code`). A name with no meaning
|
||||
/// left (`foo`) reads as nothing.
|
||||
#[test]
|
||||
fn glyph_names_outside_the_glyph_list_still_read_as_text() {
|
||||
use lopdf::{Object, dictionary};
|
||||
@@ -493,37 +493,58 @@ fn glyph_names_outside_the_glyph_list_still_read_as_text() {
|
||||
let pdf = encoded_pages(&[(differences, &content[..])]);
|
||||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text();
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
assert_eq!(lines, ["fi", "fl", "-", "'", "\u{ae}", "fi"], "{text:?}");
|
||||
assert_eq!(lines, ["fi", "fl", "-", "fi"], "{text:?}");
|
||||
}
|
||||
|
||||
/// A glyph name that only numbers its glyph, with no `/ToUnicode` (ISO 32000-2 §9.10.2 has no
|
||||
/// route for it), reads as its code's character when the number is that very code, in decimal
|
||||
/// (`C70` at 70, `C0071` at 71, `MT72` at 72) or hexadecimal (`G49` at 0x49, `GE9` at 0xE9), as
|
||||
/// pdftotext, PDFium and MuPDF all read it: Windows printer drivers name subset glyphs so. A
|
||||
/// number naming another code (`C70` at 1, `/C1` at 234) or a control character (`C9` at 9)
|
||||
/// still reads as nothing.
|
||||
/// route for it), reads as its code's Latin-1 character when the number is that very code, in
|
||||
/// decimal (`C70` at 70, `C0071` at 71, `MT72` at 72, `C39` at 39, `C174` at 174) or
|
||||
/// hexadecimal (`G49` at 0x49, `GE9` at 0xE9), as pdftotext, PDFium, MuPDF and Acrobat read
|
||||
/// it: Windows printer drivers and typesetters name subset glyphs so. A control character
|
||||
/// (`C9` at 9) still reads as nothing. Only in a font where every numbered name names its own
|
||||
/// code: one more name numbering another code (`/C1` at 233, review on #3239) turns the whole
|
||||
/// font back to nothing, and so does a font whose names number something else, where a name
|
||||
/// can match its code by coincidence (`/MT40` at 0x40).
|
||||
#[test]
|
||||
fn numbered_glyph_names_read_as_their_own_code() {
|
||||
use lopdf::{Object, dictionary};
|
||||
let name = |n: &str| Object::Name(n.as_bytes().to_vec());
|
||||
let differences = Object::Dictionary(dictionary! {
|
||||
"Type" => "Encoding",
|
||||
"Differences" => vec![
|
||||
Object::Integer(70), name("C70"), name("C0071"), name("MT72"), name("G49"),
|
||||
Object::Integer(233), name("GE9"), Object::Integer(1), name("C70"), Object::Integer(234), name("C1"),
|
||||
Object::Integer(9), name("C9"),
|
||||
],
|
||||
});
|
||||
let encoding = |differences: Vec<Object>| Object::Dictionary(dictionary! { "Type" => "Encoding", "Differences" => differences });
|
||||
// One glyph per line, as in `glyph_names_outside_the_glyph_list_still_read_as_text`.
|
||||
let mut content = b"BT /F1 20 Tf 20 290 Td".to_vec();
|
||||
for code in *b"FGHI\xe9\x01\xea\x09" {
|
||||
content.extend_from_slice(format!(" <{code:02x}> Tj 0 -25 Td").as_bytes());
|
||||
}
|
||||
content.extend_from_slice(b" ET");
|
||||
let pdf = encoded_pages(&[(differences, &content[..])]);
|
||||
let text = extract_page(&pdf, 0, &InterpreterSettings::default()).unwrap().plain_text();
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
assert_eq!(lines, ["F", "G", "H", "I", "\u{e9}"], "{text:?}");
|
||||
let one_per_line = |codes: &[u8]| {
|
||||
let mut content = b"BT /F1 20 Tf 20 290 Td".to_vec();
|
||||
for code in codes {
|
||||
content.extend_from_slice(format!(" <{code:02x}> Tj 0 -25 Td").as_bytes());
|
||||
}
|
||||
content.extend_from_slice(b" ET");
|
||||
content
|
||||
};
|
||||
let own = encoding(vec![
|
||||
Object::Integer(70),
|
||||
name("C70"),
|
||||
name("C0071"),
|
||||
name("MT72"),
|
||||
name("G49"),
|
||||
Object::Integer(233),
|
||||
name("GE9"),
|
||||
Object::Integer(39),
|
||||
name("C39"),
|
||||
Object::Integer(174),
|
||||
name("C174"),
|
||||
Object::Integer(9),
|
||||
name("C9"),
|
||||
]);
|
||||
let one_other = encoding(vec![Object::Integer(70), name("C70"), Object::Integer(233), name("C1")]);
|
||||
let numbered_otherwise = encoding(vec![Object::Integer(1), name("C70"), name("C105"), Object::Integer(64), name("MT40")]);
|
||||
let pages = [one_per_line(b"FGHI\xe9'\xae\x09"), one_per_line(b"F\xe9"), one_per_line(b"\x01\x02@")];
|
||||
let pdf = encoded_pages(&[(own, &pages[0][..]), (one_other, &pages[1][..]), (numbered_otherwise, &pages[2][..])]);
|
||||
let lines = |page| {
|
||||
let text = extract_page(&pdf, page, &InterpreterSettings::default()).unwrap().plain_text();
|
||||
text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(lines(0), ["F", "G", "H", "I", "\u{e9}", "'", "\u{ae}"]);
|
||||
assert!(lines(1).is_empty(), "/C1 at 233 beside /C70 at 70: {:?}", lines(1));
|
||||
assert!(lines(2).is_empty(), "/MT40 at 0x40 among names numbering other codes: {:?}", lines(2));
|
||||
}
|
||||
|
||||
/// Review on #3239: the glyph list specification's `uni` and `u` forms take uppercase hex
|
||||
|
||||
Vendored
+3
-6
@@ -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 (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroLine truncated
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most 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; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, TaLine truncated
|
||||
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
|
||||
@@ -93,11 +93,8 @@ each part through the list, `uniXXXX…` or `uXXXX`; a `uni` part with any group
|
||||
character maps to nothing), so `f_i`, `f_l` and `hyphen.case` read as text. A name that only
|
||||
numbers the glyph (`c251` at 97, `C1` at 233) still reads as nothing: the code's StandardEncoding
|
||||
character would be a guess, wrong wherever the font's /Encoding puts the glyph elsewhere (review
|
||||
on #3239). When the number is the glyph's own code, in decimal or hexadecimal (`C39` at 39,
|
||||
`C0032` at 32, `GE9` at 0xE9), `numbered_glyph_name_at_its_code` reads it as that code's Latin-1
|
||||
character (controls excepted), as pdftotext, PDFium and MuPDF do: name and code agree, so nothing
|
||||
is guessed (Type 1 fonts only). Covered by `text::tests::glyph_names_outside_the_glyph_list_still_read_as_text`
|
||||
and `text::tests::numbered_glyph_names_read_as_their_own_code`.
|
||||
on #3239). The one exception is patch (99): a font whose numbered names all name their own codes.
|
||||
Covered by `text::tests::glyph_names_outside_the_glyph_list_still_read_as_text`.
|
||||
|
||||
Text extraction: hayro-interpret exposes `OutlineGlyph::is_vertical` from a Type0 font’s CMap writing mode. PdfCraft follows negative glyph-space y for WMode 1 so upright vertical columns can be searched (#126).
|
||||
|
||||
|
||||
+60
-22
@@ -719,33 +719,71 @@ pub(crate) fn glyph_name_to_text(name: &str) -> Option<BfString> {
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch: the text of a glyph name outside the glyph list that only numbers its glyph
|
||||
/// (`C39`, `G27`, `MT174`: one to three ASCII letters, then decimal or hexadecimal digits) when
|
||||
/// that number is the very code the glyph is shown with: the code's Latin-1 character.
|
||||
/// The name and the code then agree on the character, so nothing is guessed. A number naming
|
||||
/// another code (`/C1` at 233, review on #3239) and a control character read as nothing.
|
||||
/// Everything from the first `.` is dropped first, as `glyph_name_to_text` drops it.
|
||||
pub(crate) fn numbered_glyph_name_at_its_code(name: &str, code: u8) -> Option<BfString> {
|
||||
/// PdfCraft patch: the numbers a glyph name that only numbers its glyph gives (`C39`, `G27`,
|
||||
/// `MT174`: one to three ASCII letters, then one to six decimal or hexadecimal digits), for
|
||||
/// every split into letters and digits, read in decimal and in hexadecimal (`GA9` is `G` with
|
||||
/// hex `A9`); nothing for any other name. Everything from the first `.` is dropped first, as
|
||||
/// `glyph_name_to_text` drops it.
|
||||
fn glyph_name_numbers(name: &str) -> impl Iterator<Item = u32> + '_ {
|
||||
let base = name.split('.').next().unwrap_or_default();
|
||||
(1..=3).flat_map(move |prefix| {
|
||||
// `from_str_radix` would also take a leading `+`: the number is digits only, and at
|
||||
// most six of them (a code is under 256, leading zeros as in `C0032`).
|
||||
let digits = base
|
||||
.get(..prefix)
|
||||
.zip(base.get(prefix..))
|
||||
.and_then(|(letters, digits)| {
|
||||
(letters.bytes().all(|b| b.is_ascii_alphabetic())
|
||||
&& (1..=6).contains(&digits.len())
|
||||
&& digits.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.then_some(digits)
|
||||
});
|
||||
digits.into_iter().flat_map(|d| {
|
||||
[10, 16]
|
||||
.into_iter()
|
||||
.filter_map(move |radix| u32::from_str_radix(d, radix).ok())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// PdfCraft patch: whether every glyph name in a simple font's encoding that only numbers its
|
||||
/// glyph (see `glyph_name_numbers`) names the very code it sits at, in decimal or hexadecimal.
|
||||
/// Names the glyph list or its `uni`/`u` forms read are not numbered names. A font whose names
|
||||
/// number something else (`/Differences [1 /C70 /C105 …]`, a glyph's order in the subset)
|
||||
/// fails, and so does one where a single name numbers another code: there a name that happens
|
||||
/// to match its code (`/MT40` at 0x40, `/C1` at 233 beside `/C70` at 70, review on #3239) is a
|
||||
/// coincidence, not evidence.
|
||||
pub(crate) fn numbered_names_name_their_codes<'a>(
|
||||
names: impl IntoIterator<Item = (u8, &'a str)>,
|
||||
) -> bool {
|
||||
names
|
||||
.into_iter()
|
||||
.filter(|(_, name)| {
|
||||
glyph_names::get(name).is_none()
|
||||
&& unicode_from_name(name).is_none()
|
||||
&& glyph_name_to_text(name).is_none()
|
||||
})
|
||||
.all(|(code, name)| {
|
||||
let mut numbers = glyph_name_numbers(name).peekable();
|
||||
numbers.peek().is_none() || numbers.any(|n| n == u32::from(code))
|
||||
})
|
||||
}
|
||||
|
||||
/// PdfCraft patch: the text of a glyph name outside the glyph list that only numbers its glyph
|
||||
/// (see `glyph_name_numbers`) when that number is the very code the glyph is shown with: the
|
||||
/// code's Latin-1 character, for codes above 127 too (`C174` reads `®`), as pdftotext, PDFium,
|
||||
/// MuPDF and Acrobat read it. The name and the code then agree, so nothing is guessed from an
|
||||
/// encoding table. A number naming another code (`/C1` at 233, review on #3239) and a control
|
||||
/// character read as nothing. Callers apply it only in a font where
|
||||
/// `numbered_names_name_their_codes` holds.
|
||||
pub(crate) fn numbered_glyph_name_at_its_code(name: &str, code: u8) -> Option<BfString> {
|
||||
let c = char::from(code);
|
||||
if c.is_control() {
|
||||
return None;
|
||||
}
|
||||
// Every split into one to three letters and the number: `GA9` is `G` with hex `A9`.
|
||||
let names_code = |prefix: usize| {
|
||||
let (Some(letters), Some(digits)) = (base.get(..prefix), base.get(prefix..)) else {
|
||||
return false;
|
||||
};
|
||||
// `from_str_radix` would also take a leading `+`: the number is digits only, and at
|
||||
// most six of them (a code is under 256, leading zeros as in `C0032`).
|
||||
letters.bytes().all(|b| b.is_ascii_alphabetic())
|
||||
&& (1..=6).contains(&digits.len())
|
||||
&& digits.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& [10, 16]
|
||||
.into_iter()
|
||||
.any(|radix| u32::from_str_radix(digits, radix).is_ok_and(|n| n == u32::from(code)))
|
||||
};
|
||||
(1..=3).any(names_code).then_some(BfString::Char(c))
|
||||
glyph_name_numbers(name)
|
||||
.any(|n| n == u32::from(code))
|
||||
.then_some(BfString::Char(c))
|
||||
}
|
||||
|
||||
pub(crate) fn unicode_from_name(name: &str) -> Option<char> {
|
||||
|
||||
+41
-15
@@ -3,7 +3,7 @@ use crate::font::standard_font::{StandardFont, StandardKind, select_standard_fon
|
||||
use crate::font::true_type::{Width, read_encoding, read_widths};
|
||||
use crate::font::{
|
||||
Encoding, FallbackFontQuery, glyph_name_to_text, glyph_name_to_unicode, normalized_glyph_name,
|
||||
numbered_glyph_name_at_its_code, read_to_unicode,
|
||||
numbered_glyph_name_at_its_code, numbered_names_name_their_codes, read_to_unicode,
|
||||
};
|
||||
use crate::{CMapResolverFn, CacheKey, FontResolverFn};
|
||||
use hayro_cmap::{BfString, CMap};
|
||||
@@ -13,10 +13,17 @@ use hayro_syntax::object::dict::keys::{FONT_DESC, FONT_FILE, FONT_FILE3};
|
||||
use kurbo::BezPath;
|
||||
use skrifa::GlyphId;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Type1Font(u128, Kind, Option<CMap>);
|
||||
pub(crate) struct Type1Font(
|
||||
u128,
|
||||
Kind,
|
||||
Option<CMap>,
|
||||
/// PdfCraft patch: whether the font's numbered glyph names all name their own codes
|
||||
/// (`numbered_names_name_their_codes`), worked out on first use.
|
||||
OnceLock<bool>,
|
||||
);
|
||||
|
||||
impl Type1Font {
|
||||
pub(crate) fn new(
|
||||
@@ -50,23 +57,29 @@ impl Type1Font {
|
||||
resolver,
|
||||
)?),
|
||||
to_unicode.clone(),
|
||||
OnceLock::new(),
|
||||
))
|
||||
};
|
||||
|
||||
let inner = if is_cff(dict) {
|
||||
if let Some(cff) = CffKind::new(dict) {
|
||||
Self(cache_key, Kind::Cff(cff), to_unicode)
|
||||
Self(cache_key, Kind::Cff(cff), to_unicode, OnceLock::new())
|
||||
} else {
|
||||
return fallback();
|
||||
}
|
||||
} else if is_type1(dict) {
|
||||
if let Some(f) = Type1Kind::new(dict) {
|
||||
Self(cache_key, Kind::Type1(f), to_unicode)
|
||||
Self(cache_key, Kind::Type1(f), to_unicode, OnceLock::new())
|
||||
} else {
|
||||
return fallback();
|
||||
}
|
||||
} else if let Some(standard) = StandardKind::new(dict, resolver) {
|
||||
Self(cache_key, Kind::Standard(standard), to_unicode)
|
||||
Self(
|
||||
cache_key,
|
||||
Kind::Standard(standard),
|
||||
to_unicode,
|
||||
OnceLock::new(),
|
||||
)
|
||||
} else {
|
||||
return fallback();
|
||||
};
|
||||
@@ -78,7 +91,7 @@ impl Type1Font {
|
||||
let dict = Dict::default();
|
||||
let standard = StandardKind::new_with_standard(&dict, font, true, resolver)?;
|
||||
|
||||
Some(Self(0, Kind::Standard(standard), None))
|
||||
Some(Self(0, Kind::Standard(standard), None, OnceLock::new()))
|
||||
}
|
||||
|
||||
pub(crate) fn map_code(&self, code: u8) -> GlyphId {
|
||||
@@ -128,17 +141,30 @@ impl Type1Font {
|
||||
}
|
||||
// PdfCraft patch (#3169, #3170): a name outside the glyph list still reads by the
|
||||
// glyph list specification's full mapping (`f_i`, `hyphen.case`). A name that only
|
||||
// numbers the glyph (`C39`, `c251`) reads as the code's character only when its number
|
||||
// is that code (`C39` at 39), as pdftotext, PDFium and MuPDF read it; a number naming
|
||||
// another code is no evidence and reads as nothing: the code's StandardEncoding
|
||||
// character would be a guess, wrong wherever the font's /Encoding puts the glyph
|
||||
// elsewhere (review on #3239).
|
||||
let name = match &self.1 {
|
||||
// numbers the glyph (`C39`, `c251`) reads as the code's Latin-1 character only when its
|
||||
// number is that code (`C39` at 39) and every numbered name in the font names its own
|
||||
// code, as pdftotext, PDFium, MuPDF and Acrobat read it. Anywhere else the number is no
|
||||
// evidence and reads as nothing: the code's StandardEncoding character would be a
|
||||
// guess, wrong wherever the font's /Encoding puts the glyph elsewhere (review on #3239).
|
||||
let name = self.code_to_ps_name(code)?;
|
||||
glyph_name_to_text(name).or_else(|| {
|
||||
let own_codes = *self.3.get_or_init(|| {
|
||||
numbered_names_name_their_codes(
|
||||
(0..=u8::MAX).filter_map(|c| Some((c, self.code_to_ps_name(c)?))),
|
||||
)
|
||||
});
|
||||
own_codes
|
||||
.then(|| numbered_glyph_name_at_its_code(name, code))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
fn code_to_ps_name(&self, code: u8) -> Option<&str> {
|
||||
match &self.1 {
|
||||
Kind::Standard(s) => s.code_to_ps_name(code),
|
||||
Kind::Cff(c) => c.code_to_ps_name(code),
|
||||
Kind::Type1(t) => t.code_to_ps_name(code),
|
||||
}?;
|
||||
glyph_name_to_text(name).or_else(|| numbered_glyph_name_at_its_code(name, code))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user