diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9af81b00e..0cfc3bb64 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -4,7 +4,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with SHA-256 hashes, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE). -## In this repository (283) +## In this repository (284) | Asset | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---| @@ -227,6 +227,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `vendor/hayro-interpret/assets/FoxitSymbol.pfb` | FoxitSymbol (standard-14 substitute font) | Foxit Software Inc. / PDFium Authors | BSD-3-Clause | https://pdfium.googlesource.com/pdfium (via hayro-interpret 0.7.0 assets/) | Renders non-embedded standard-14 fonts (vendored hayro-interpret) | | `vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc` | CGATS001Compat v2 micro ICC profile | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | CC0-1.0 | https://github.com/saucecontrol/Compact-ICC-Profiles | Default CMYK colour conversion (vendored hayro-interpret) | | `crates/fonts/src/std14_metrics.rs` | Standard-14 font advance widths and encodings (as Rust tables) | Adobe (Core14 AFM metrics, PDF specification encodings); tables generated by the PdfCraft contributors | MIT OR Apache-2.0 | ISO 32000-2 Annex D and the Adobe Core14 AFM metrics. Generated by joining the published WinAnsi, Symbol and ZapfDingbats encodings (code to glyph name) with the per-glyph advance widths, then spot-checked against the specification by hand in the tests of crates/fonts/src/std14.rs. Data only: the code that reads these tables lives in std14.rs, so that ordinary edits do not churn this file's hash. | Advance widths for the fourteen standard fonts, which a PDF may name without embedding. Non-visual data, not a typeface: the item AGENTS.md 1.1 permits, held first-party so generated appearance streams and the renderer agree. | +| `vendor/hayro-cmap/assets/cmaps.brotli` | Adobe CMap resources (predefined CJK CMaps) | Adobe | BSD-3-Clause | https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap 0.1.0 assets/) | Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1 | | `docs/brand/artcraft-logo-white.png` | ArtCraft brand: artcraft-logo-white | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. | | `docs/brand/artcraft-logo-white.svg` | ArtCraft brand: artcraft-logo-white | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. | | `docs/brand/artcraft-logo.png` | ArtCraft brand: artcraft-logo | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. | @@ -292,7 +293,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs | | `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs | -## Compiled in through dependencies (6) +## Compiled in through dependencies (5) | Crate | File | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---|---| @@ -300,7 +301,6 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `epaint_default_fonts` 0.36.2 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) | | `epaint_default_fonts` 0.36.2 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui fallback fonts (eframe feature default_fonts) | | `epaint_default_fonts` 0.36.2 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui fallback fonts (eframe feature default_fonts) | -| `hayro-cmap` 0.1.0 | `assets/cmaps.brotli` | Adobe CMap resources (predefined CJK CMaps) (non-visual data, AGENTS.md §1.1) | Adobe | BSD-3-Clause | https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap) | Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1 | | `hayro-interpret` 0.7.0 | `src/font/generated/metrics.rs` | Standard-14 font metrics and encodings (as Rust tables) (non-visual data, AGENTS.md §1.1) | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | MIT OR Apache-2.0 | ISO 32000-2 Annex D; Adobe Core14 AFM files (via vendored hayro-interpret) | Glyph widths and encodings for non-embedded standard fonts. Non-visual data, allowed by AGENTS.md §1.1 | ## Downloaded at build time (22) diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index 9b079aa62..c1f67bfd9 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -2469,14 +2469,13 @@ kind = "font" usage = "egui fallback fonts (eframe feature default_fonts)" sha256 = "f426bec371f484646d002717e2c555a95cd5145e635d83a48bbef83f3abf18ca" -[[bundled]] -crate = "hayro-cmap" -version = "0.1.0" -path = "assets/cmaps.brotli" +[[asset]] +path = "vendor/hayro-cmap/assets/cmaps.brotli" title = "Adobe CMap resources (predefined CJK CMaps)" author = "Adobe" -source = "https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap)" +source = "https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap 0.1.0 assets/)" licence = "BSD-3-Clause" +licence_file = "vendor/hayro-cmap/assets/LICENSE.txt" kind = "data" adobe_data = true usage = "Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1" diff --git a/Cargo.lock b/Cargo.lock index 755c681a5..b43147daa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2549,8 +2549,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6" dependencies = [ "brotli", "hayro-postscript", diff --git a/Cargo.toml b/Cargo.toml index 0106433df..201240314 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,6 +114,7 @@ codegen-units = 1 hayro-interpret = { path = "vendor/hayro-interpret" } hayro = { path = "vendor/hayro" } hayro-syntax = { path = "vendor/hayro-syntax" } +hayro-cmap = { path = "vendor/hayro-cmap" } hayro-jbig2 = { path = "vendor/hayro-jbig2" } lopdf = { path = "vendor/lopdf" } winit = { path = "vendor/winit" } diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs index 964eec85d..9e84cb62b 100644 --- a/crates/annot/src/lib.rs +++ b/crates/annot/src/lib.rs @@ -659,25 +659,54 @@ impl ReviewState { pub fn page_refs(doc: &Document) -> Result, AnnotError> { let root = doc.root().ok_or(AnnotError::NoPageTree)?; let pages = doc.get(root).as_dict().and_then(|d| d.reference(b"Pages")).ok_or(AnnotError::NoPageTree)?; - let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); - let mut stack = vec![pages]; - while let Some(node) = stack.pop() { - if !seen.insert(node) || seen.len() > 1_000_000 { - continue; - } - let obj = doc.get(node); - let Some(d) = obj.as_dict() else { continue }; - match d.get(b"Kids").map(|k| doc.resolve(k)) { - Some(kids) if d.name(b"Type") != Some(b"Page") => { - if let Some(a) = kids.as_array() { - stack.extend(a.iter().rev().filter_map(|k| k.as_ref())); - } + Ok(PageWalk::new(doc, pages).collect()) +} + +/// Depth-first walk over the leaf pages under `top`. It keeps one cursor per open `/Kids` array, +/// never one entry per child, so a child listed many times or shared between nodes is skipped by +/// the seen check without being queued first (`pdfcraft_model::pages` walks the same way). +/// Cycles end at the seen check and at most a million nodes are visited. +struct PageWalk<'a> { + doc: &'a Document, + seen: std::collections::HashSet, + pending: Vec<(std::sync::Arc, usize)>, +} + +impl<'a> PageWalk<'a> { + fn new(doc: &'a Document, top: ObjRef) -> Self { + let top = std::sync::Arc::new(Object::Array(vec![Object::Ref(top)])); + Self { doc, seen: Default::default(), pending: vec![(top, 0)] } + } +} + +impl Iterator for PageWalk<'_> { + type Item = ObjRef; + + fn next(&mut self) -> Option { + while let Some((kids, next)) = self.pending.last_mut() { + let Some(kid) = kids.as_array().and_then(|a| a.get(*next)) else { + self.pending.pop(); + continue; + }; + let node = kid.as_ref(); + *next += 1; + let Some(node) = node else { continue }; + if self.seen.len() >= 1_000_000 { + self.pending.clear(); + return None; + } + if !self.seen.insert(node) { + continue; + } + let obj = self.doc.get(node); + let Some(d) = obj.as_dict() else { continue }; + match d.get(b"Kids").map(|k| self.doc.resolve(k)) { + Some(kids) if d.name(b"Type") != Some(b"Page") => self.pending.push((kids, 0)), + _ => return Some(node), } - _ => out.push(node), } + None } - Ok(out) } fn page_ref(doc: &Document, page: usize) -> Result { diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs index bdff6f6a7..91617a0dc 100644 --- a/crates/annot/src/tests.rs +++ b/crates/annot/src/tests.rs @@ -1474,3 +1474,20 @@ fn lines_and_polygons_are_reshaped_by_their_points() { let s = add_annotation(&mut doc, &new(0, Shape::Rectangle { rect: [10.0, 10.0, 50.0, 50.0] }), &meta("s")).unwrap(); assert!(matches!(set_points(&mut doc, 0, s, &[[0.0, 0.0], [50.0, 50.0]], &meta("")), Err(AnnotError::Invalid(_)))); } + +#[test] +fn page_walk_skips_repeated_and_cyclic_kids_without_queueing_them() { + let mut doc = fixture(); + let root = ObjRef { num: 2, generation: 0 }; + let (first, second) = (ObjRef { num: 3, generation: 0 }, ObjRef { num: 4, generation: 0 }); + // A cycle back to the root, then both pages 128 times over. + let mut kids = vec![Object::Ref(root)]; + kids.extend([Object::Ref(first), Object::Ref(second)].into_iter().cycle().take(256)); + doc.update_dict(root, |d| d.set(b"Kids".to_vec(), Object::Array(kids))).unwrap(); + let mut walk = PageWalk::new(&doc, root); + assert_eq!(walk.next(), Some(first)); + assert!(walk.pending.len() <= 2, "repeated kids retained {} pending entries", walk.pending.len()); + assert_eq!(walk.next(), Some(second)); + assert_eq!(walk.next(), None); + assert_eq!(page_refs(&doc).unwrap(), [first, second]); +} diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rs index c7c8bca9e..eb126ffa2 100644 --- a/crates/content/src/lib.rs +++ b/crates/content/src/lib.rs @@ -219,19 +219,40 @@ fn inline_image(data: &[u8], pos: usize) -> Result<(Dict, Vec, usize), usize return Ok((dict, Vec::new(), data.len())); } // Without an `EI` after it, the image runs to the end of the stream. - return Err(end_of_image(data, at).map_or(data.len(), |(_, end)| end)); + return Err(end_of_image(data, at, b"").map_or(data.len(), |(_, end)| end)); }; dict.set(k, v); } // One whitespace byte separates ID from the data. let begin = (lx.pos + 1).min(data.len()); - let end = unfiltered_image_end(data, begin, &dict).or_else(|| end_of_image(data, begin)); + let end = unfiltered_image_end(data, begin, &dict) + .or_else(|| declared_image_end(data, begin, &dict)) + .or_else(|| image_data_end(data, begin, filter_eod(&dict))); Ok(match end { Some((end_data, end)) => (dict, data[begin..end_data].to_vec(), end), None => (dict, data[begin..].to_vec(), data.len()), }) } +/// The end-of-data marker (`>` for ASCIIHex, `~>` for ASCII85) of the outer stream filter, if any. +fn filter_eod(dict: &Dict) -> &'static [u8] { + for key in [b"Filter".as_slice(), b"F"] { + if let Some(filter) = dict.get(key) { + let name = match filter { + Object::Name(name) => Some(name.as_slice()), + Object::Array(filters) => filters.first().and_then(Object::as_name), + _ => None, + }; + return match name { + Some(b"ASCIIHexDecode" | b"AHx") => b">", + Some(b"ASCII85Decode" | b"A85") => b"~>", + _ => b"", + }; + } + } + b"" +} + /// An unfiltered image's samples determine its length, including byte padding per row. /// Binary samples may themselves contain whitespace + `EI` + whitespace, so use the known /// length when the actual terminator follows it. Unknown or damaged layouts keep the heuristic. @@ -293,23 +314,60 @@ fn unfiltered_image_end(data: &[u8], begin: usize, dict: &Dict) -> Option<(usize let row = width.checked_mul(components)?.checked_mul(bits)?.div_ceil(8); let end_data = begin.checked_add(row.checked_mul(height)?)?; let after = data.get(end_data..)?; - if !after.first().is_some_and(|b| is_ws(*b)) { + let separator = after.iter().position(|b| !is_ws(*b))?; + if separator == 0 && data.get(end_data.checked_sub(1)?).is_some_and(|b| is_ws(*b)) { return None; } - let separator = after.iter().position(|b| !is_ws(*b))?; let ei = end_data.checked_add(separator)?; let end = ei.checked_add(2)?; if data.get(ei..end) == Some(b"EI") && data.get(end).is_none_or(|b| is_ws(*b) || is_delim(*b)) { Some((end_data, end)) } else { None } } +/// The length declared by `/L` (or `/Length`, ISO 32000-2 §8.9.7), used when `EI` follows the +/// declared bytes after optional whitespace. A declared length without that `EI` is ignored. +fn declared_image_end(data: &[u8], begin: usize, dict: &Dict) -> Option<(usize, usize)> { + let length = dict.get(b"L").or_else(|| dict.get(b"Length"))?.as_int()?; + let end_data = begin.checked_add(usize::try_from(length).ok()?)?; + let after = data.get(end_data..)?; + let ei = end_data.checked_add(after.iter().position(|b| !is_ws(*b))?)?; + let end = ei.checked_add(2)?; + if data.get(ei..end) == Some(b"EI") && data.get(end).is_none_or(|b| is_ws(*b) || is_delim(*b)) { Some((end_data, end)) } else { None } +} + +/// Where inline image data of unknown length ends. A candidate `EI` followed by binary bytes before +/// the next `EI` lies inside the (compressed) data, unless another inline image starts first. +fn image_data_end(data: &[u8], begin: usize, eod: &[u8]) -> Option<(usize, usize)> { + let mut candidate = end_of_image(data, begin, eod)?; + loop { + let (end_data, end) = candidate; + let Some(next) = end_of_image(data, end, eod) else { + return Some(candidate); + }; + let between = data.get(end..next.0).unwrap_or_default(); + if !between.iter().any(|b| !b.is_ascii()) || starts_inline_image(between) { + return Some((end_data, end)); + } + candidate = next; + } +} + +/// Whether `bytes` hold a whitespace-delimited `BI` operator. +fn starts_inline_image(bytes: &[u8]) -> bool { + bytes + .windows(2) + .enumerate() + .any(|(i, pair)| pair == b"BI" && (i == 0 || is_ws(bytes[i - 1])) && bytes.get(i + 2).is_none_or(|b| is_ws(*b) || is_delim(*b))) +} + /// Where inline image data starting at `begin` ends: (end of the data, position after `EI`). The -/// data ends at whitespace + `EI` + (whitespace, a delimiter or the end). -fn end_of_image(data: &[u8], begin: usize) -> Option<(usize, usize)> { +/// data ends at whitespace (or `eod`: `>` for ASCIIHex, `~>` for ASCII85) + `EI` + (whitespace, +/// a delimiter or the end). +fn end_of_image(data: &[u8], begin: usize, eod: &[u8]) -> Option<(usize, usize)> { let mut i = begin; while i + 2 <= data.len() { if data[i] == b'E' && data.get(i + 1) == Some(&b'I') - && (i == begin || is_ws(data[i - 1])) + && (i == begin || is_ws(data[i - 1]) || (!eod.is_empty() && data[begin..i].ends_with(eod))) && data.get(i + 2).is_none_or(|b| is_ws(*b) || is_delim(*b)) { let end_data = if i > begin && is_ws(data[i - 1]) { i - 1 } else { i }; diff --git a/crates/content/src/tests.rs b/crates/content/src/tests.rs index 1119bdaf9..094a0665d 100644 --- a/crates/content/src/tests.rs +++ b/crates/content/src/tests.rs @@ -151,6 +151,32 @@ fn filtered_unknown_and_damaged_inline_images_keep_the_existing_fallback() { } } +/// A zlib stream (one stored block) for 64 DeviceGray samples whose bytes hold " EI\n" at offset 41, +/// the way a stored deflate block copies incompressible samples verbatim (#3579). +const FLATE_WITH_EI: &str = "789c014000bfffed746159d50788f7ea604984cd08e00b4c8983207f56fe82c77ef8dfb8b9a3a586382045490a3120\ + 31206c2025630aaa4353e6813e233b96539c18bc3a2c5009e9d51b81"; + +#[test] +fn flate_inline_image_is_not_cut_at_an_ei_inside_its_compressed_bytes() { + let flate: Vec = (0..FLATE_WITH_EI.len()).step_by(2).map(|i| u8::from_str_radix(&FLATE_WITH_EI[i..i + 2], 16).unwrap()).collect(); + assert_eq!(flate.len(), 75); + assert_eq!(&flate[41..45], b" EI\n"); + for parameters in [b"/W 64 /H 1 /BPC 8 /CS /G /F /Fl".as_slice(), b"/W 64 /H 1 /BPC 8 /CS /G /F /Fl /L 75"] { + let mut src = b"q 200 0 0 200 100 300 cm BI ".to_vec(); + src.extend_from_slice(parameters); + src.extend_from_slice(b" ID "); + src.extend_from_slice(&flate); + src.extend_from_slice(b"\nEI Q BT /F1 24 Tf 72 200 Td (AFTER) Tj ET"); + let parsed = parse(&src); + let label = String::from_utf8_lossy(parameters); + assert_eq!(parsed.ops[2].inline.as_ref().unwrap().1.len(), 75, "{label}"); + let names: Vec<&[u8]> = parsed.ops.iter().map(|o| o.op.as_slice()).collect(); + assert_eq!(names, [&b"q"[..], b"cm", b"BI", b"Q", b"BT", b"Tf", b"Td", b"Tj", b"ET"], "{label}"); + assert_eq!(parsed.skipped, 0, "{label}"); + assert_eq!(parse(&serialize_ops(&parsed.ops)).ops[2].inline, parsed.ops[2].inline, "{label}"); + } +} + fn inline_pdf(content: &[u8], object_streams: bool) -> Vec { use pdfcraft_cos::{Document, SaveOptions, Stream, write_full}; @@ -388,3 +414,48 @@ fn piece_lookup_preserves_exact_boundary_and_empty_piece_mapping() { assert_eq!(empty.piece_of(0), 0); assert_eq!(empty.piece_of(usize::MAX), 0); } + +#[test] +fn inline_image_terminator_without_preceding_whitespace() { + let cases: &[(&[u8], &[u8])] = &[ + (b"BI /W 4 /H 1 /BPC 8 /CS /G /F /AHx ID 2060A0E0>EI Q BT /F1 18 Tf (After) Tj ET", b"2060A0E0>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G /Filter /ASCIIHexDecode ID 2060A0E0>EI Q BT /F1 18 Tf (After) Tj ET", b"2060A0E0>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G /F [/AHx] ID 2060A0E0>EI Q BT /F1 18 Tf (After) Tj ET", b"2060A0E0>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G /F [/AHx /RL] ID 2060A0E0>EI Q BT /F1 18 Tf (After) Tj ET", b"2060A0E0>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G /F /A85 ID 5s,^g~>EI Q BT /F1 18 Tf (After) Tj ET", b"5s,^g~>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G /Filter /ASCII85Decode ID 5s,^g~>EI Q BT /F1 18 Tf (After) Tj ET", b"5s,^g~>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G /F [/A85 /RL] ID 5s,^g~>EI Q BT /F1 18 Tf (After) Tj ET", b"5s,^g~>"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G ID ab()EI Q BT /F1 18 Tf (After) Tj ET", b"ab()"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G ID ab[]EI Q BT /F1 18 Tf (After) Tj ET", b"ab[]"), + (b"BI /W 4 /H 1 /BPC 8 /CS /G ID \x20\x60\xa0\xe0EI Q BT /F1 18 Tf (After) Tj ET", b"\x20\x60\xa0\xe0"), + ]; + + for (src, expected_data) in cases { + let p = parse(src); + assert_eq!(p.skipped, 0, "stream should have 0 skipped bytes: {}", String::from_utf8_lossy(src)); + let names: Vec<&[u8]> = p.ops.iter().map(|o| o.op.as_slice()).collect(); + assert_eq!( + names, + [&b"BI"[..], b"Q", b"BT", b"Tf", b"Tj", b"ET"], + "operators after inline image must be preserved: {}", + String::from_utf8_lossy(src) + ); + let (_, img) = p.ops[0].inline.as_ref().unwrap(); + assert_eq!(img, expected_data, "inline image data must match: {}", String::from_utf8_lossy(src)); + } +} + +#[test] +fn ascii85_inline_image_does_not_terminate_at_gt_ei_inside_payload() { + for src in [ + b"BI /W 4 /H 1 /BPC 8 /CS /G /F /A85 ID !!!!>EI !!~>\nEI Q BT /F1 18 Tf (After) Tj ET".as_slice(), + b"BI /W 4 /H 1 /BPC 8 /CS /G /F [/A85 /AHx] ID !!!!>EI !!~>\nEI Q BT /F1 18 Tf (After) Tj ET".as_slice(), + ] { + let p = parse(src); + assert_eq!(p.skipped, 0); + let names: Vec<&[u8]> = p.ops.iter().map(|o| o.op.as_slice()).collect(); + assert_eq!(names, [&b"BI"[..], b"Q", b"BT", b"Tf", b"Tj", b"ET"]); + let (_, img) = p.ops[0].inline.as_ref().unwrap(); + assert_eq!(img, b"!!!!>EI !!~>"); + } +} diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rs index 639edf582..ae00234d0 100644 --- a/crates/cos/src/document.rs +++ b/crates/cos/src/document.rs @@ -268,6 +268,20 @@ impl XrefIndex { } } + /// Every entry, newest section first, as the materialized reader keeps them. + fn to_map(&self, file: &[u8]) -> BTreeMap { + match self { + Self::Materialized(entries) => entries.as_ref().clone(), + Self::Compact { revisions, .. } => { + let mut numbers = Vec::new(); + for revision in revisions { + revision.extend_numbers(&mut numbers); + } + numbers.into_iter().filter_map(|num| self.lookup(num, file).map(|entry| (num, entry))).collect() + } + } + } + fn max_num(&self) -> u32 { match self { Self::Compact { max_num, .. } => *max_num, @@ -317,11 +331,22 @@ pub struct Revision { #[derive(Clone, Debug)] struct ObjStm { - /// (object number, byte offset within `data`). - index: Vec<(u32, usize)>, + /// One slot per member in stream order, since cross-reference entries name a member by its + /// position: (object number, byte offset within `data`), or `None` for a member whose number + /// or offset is unusable ([`objstm_member`]). + index: Vec>, data: Arc>, } +/// Where member `num` of an object stream starts: its `offset` past `/First` (`first`), when the +/// number is an object number and the start lies inside the decoded `len` bytes. Checked on every +/// target, so a 32-bit build neither truncates nor wraps a large `/First` or offset (#1815). +fn objstm_member(num: i64, offset: i64, first: Option, len: usize) -> Option<(u32, usize)> { + let num = u32::try_from(num).ok()?; + let start = first?.checked_add(usize::try_from(offset).ok()?)?; + (start < len).then_some((num, start)) +} + /// Where an overlay slot came from. #[derive(Clone, Debug, PartialEq)] enum Slot { @@ -386,6 +411,10 @@ pub struct Document { revisions: Arc>, /// See [`Self::xref_oddities`]. xref_oddities: Arc>, + /// Where the file's object headers are, as (offset, generation) of the last header of each + /// number. Filled only when the cross-reference data proved inconsistent; see + /// `fill_xref_gaps`. + located: Arc>, repair_log: Arc>, cache: Arc>>>, objstms: Arc>>>, @@ -435,7 +464,7 @@ impl ObjectReader { let bytes = streams.values().fold(0usize, |bytes, stream| { bytes .saturating_add(stream.data.capacity()) - .saturating_add(stream.index.capacity().saturating_mul(std::mem::size_of::<(u32, usize)>())) + .saturating_add(stream.index.capacity().saturating_mul(std::mem::size_of::>())) }); if bytes > Self::STREAM_BYTES || streams.len() >= Self::OBJECTS { // Retain one oversized active stream so its next object does not require @@ -508,6 +537,7 @@ impl Document { trailer: Dict::new(), revisions: Arc::new(Vec::new()), xref_oddities: Arc::default(), + located: Arc::default(), repair_log: Arc::new(Vec::new()), cache: Arc::default(), objstms: Arc::default(), @@ -589,6 +619,7 @@ impl Document { trailer: Dict::new(), revisions: Arc::new(Vec::new()), xref_oddities: Arc::default(), + located: Arc::default(), repair_log: Arc::new(Vec::new()), cache: Arc::default(), objstms: Arc::default(), @@ -616,6 +647,7 @@ impl Document { doc.trailer = trailer; doc.revisions = Arc::new(revisions); doc.xref_oddities = Arc::new(oddities); + doc.fill_xref_gaps(&mut log); // Authenticate before checking the catalog: it may sit in an encrypted object // stream, which reads as garbage until the key is known. if let Some(enc) = doc.trailer.get(b"Encrypt").cloned() { @@ -950,9 +982,9 @@ impl Document { // Offsets may count from a header that does not start the file. usize::try_from(offset).is_ok_and(|off| at(off) || (self.header_offset != 0 && at(off.saturating_add(self.header_offset)))) } - Some(XrefEntry::InStream { stream, index }) => { - self.objstm(stream).is_ok_and(|stm| usize::try_from(index).ok().and_then(|i| stm.index.get(i)).is_some_and(|(n, _)| *n == num)) - } + Some(XrefEntry::InStream { stream, index }) => self + .objstm(stream) + .is_ok_and(|stm| usize::try_from(index).ok().and_then(|i| stm.index.get(i)).is_some_and(|m| m.is_some_and(|(n, _)| n == num))), } } @@ -1065,7 +1097,7 @@ impl Document { let bytes = streams.values().fold(0usize, |bytes, stream| { bytes .saturating_add(stream.data.capacity()) - .saturating_add(stream.index.capacity().saturating_mul(std::mem::size_of::<(u32, usize)>())) + .saturating_add(stream.index.capacity().saturating_mul(std::mem::size_of::>())) }); bytes > Self::EDITOR_OBJSTM_BYTES || streams.len() > Self::EDITOR_OBJSTM_OBJECTS }; @@ -1151,19 +1183,15 @@ impl Document { // Offsets relative to a shifted header, or simply wrong: try both fixes. at(off) .or_else(|| if self.header_offset == 0 { None } else { at(off.saturating_add(self.header_offset)) }) + .or_else(|| self.located.get(&num).and_then(|(o, _)| usize::try_from(*o).ok()).and_then(at)) .or_else(|| self.scan_for(num).map(|(id, o)| self.decrypted(id, o))) .ok_or(CosError::MissingObject(num)) } Some(XrefEntry::InStream { stream, index }) => { let stm = self.objstm(stream)?; - let (n, off) = stm - .index - .get(index as usize) - .copied() - .or_else(|| stm.index.iter().find(|(n, _)| *n == num).copied()) - .ok_or(CosError::MissingObject(num))?; - let off = - if n == num { off } else { stm.index.iter().find(|(n, _)| *n == num).map(|(_, o)| *o).ok_or(CosError::MissingObject(num))? }; + // The member at the entry's position, else wherever the stream lists `num`. + let at = usize::try_from(index).ok().and_then(|i| stm.index.get(i)).copied().flatten().filter(|(n, _)| *n == num); + let (_, off) = at.or_else(|| stm.index.iter().flatten().find(|(n, _)| *n == num).copied()).ok_or(CosError::MissingObject(num))?; Lexer::new(&stm.data, off).object() } } @@ -1187,13 +1215,13 @@ impl Document { }; let Object::Stream(s) = &*loaded else { return Err(CosError::MissingObject(num)) }; let n = s.dict.int(b"N").unwrap_or(0).clamp(0, 1_000_000) as usize; - let first = s.dict.int(b"First").unwrap_or(0).max(0) as usize; + let first = usize::try_from(s.dict.int(b"First").unwrap_or(0).max(0)).ok(); let data = s.decoded_within(self.stream_limit)?; let mut lx = Lexer::new(&data, 0); let mut index = Vec::with_capacity(n); for _ in 0..n { let (Some(Object::Int(onum)), Some(Object::Int(off))) = (lx.object().ok(), lx.object().ok()) else { break }; - index.push((onum.max(0) as u32, first + off.max(0) as usize)); + index.push(objstm_member(onum, off, first, data.len())); } let stm = Arc::new(ObjStm { index, data: Arc::new(data) }); // Same bound as the object cache: decoded object streams can be megabytes each. @@ -1476,7 +1504,7 @@ impl Document { } } sections.push(XrefRevisionSection { primary, hybrid }); - next = sect_trailer.int(b"Prev").filter(|p| *p >= 0).map(|p| p as u64); + next = prev_offset(data, §_trailer, off, |num| sections.iter().find_map(|s| s.lookup(num, data)), log); if trailer.is_none() { trailer = Some(sect_trailer); } @@ -1526,7 +1554,7 @@ impl Document { if !valid_xref_range(start, count) || count > 10_000_000 { return Err(CosError::Syntax { offset: lx.pos, detail: "invalid xref object range".into() }); } - let shifted = subsection_start(data, lx.pos, start, count); + let shifted = subsection_start(data, self.header_offset, lx.pos, start, count); renumbered |= shifted != start; let start = shifted; let Some(next_rows) = usize::try_from(count).ok().and_then(|count| row_count.checked_add(count)) else { return Ok(None) }; @@ -1764,7 +1792,7 @@ impl Document { for (num, e) in sect { entries.entry(num).or_insert(e); } - next = sect_trailer.int(b"Prev").filter(|p| *p >= 0).map(|p| p as u64); + next = prev_offset(data, §_trailer, off, |num| entries.get(&num).copied(), log); if trailer.is_none() { trailer = Some(sect_trailer); } @@ -1802,7 +1830,7 @@ impl Document { if !valid_xref_range(start, count) || count > 10_000_000 { return Err(CosError::Syntax { offset: lx.pos, detail: "invalid xref object range".into() }); } - let shifted = subsection_start(data, lx.pos, start, count); + let shifted = subsection_start(data, self.header_offset, lx.pos, start, count); if shifted != start { log.push(format!("xref subsection at {off} is numbered from 1 but begins with object 0's entry; read from 0")); } @@ -1906,32 +1934,72 @@ impl Document { Ok((s.dict.clone(), true)) } + /// Cross-reference data that leaves out objects the file contains: a subsection numbered one + /// too low (object 0 in use, the last object without an entry), or an in-use entry at offset 0 + /// that nothing else replaces. (A number no section lists is not evidence: it is a null + /// object, §7.3.10, and valid files have them below an oversized `/Size`.) Viewers rebuild + /// the table and show these objects; reading them as null would drop them from every copy. + /// When one of those shows, the file is scanned once for object headers, and wrong offsets + /// are looked up there (`load`). Only the numbers the damage leaves out take the last + /// header's location: one whose entry was set aside, or the last object of a subsection + /// numbered one too low. Any other unlisted number stays null, and existing + /// entries are never replaced: an object freed by an update stays freed. + fn fill_xref_gaps(&mut self, log: &mut Vec) { + let entries = &self.entries; + let shifted = matches!(entries.lookup(0, &self.data), Some(XrefEntry::InFile { .. })); + let set_aside = self.xref_oddities.iter().any(|(_, num)| entries.lookup(*num, &self.data).is_none()); + if !(shifted || set_aside) { + return; + } + let mut located = BTreeMap::new(); + for (num, offset, generation, _) in object_headers(&self.data) { + located.insert(num, (offset, generation)); + } + let mut filled = entries.to_map(&self.data); + // A subsection `0 N` whose rows are those of objects 1 to N leaves out object N, whatever + // newer sections say about its neighbours. + let past_shift: HashSet = if shifted { + self.revisions + .iter() + .filter(|r| !r.is_stream) + .filter_map(|r| usize::try_from(r.xref_offset).ok().map(|o| if r.header_relative { o.saturating_add(self.header_offset) } else { o })) + .filter_map(|at| shifted_subsection_end(&self.data, at)) + .collect() + } else { + HashSet::new() + }; + let odd: HashSet = self.xref_oddities.iter().map(|(_, n)| *n).collect(); + let mut found = 0usize; + for (&num, &(offset, generation)) in &located { + let left_out = past_shift.contains(&num) || odd.contains(&num); + if num != 0 && !filled.contains_key(&num) && left_out { + filled.insert(num, XrefEntry::InFile { offset, generation }); + found += 1; + } + } + if found > 0 { + log.push(format!("the cross-reference data leaves out {found} objects the file contains; located them by their object headers")); + self.entries = Arc::new(XrefIndex::Materialized(Arc::new(filled))); + } + self.located = Arc::new(located); + } + /// Rebuild the cross-reference index by scanning for `N G obj` headers (§7.5.4 recovery). fn reconstruct(&mut self, log: &mut Vec) -> Result<(), CosError> { let data = self.data.clone(); let mut entries: BTreeMap = BTreeMap::new(); - let mut i = 0; let mut objstms = Vec::new(); - while i < data.len() { - // Object headers start at a line start (or after whitespace). - let at_start = i == 0 || is_whitespace(data[i - 1]) || data[i - 1] == b'>'; - if at_start && data[i].is_ascii_digit() { - let mut lx = Lexer::new(&data, i); - let n = lx.token(); - lx.skip_ws(); - let g = lx.token(); - if !n.is_empty() && !g.is_empty() && n.iter().all(u8::is_ascii_digit) && g.iter().all(u8::is_ascii_digit) && lx.eat_keyword(b"obj") { - let num = std::str::from_utf8(n).ok().and_then(|s| s.parse::().ok()); - let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::().ok()).unwrap_or(0); - if let Some(num) = num { - entries.insert(num, XrefEntry::InFile { offset: i as u64, generation }); - objstms.push(num); - } - i = lx.pos; - continue; - } + // Offsets of objects that may be cross-reference streams: their dictionaries are the + // trailers of files that have no `trailer` keyword (§7.5.8). + let mut xref_streams = Vec::new(); + for (num, offset, generation, body) in object_headers(&data) { + entries.insert(num, XrefEntry::InFile { offset, generation }); + objstms.push(num); + if find(&data, b"/XRef", body, body.saturating_add(1024)).is_some() + && let Ok(at) = usize::try_from(offset) + { + xref_streams.push(at); } - i += 1; } if entries.is_empty() { return Err(CosError::Syntax { offset: 0, detail: "no objects found".into() }); @@ -1945,28 +2013,54 @@ impl Document { && s.dict.name(b"Type") == Some(b"ObjStm") && let Ok(stm) = self.objstm(num) { - for (idx, (inner, _)) in stm.index.iter().enumerate() { - entries.entry(*inner).or_insert(XrefEntry::InStream { stream: num, index: idx as u32 }); + for (idx, member) in stm.index.iter().enumerate() { + if let Some((inner, _)) = member { + entries.entry(*inner).or_insert(XrefEntry::InStream { stream: num, index: idx as u32 }); + } } } } let object_count = entries.len(); self.entries = Arc::new(XrefIndex::Materialized(Arc::new(entries))); self.cache.lock().map_err(|_| CosError::Poisoned)?.clear(); - // Trailer: the last `trailer` dictionary with a usable /Root, else the catalog itself. - let mut trailer = None; + // Trailer: the last `trailer` dictionary or cross-reference stream dictionary with a + // usable /Root (last in the file, whichever kind), else the catalog itself. One whose + // /Root is a catalog (as `root_is_catalog` judges it) beats one whose /Root is another + // dictionary, such as /Info, wherever it is; an FDF's /Root (no /Type, no /Pages) still + // counts when nothing better is there. + // A file whose only trailers are cross-reference streams (and whose `startxref` is gone + // or points nowhere) keeps its /Info, /ID and /Encrypt this way. + let rank = |at: usize, d: &Dict| { + let root = self.try_get(d.reference(b"Root")?.num).ok()?; + let Object::Dict(c) = &*root else { return None }; + Some((c.name(b"Type") == Some(b"Catalog") || c.contains(b"Pages"), at)) + }; + let mut trailer: Option<((bool, usize), Dict)> = None; let mut from = 0; while let Some(p) = find(&data, b"trailer", from, data.len()) { from = p + 7; let mut lx = Lexer::new(&data, from); if let Ok(Object::Dict(d)) = lx.object() - && d.reference(b"Root").is_some_and(|r| matches!(self.try_get(r.num).as_deref(), Ok(Object::Dict(_)))) + && let Some(r) = rank(p, &d) + && trailer.as_ref().is_none_or(|(best, _)| r > *best) { - trailer = Some(d); + trailer = Some((r, d)); + } + } + for at in xref_streams { + if trailer.as_ref().is_some_and(|((catalog, p), _)| *catalog && *p > at) { + continue; + } + if let Ok((_, Object::Stream(s))) = parse_indirect_shared(&data, at, &|_| None) + && s.dict.name(b"Type") == Some(b"XRef") + && let Some(r) = rank(at, &s.dict) + && trailer.as_ref().is_none_or(|(best, _)| r > *best) + { + trailer = Some((r, s.dict)); } } let trailer = match trailer { - Some(t) => t, + Some((_, t)) => t, None => { let catalog = self .entries @@ -1980,7 +2074,9 @@ impl Document { } }; let mut trailer = trailer; - for k in [&b"Prev"[..], b"XRefStm"] { + // What a cross-reference stream's dictionary carries for itself goes, as the chain + // readers drop it: a save writes its own. + for k in [&b"Prev"[..], b"XRefStm", b"Type", b"W", b"Index", b"Filter", b"DecodeParms", b"Length"] { trailer.remove(k); } self.trailer = trailer; @@ -1990,6 +2086,96 @@ impl Document { } } +/// For a classic table at `at` whose first subsection is `0 N` and opens with an in-use row +/// (the rows of objects 1 to N), the number N its rows really end at. +fn shifted_subsection_end(data: &[u8], at: usize) -> Option { + let mut lx = Lexer::new(data, at); + if !lx.eat_keyword(b"xref") { + return None; + } + let (Ok(Object::Int(0)), Ok(Object::Int(count))) = (lx.object(), lx.object()) else { return None }; + lx.skip_ws(); + let offset = std::str::from_utf8(lx.token()).ok().and_then(|s| s.parse::().ok()); + lx.skip_ws(); + lx.token(); + lx.skip_ws(); + match (offset, lx.token()) { + (Some(offset), b"n") if offset != 0 => u32::try_from(count).ok().filter(|n| *n > 0), + _ => None, + } +} + +/// Every `N G obj` header in `data`, in file order, as (number, offset, generation, position +/// after `obj`). +fn object_headers(data: &[u8]) -> Vec<(u32, u64, u16, usize)> { + let mut headers = Vec::new(); + let mut i = 0; + while i < data.len() { + // Object headers start at a line start (or after whitespace). + let at_start = i == 0 || is_whitespace(data[i - 1]) || data[i - 1] == b'>'; + if at_start && data[i].is_ascii_digit() { + let mut lx = Lexer::new(data, i); + let n = lx.token(); + lx.skip_ws(); + let g = lx.token(); + if !n.is_empty() && !g.is_empty() && n.iter().all(u8::is_ascii_digit) && g.iter().all(u8::is_ascii_digit) && lx.eat_keyword(b"obj") { + let num = std::str::from_utf8(n).ok().and_then(|s| s.parse::().ok()); + let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::().ok()).unwrap_or(0); + if let Some(num) = num { + headers.push((num, i as u64, generation, lx.pos)); + } + i = lx.pos; + continue; + } + } + i += 1; + } + headers +} + +/// The offset of the section before the one whose trailer this is (`/Prev`), if any. Some writers +/// give it as a reference, `N 0 R`. When the sections read so far (`lookup`) place that object +/// and it holds an offset (iText's `indirectPrev.pdf`), that is the offset; otherwise, as the +/// tiff2pdf files in JHOVE's PDF-HUL-157 cases need, the sections before are at N. Either way the +/// reference is noted. Any other value that is not an offset is noted and ends the chain. +fn prev_offset(data: &[u8], trailer: &Dict, off: u64, lookup: impl Fn(u32) -> Option, log: &mut Vec) -> Option { + match trailer.get(b"Prev") { + Some(Object::Int(p)) if *p >= 0 => Some(*p as u64), + Some(Object::Ref(r)) => { + let held = match lookup(r.num) { + Some(XrefEntry::InFile { offset, generation }) if generation == r.generation => { + usize::try_from(offset).ok().and_then(|at| parse_indirect(data, at, &|_| None).ok()).and_then(|(at, value)| match value { + Object::Int(p) if at == *r && p >= 0 => Some(p as u64), + _ => None, + }) + } + _ => None, + }; + match held { + Some(p) => { + log.push(format!( + "the trailer at {off} gives /Prev as the reference {} {} R; reading the offset {p} it holds", + r.num, r.generation + )); + Some(p) + } + None => { + log.push(format!( + "the trailer at {off} gives /Prev as the reference {} {} R; reading it as offset {}", + r.num, r.generation, r.num + )); + Some(u64::from(r.num)) + } + } + } + Some(_) => { + log.push(format!("the trailer at {off} has a /Prev that is not an offset; the sections before it are unreachable")); + None + } + None => None, + } +} + pub(crate) fn find(hay: &[u8], needle: &[u8], from: usize, to: usize) -> Option { let to = to.min(hay.len()); if from >= to || needle.is_empty() || to - from < needle.len() { @@ -2020,9 +2206,10 @@ fn generated_id(seed: &[u8; 32]) -> Vec { /// The object number a classic xref subsection really starts at. A common producer bug heads the /// table `1 n` and then writes object 0's free entry (`0000000000 65535 f`) as its first row, so /// every row would be read one number too high and object 1 as free. Such a subsection is read -/// from 0 when its second row, read that way, locates an object that is indeed numbered 1. `rows` -/// is the position just after the subsection header. -fn subsection_start(data: &[u8], rows: usize, start: i64, count: i64) -> i64 { +/// from 0 when its second row, read that way, locates an object that is indeed numbered 1, at +/// that offset or, as `load` reads offsets, relative to a header shifted by `header_offset`. +/// `rows` is the position just after the subsection header. +fn subsection_start(data: &[u8], header_offset: usize, rows: usize, start: i64, count: i64) -> i64 { if start != 1 || count < 2 { return start; } @@ -2037,12 +2224,15 @@ fn subsection_start(data: &[u8], rows: usize, start: i64, count: i64) -> i64 { }; let (Some(0), Some(65535), true) = row() else { return start }; let (Some(second), _, false) = row() else { return start }; - let Some(at) = usize::try_from(second).ok().filter(|at| *at < data.len()) else { return start }; - let mut obj = Lexer::new(data, at); - match (obj.object(), obj.object()) { - (Ok(Object::Int(1)), Ok(Object::Int(_))) if obj.eat_keyword(b"obj") => 0, - _ => start, - } + let object_one = |at: usize| { + if at >= data.len() { + return false; + } + let mut obj = Lexer::new(data, at); + matches!((obj.object(), obj.object()), (Ok(Object::Int(1)), Ok(Object::Int(_)))) && obj.eat_keyword(b"obj") + }; + let Ok(second) = usize::try_from(second) else { return start }; + if object_one(second) || (header_offset != 0 && object_one(second.saturating_add(header_offset))) { 0 } else { start } } /// Object numbers must fit the representation used by references and the xref map. @@ -2297,6 +2487,221 @@ endobj assert!(!doc.repair_log().iter().any(|l| l.contains("numbered from 1"))); } + /// A one-page scan: the page draws image 5 with content stream 4. + fn scanned_page() -> Vec { + build( + &[ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>", + "<< /Length 21 >>\nstream\n10 0 0 10 0 0 cm /Im0 Do\nendstream", + "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\nA\nendstream", + ], + "/Root 1 0 R", + ) + } + + /// `bytes` with its cross-reference table replaced by `table` (the lines after `xref`). + fn with_table(bytes: &[u8], table: &[String], size: usize) -> Vec { + let text = String::from_utf8_lossy(bytes).into_owned(); + let at = text.rfind("\nxref\n").unwrap() + 1; + let mut out = bytes[..at].to_vec(); + out.extend_from_slice(format!("xref\n{}\ntrailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{at}\n%%EOF\n", table.join("\n")).as_bytes()); + out + } + + /// The table's entry lines, object 0 first. + fn table_entries(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes).into_owned(); + let at = text.rfind("\nxref\n").unwrap() + 1; + text[at..].lines().skip(2).take_while(|l| !l.starts_with("trailer")).map(str::to_string).collect() + } + + /// The classic off-by-one: the subsection says it starts at 0 but lists objects 1 to 5, so + /// the last object has no entry. Viewers rebuild the table and show the page; a reader that + /// took the missing entry for a null object dropped the image when pages were copied (#1628). + #[test] + fn an_off_by_one_xref_subsection_still_finds_the_last_object() { + let base = scanned_page(); + let entries = table_entries(&base); + let mut table = vec!["0 5".to_string()]; + table.extend(entries[1..6].iter().cloned()); + let doc = Document::open(Arc::new(with_table(&base, &table, 5))).unwrap(); + let image = doc.get(ObjRef::new(5, 0)); + assert_eq!(image.as_dict().and_then(|d| d.name(b"Subtype")), Some(&b"Image"[..]), "{image:?}"); + assert!(matches!(&*image, Object::Stream(_))); + assert!(matches!(&*doc.get(ObjRef::new(4, 0)), Object::Stream(s) if &s.raw[..] == b"10 0 0 10 0 0 cm /Im0 Do")); + assert!(doc.repair_log().iter().any(|l| l.contains("object headers")), "{:?}", doc.repair_log()); + } + + /// An "in use" entry at offset 0 says nothing about where the object is: the object is + /// found by its header, and the repair is recorded. + #[test] + fn an_object_listed_at_offset_zero_is_found_by_its_header() { + let base = scanned_page(); + for num in [4usize, 5] { + let mut table = vec!["0 6".to_string()]; + table.extend(table_entries(&base)); + table[num + 1] = "0000000000 00000 n ".into(); + let doc = Document::open(Arc::new(with_table(&base, &table, 6))).unwrap(); + assert!(matches!(&*doc.get(ObjRef::new(num as u32, 0)), Object::Stream(_)), "object {num}"); + assert!(doc.repair_log().iter().any(|l| l.contains("object headers")), "object {num}: {:?}", doc.repair_log()); + } + } + + /// A valid table that simply does not list every number below `/Size` is not repaired: an + /// unlisted number is a null object (§7.3.10), even when an old body with that number is + /// still in the file. + #[test] + fn a_consistent_table_with_unlisted_numbers_is_taken_as_it_is() { + let base = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "(three)"], "/Root 1 0 R"); + let at = String::from_utf8_lossy(&base).rfind("\nxref\n").unwrap() + 1; + let mut bytes = base[..at].to_vec(); + bytes.extend_from_slice(b"4 0 obj\n(stale)\nendobj\n"); + let mut table = vec!["0 4".to_string()]; + table.extend(table_entries(&base)); + let doc = Document::open(Arc::new(with_table(&[&bytes[..], &base[at..]].concat(), &table, 6))).unwrap(); + assert!(doc.repair_log().is_empty(), "{:?}", doc.repair_log()); + assert_eq!(*doc.get(ObjRef::new(4, 0)), Object::Null); + assert!(matches!(&*doc.get(ObjRef::new(3, 0)), Object::String(_))); + } + + /// Filling the gaps of a damaged table never brings back an object that an incremental + /// update freed: its body is still in the file, but the newer section says it is gone. + #[test] + fn an_object_freed_by_an_update_stays_freed_when_the_table_is_repaired() { + let base = scanned_page(); + // The original table lists the content stream at offset 0, so the gaps get filled. + let mut table = vec!["0 6".to_string()]; + table.extend(table_entries(&base)); + table[5] = "0000000000 00000 n ".into(); + let mut bytes = with_table(&base, &table, 6); + let prev = String::from_utf8_lossy(&bytes).rfind("\nxref\n").unwrap() + 1; + let section = bytes.len(); + bytes.extend_from_slice( + format!("xref\n5 1\n0000000000 00001 f \ntrailer\n<< /Size 6 /Root 1 0 R /Prev {prev} >>\nstartxref\n{section}\n%%EOF\n").as_bytes(), + ); + let doc = Document::open(Arc::new(bytes)).unwrap(); + assert!(matches!(&*doc.get(ObjRef::new(4, 0)), Object::Stream(_)), "the gap is filled"); + assert_eq!(*doc.get(ObjRef::new(5, 0)), Object::Null, "the freed image stays freed"); + assert_eq!(doc.xref_entry(5), Some(XrefEntry::Free { next_generation: 1 })); + } + + /// Repairing a damaged table fills only the numbers the damage leaves out: an old body of a + /// number no section lists, under an oversized `/Size`, stays a null object. + #[test] + fn a_repaired_table_leaves_an_unlisted_number_null() { + let base = scanned_page(); + let at = String::from_utf8_lossy(&base).rfind("\nxref\n").unwrap() + 1; + let entries = table_entries(&base); + let mut offset_zero = vec!["0 6".to_string()]; + offset_zero.extend(entries.iter().cloned()); + offset_zero[5] = "0000000000 00000 n ".into(); + let mut off_by_one = vec!["0 5".to_string()]; + off_by_one.extend(entries[1..6].iter().cloned()); + for (name, table, found) in [("offset 0", offset_zero, 4), ("off by one", off_by_one, 5)] { + let bytes = [&base[..at], b"7 0 obj\n(stale)\nendobj\n", &base[at..]].concat(); + let doc = Document::open(Arc::new(with_table(&bytes, &table, 9))).unwrap(); + assert!(matches!(&*doc.get(ObjRef::new(found, 0)), Object::Stream(_)), "{name}: the gap is filled"); + assert_eq!(*doc.get(ObjRef::new(7, 0)), Object::Null, "{name}: {:?}", doc.repair_log()); + assert_eq!(doc.xref_entry(7), None, "{name}"); + } + } + + /// The last object of a subsection numbered one too low is filled from that subsection, + /// whatever later happens to the row before it: an incremental save that rewrites object 4, + /// or object 4's own row at offset 0. + #[test] + fn the_last_object_of_a_shifted_subsection_is_filled_whatever_its_neighbour_says() { + let base = scanned_page(); + let entries = table_entries(&base); + let mut off_by_one = vec!["0 5".to_string()]; + off_by_one.extend(entries[1..6].iter().cloned()); + let shifted = with_table(&base, &off_by_one, 5); + let prev = String::from_utf8_lossy(&shifted).rfind("\nxref\n").unwrap() + 1; + let mut updated = shifted.clone(); + let body = updated.len(); + updated.extend_from_slice(b"4 0 obj\n<< /Length 21 >>\nstream\n10 0 0 10 0 0 cm /Im0 Do\nendstream\nendobj\n"); + let section = updated.len(); + updated.extend_from_slice( + format!("xref\n4 1\n{body:010} 00000 n \ntrailer\n<< /Size 6 /Root 1 0 R /Prev {prev} >>\nstartxref\n{section}\n%%EOF\n").as_bytes(), + ); + let mut neighbour_at_zero = off_by_one.clone(); + neighbour_at_zero[5] = "0000000000 00000 n ".into(); + for (name, bytes) in [("updated", updated), ("row 4 at offset 0", with_table(&base, &neighbour_at_zero, 5))] { + let doc = Document::open(Arc::new(bytes)).unwrap(); + let image = doc.get(ObjRef::new(5, 0)); + assert_eq!(image.as_dict().and_then(|d| d.name(b"Subtype")), Some(&b"Image"[..]), "{name}: {:?}", doc.repair_log()); + } + } + + /// The image the first page draws as `/Im1`, followed through the page tree. + fn first_page_image(doc: &Document) -> Arc { + let catalog = doc.get(doc.root().unwrap()); + let pages = doc.resolve(catalog.as_dict().unwrap().get(b"Pages").unwrap()); + let page = doc.resolve(&pages.as_dict().unwrap().get(b"Kids").unwrap().as_array().unwrap()[0]); + let resources = doc.resolve(page.as_dict().unwrap().get(b"Resources").unwrap()); + let xobjects = doc.resolve(resources.as_dict().unwrap().get(b"XObject").unwrap()); + doc.resolve(xobjects.as_dict().unwrap().get(b"Im1").unwrap()) + } + + /// The opposite off-by-one (#1628): the subsection says it starts at 1, but its first entry + /// is object 0's free-list head, so every entry lands one number too high and object 1, the + /// image, reads as free. The offset the table gives object 2 holds `1 0 obj`, so the + /// subsection is read from 0, and the image survives a full save. + #[test] + fn a_subsection_from_one_that_opens_with_the_free_list_head_is_read_from_zero() { + let base = build( + &[ + "<< /Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Length 12 >>\nstream\nABCDEFGHIJKL\nendstream", + "<< /Length 29 >>\nstream\nq 72 0 0 72 0 0 cm /Im1 Do Q\nendstream", + "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 72 72] /Resources << /XObject << /Im1 1 0 R >> >> /Contents 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Catalog /Pages 4 0 R >>", + "<< /Subject (synthetic) >>", + ], + "/Root 5 0 R /Info 6 0 R", + ); + // /Size 7 is one short of the shifted numbers; /Size 8 covers them all. Junk before the + // header moves every object past the offsets the table gives; it is not a comment, which + // the lexer would skip on its way to `1 0 obj` anyway. + for (size, junk) in [(7, ""), (8, ""), (7, "Content-Type: application/pdf\n\n")] { + let text = String::from_utf8_lossy(&base).replace("\nxref\n0 7\n", "\nxref\n1 7\n").replace("/Size 7 ", &format!("/Size {size} ")); + let doc = Document::open(Arc::new(format!("{junk}{text}").into_bytes())).unwrap(); + let image = first_page_image(&doc); + assert_eq!(image.as_dict().and_then(|d| d.name(b"Subtype")), Some(&b"Image"[..]), "/Size {size} {junk:?}: {image:?}"); + assert_eq!(doc.xref_entry(0), Some(XrefEntry::Free { next_generation: 65535 }), "/Size {size} {junk:?}"); + assert!(doc.repair_log().iter().any(|l| l.contains("from 0")), "/Size {size} {junk:?}: {:?}", doc.repair_log()); + let saved = Document::open(Arc::new(crate::write_full(&doc, &crate::SaveOptions::default()).unwrap())).unwrap(); + let image = first_page_image(&saved); + assert!(matches!(&*image, Object::Stream(s) if &s.raw[..] == b"ABCDEFGHIJKL"), "/Size {size} {junk:?}: {image:?}"); + } + } + + /// Object 1 really freed: the subsection from 1 opens with a free entry, but the next entry's + /// offset holds object 2, not object 1. The table is taken as it is, and the old body of + /// object 1 still in the file stays freed. + #[test] + fn a_subsection_from_one_whose_next_offset_holds_object_two_is_taken_as_it_is() { + let base = build(&["(freed)", "<< /Type /Catalog /Pages 3 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], "/Root 2 0 R"); + let entries = table_entries(&base); + let mut table = vec!["1 3".to_string(), "0000000000 65535 f ".to_string()]; + table.extend(entries[2..].iter().cloned()); + let text = String::from_utf8_lossy(&base).into_owned(); + let at = text.rfind("\nxref\n").unwrap() + 1; + for junk in ["", "Content-Type: application/pdf\n\n"] { + let mut bytes = junk.as_bytes().to_vec(); + bytes.extend_from_slice(&base[..at]); + bytes.extend_from_slice(format!("xref\n{}\ntrailer\n<< /Size 4 /Root 2 0 R >>\nstartxref\n{at}\n%%EOF\n", table.join("\n")).as_bytes()); + let doc = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(doc.xref_entry(1), Some(XrefEntry::Free { next_generation: 65535 }), "{junk:?}"); + assert_eq!(*doc.get(ObjRef::new(1, 0)), Object::Null, "{junk:?}: the freed object stays freed"); + assert!(matches!(&*doc.get(ObjRef::new(2, 0)), Object::Dict(d) if d.name(b"Type") == Some(&b"Catalog"[..])), "{junk:?}"); + assert!(!doc.repair_log().iter().any(|l| l.contains("from 0")), "{junk:?}: {:?}", doc.repair_log()); + assert!(!junk.is_empty() || doc.repair_log().is_empty(), "{:?}", doc.repair_log()); + } + } + #[test] fn opening_an_exhausted_classic_xref_repairs_and_allocates() { // The extra in-use row need not be loaded to exhaust the next object number. @@ -2574,7 +2979,7 @@ endobj assert!(reader.document.cache.lock().unwrap().len() < ObjectReader::OBJECTS); let decoded = reader.document.objstms.lock().unwrap(); assert!(decoded.len() < ObjectReader::OBJECTS); - let bytes: usize = decoded.values().map(|s| s.data.capacity() + s.index.capacity() * std::mem::size_of::<(u32, usize)>()).sum(); + let bytes: usize = decoded.values().map(|s| s.data.capacity() + s.index.capacity() * std::mem::size_of::>()).sum(); assert!(bytes <= ObjectReader::STREAM_BYTES || decoded.len() == 1, "only one oversized stream may remain"); } drop(reader); @@ -2695,6 +3100,16 @@ endobj /// says it lives in object stream 4. #[test] fn hybrid_reference_files_read_the_xref_stream_too() { + let doc = Document::open(Arc::new(object_stream_file("3 0 ", "<< /Hidden (yes) >>", 0))).unwrap(); + assert!(doc.repair_log().is_empty(), "{:?}", doc.repair_log()); + assert_compact_matches_materialized(&doc); + assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("yes")); + } + + /// A hybrid-reference file whose classic table leaves object 3 out, and whose `/XRefStm` + /// stream puts it at position `member` of object stream 4, which holds `header` (the number + /// and offset pairs) and then `members`. + fn object_stream_file(header: &str, members: &str, member: u8) -> Vec { let mut out = b"%PDF-1.5\n".to_vec(); let mut offs = [0usize; 6]; let mut obj = |out: &mut Vec, n: usize, body: &[u8]| { @@ -2705,12 +3120,13 @@ endobj }; obj(&mut out, 1, b"<< /Type /Catalog /Pages 2 0 R >>"); obj(&mut out, 2, b"<< /Type /Pages /Kids [] /Count 0 /Extra 3 0 R >>"); - let inner = b"3 0 << /Hidden (yes) >>"; - let mut stm = format!("<< /Type /ObjStm /N 1 /First 4 /Length {} >>\nstream\n", inner.len()).into_bytes(); - stm.extend_from_slice(inner); + let count = header.split_whitespace().count() / 2; + let inner = format!("{header}{members}"); + let mut stm = format!("<< /Type /ObjStm /N {count} /First {} /Length {} >>\nstream\n", header.len(), inner.len()).into_bytes(); + stm.extend_from_slice(inner.as_bytes()); stm.extend_from_slice(b"\nendstream"); obj(&mut out, 4, &stm); - let data = [2u8, 0, 4, 0]; + let data = [2u8, 0, 4, member]; let mut xs = format!("<< /Type /XRef /Size 6 /W [1 2 1] /Index [3 1] /Length {} >>\nstream\n", data.len()).into_bytes(); xs.extend_from_slice(&data); xs.extend_from_slice(b"\nendstream"); @@ -2722,11 +3138,47 @@ endobj out.extend_from_slice(line.as_bytes()); } out.extend_from_slice(format!("trailer << /Size 6 /Root 1 0 R /XRefStm {} >>\nstartxref\n{table}\n%%EOF\n", offs[5]).as_bytes()); - let doc = Document::open(Arc::new(out)).unwrap(); - assert!(doc.repair_log().is_empty(), "{:?}", doc.repair_log()); - assert_compact_matches_materialized(&doc); - let hidden = doc.get(ObjRef::new(3, 0)); - assert_eq!(hidden.as_dict().and_then(|d| d.get(b"Hidden").and_then(|h| h.as_string().map(|s| s.to_text()))), Some("yes".into())); + out + } + + fn text_of(doc: &Document, num: u32, key: &[u8]) -> Option { + doc.get(ObjRef::new(num, 0)).as_dict().and_then(|d| d.get(key).and_then(|v| v.as_string().map(|s| s.to_text()))) + } + + /// An object stream member numbered 2^32 + 3 is not object 3 (#1815): the number used to be + /// cast to `u32`, which dropped the high bits. + #[test] + fn object_stream_numbers_beyond_u32_are_not_truncated() { + let control = Document::open(Arc::new(object_stream_file("3 0 ", "<< /Member (yes) >>", 0))).unwrap(); + assert_eq!(text_of(&control, 3, b"Member").as_deref(), Some("yes")); + let doc = Document::open(Arc::new(object_stream_file("4294967299 0 ", "<< /Member (yes) >>", 0))).unwrap(); + assert!(matches!(*doc.get(ObjRef::new(3, 0)), Object::Null), "{:?}", doc.get(ObjRef::new(3, 0))); + assert!(!doc.xref_entry_is_exact(3)); + } + + /// Member starts are checked rather than cast, so they cannot wrap on any target (#1815). + #[test] + fn object_stream_member_starts_are_checked() { + assert_eq!(objstm_member(3, 4, Some(10), 20), Some((3, 14))); + assert_eq!(objstm_member(3, 9, Some(10), 20), Some((3, 19)), "the last byte"); + assert_eq!(objstm_member(3, 10, Some(10), 20), None, "at the end of the data"); + assert_eq!(objstm_member(3, 1, Some(usize::MAX), 20), None, "/First plus the offset overflows"); + assert_eq!(objstm_member(3, i64::MAX, Some(10), 20), None); + assert_eq!(objstm_member(3, -1, Some(10), 20), None); + assert_eq!(objstm_member(3, 0, None, 20), None, "/First does not fit in usize"); + assert_eq!(objstm_member(i64::from(u32::MAX), 0, Some(0), 1), Some((u32::MAX, 0))); + assert_eq!(objstm_member(i64::from(u32::MAX) + 1, 0, Some(0), 1), None); + assert_eq!(objstm_member(-1, 0, Some(0), 1), None); + } + + /// A member at a negative offset is unusable, not the stream's first member (#1815): the + /// offset used to be clamped to zero, which read the object at `/First`. + #[test] + fn object_stream_negative_offsets_are_refused() { + let doc = Document::open(Arc::new(object_stream_file("7 0 3 -1 ", "<< /First (yes) >>", 1))).unwrap(); + assert!(matches!(*doc.get(ObjRef::new(3, 0)), Object::Null), "{:?}", doc.get(ObjRef::new(3, 0))); + let control = Document::open(Arc::new(object_stream_file("7 0 3 19 ", "<< /First (yes) >> << /Second (yes) >>", 1))).unwrap(); + assert_eq!(text_of(&control, 3, b"Second").as_deref(), Some("yes")); } #[test] @@ -2834,6 +3286,125 @@ endobj } } + /// A trailer whose /Prev is written as the reference `N 0 R` (tiff2pdf did this; the files + /// are JHOVE's PDF-HUL-157 cases, #2366) used to end the cross-reference chain silently, so + /// every object of the earlier sections read as null: a four-page file showed one page, and + /// a full save wrote the three missing kids as null. The offset is read from the reference. + #[test] + fn a_prev_written_as_a_reference_still_reaches_the_earlier_sections() { + let base = build( + &["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R >>"], + "/Root 1 0 R", + ); + let prev = String::from_utf8_lossy(&base).rfind("xref\n0 4").unwrap(); + let update = |prev_entry: &str| { + let mut bytes = base.clone(); + let at = bytes.len(); + bytes.extend_from_slice(b"4 0 obj\n<< /Title (Update) >>\nendobj\n"); + let xref = bytes.len(); + bytes.extend_from_slice( + format!( + "xref\n4 1\n{at:010} 00000 n \ntrailer\n<< /Size 5 /Root 1 0 R /Info 4 0 R /Prev {prev_entry} >>\nstartxref\n{xref}\n%%EOF\n" + ) + .as_bytes(), + ); + Document::open(Arc::new(bytes)).unwrap() + }; + let good = update(&prev.to_string()); + let bad = update(&format!("{prev} 0 R")); + assert!(good.repair_log().is_empty(), "{:?}", good.repair_log()); + assert_eq!(bad.revisions().len(), 2, "{:?}", bad.repair_log()); + assert_eq!(bad.repair_log().len(), 1, "a note about the /Prev: {:?}", bad.repair_log()); + assert_eq!(bad.xref_entry(3), good.xref_entry(3), "the page of the first section is reached"); + assert_eq!(bad.get(ObjRef::new(3, 0)).as_dict().and_then(|d| d.name(b"Type")), Some(&b"Page"[..])); + assert_eq!( + bad.get(ObjRef::new(4, 0)).as_dict().and_then(|d| d.get(b"Title").and_then(|t| t.as_string().map(|s| s.to_text()))), + Some("Update".into()) + ); + } + + /// iText's `indirectPrev.pdf` in miniature: the update's trailer gives `/Prev 4 0 R`, and + /// object 4, listed in that update, holds the offset of the first section. Read as offset 4 + /// (inside the header), the chain broke and the file was rebuilt without its revisions. + #[test] + fn a_prev_reference_to_an_object_holding_the_offset_reads_that_offset() { + let mut bytes = build( + &["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R >>"], + "/Root 1 0 R", + ); + let prev = String::from_utf8_lossy(&bytes).rfind("xref\n0 4").unwrap(); + let mut at = Vec::new(); + for (num, body) in + [(2, "<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_string()), (4, prev.to_string()), (5, "<< /Type /Page /Parent 2 0 R >>".into())] + { + at.push(bytes.len()); + bytes.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes()); + } + let xref = bytes.len(); + bytes.extend_from_slice( + format!( + "xref\n2 1\n{:010} 00000 n \n4 2\n{:010} 00000 n \n{:010} 00000 n \ntrailer\n<< /Size 6 /Root 1 0 R /Prev 4 0 R >>\nstartxref\n{xref}\n%%EOF\n", + at[0], at[1], at[2] + ) + .as_bytes(), + ); + let doc = Document::open(Arc::new(bytes)).unwrap(); + assert_eq!(doc.revisions().len(), 2, "{:?}", doc.repair_log()); + assert_eq!(doc.repair_log().len(), 1, "a note about the /Prev, and no rebuild: {:?}", doc.repair_log()); + assert!(doc.repair_log()[0].contains(&format!("the offset {prev}")), "{:?}", doc.repair_log()); + assert_eq!(doc.get(ObjRef::new(3, 0)).as_dict().and_then(|d| d.name(b"Type")), Some(&b"Page"[..])); + assert_compact_matches_materialized(&doc); + } + + /// A file whose only trailers are cross-reference stream dictionaries, with its `startxref` + /// out of reach (here a second file appended after it, cut off before its own + /// cross-reference data, as in #2365), is rebuilt from its object headers. The rebuild used + /// to look only for the `trailer` keyword, so /Info and /ID were lost, and a full save after + /// editing one Info field dropped every other. + #[test] + fn reconstruction_takes_the_trailer_from_a_cross_reference_stream() { + let table = build( + &["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Title (Kept) /Creator (Me) >>"], + "/Root 1 0 R /Info 3 0 R", + ); + let packed = crate::write_full(&Document::open(Arc::new(table)).unwrap(), &crate::SaveOptions::default()).unwrap(); + let text = String::from_utf8_lossy(&packed); + assert!(text.contains("/XRef") && !text.contains("trailer"), "a cross-reference stream is the only trailer"); + let mut bytes = packed.clone(); + let appended = format!("%PDF-1.3\n90 0 obj\n<< /Length 5000 >>\nstream\n{}\nendstream\nendobj\n", "x".repeat(5000)); + bytes.extend_from_slice(appended.as_bytes()); + let doc = Document::open(Arc::new(bytes)).unwrap(); + assert!(doc.revisions().is_empty(), "rebuilt: {:?}", doc.repair_log()); + let info = doc.trailer().reference(b"Info").expect("the cross-reference stream's /Info"); + let field = |d: &Document, key: &[u8]| d.get(info).as_dict().unwrap().get(key).unwrap().as_string().unwrap().bytes.clone(); + assert_eq!(field(&doc, b"Title"), b"Kept"); + assert!(doc.trailer().get(b"ID").is_some(), "and its /ID"); + let mut edited = doc.clone(); + edited.update_dict(info, |d| d.set(b"Subject".to_vec(), Object::String(crate::PdfString::literal("new")))).unwrap(); + let saved = crate::write_full(&edited, &crate::SaveOptions::default()).unwrap(); + let back = Document::open(Arc::new(saved)).unwrap(); + assert!(back.repair_log().is_empty(), "{:?}", back.repair_log()); + let info = back.trailer().reference(b"Info").expect("the full save keeps /Info"); + let field = |key: &[u8]| back.get(info).as_dict().unwrap().get(key).unwrap().as_string().unwrap().bytes.clone(); + assert_eq!((field(b"Title"), field(b"Creator"), field(b"Subject")), (b"Kept".to_vec(), b"Me".to_vec(), b"new".to_vec())); + } + + /// A rebuild prefers a trailer whose /Root is the catalog (as `root_is_catalog` judges it): a + /// later cross-reference stream whose /Root points at the Info dictionary does not replace an + /// earlier good trailer, or a full save would write the Info dictionary as /Root. + #[test] + fn reconstruction_skips_a_trailer_whose_root_is_not_the_catalog() { + let mut bytes = + build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Title (Kept) >>"], "/Root 1 0 R /Info 3 0 R"); + bytes.extend_from_slice(b"4 0 obj\n<< /Type /XRef /Size 5 /W [1 1 1] /Root 3 0 R /Length 3 >>\nstream\nabc\nendstream\nendobj\n"); + let appended = format!("%PDF-1.3\n90 0 obj\n<< /Length 5000 >>\nstream\n{}\nendstream\nendobj\n", "x".repeat(5000)); + bytes.extend_from_slice(appended.as_bytes()); + let doc = Document::open(Arc::new(bytes)).unwrap(); + assert!(doc.repair_log().iter().any(|l| l.contains("rebuilt")), "{:?}", doc.repair_log()); + assert_eq!(doc.trailer().reference(b"Root").map(|r| r.num), Some(1), "the catalog, not the Info dictionary"); + assert_eq!(doc.trailer().reference(b"Info").map(|r| r.num), Some(3)); + } + #[test] fn damaged_xref_is_reconstructed() { let mut bytes = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"], "/Root 1 0 R"); diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 854554212..c4b5be1ba 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -457,25 +457,54 @@ fn nums(doc: &Document, o: Option<&Object>) -> Option> { pub(crate) fn page_refs(doc: &Document) -> Vec { let Some(root) = doc.root() else { return Vec::new() }; let Some(pages) = doc.get(root).as_dict().and_then(|d| d.reference(b"Pages")) else { return Vec::new() }; - let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); - let mut stack = vec![pages]; - while let Some(node) = stack.pop() { - if !seen.insert(node) || seen.len() > 1_000_000 { - continue; - } - let obj = doc.get(node); - let Some(d) = obj.as_dict() else { continue }; - match d.get(b"Kids").map(|k| doc.resolve(k)) { - Some(kids) if d.name(b"Type") != Some(b"Page") => { - if let Some(a) = kids.as_array() { - stack.extend(a.iter().rev().filter_map(|k| k.as_ref())); - } + PageWalk::new(doc, pages).collect() +} + +/// Depth-first walk over the leaf pages under `top`. It keeps one cursor per open `/Kids` array, +/// never one entry per child, so a child listed many times or shared between nodes is skipped by +/// the seen check without being queued first (`pdfcraft_model::pages` walks the same way). +/// Cycles end at the seen check and at most a million nodes are visited. +struct PageWalk<'a> { + doc: &'a Document, + seen: std::collections::HashSet, + pending: Vec<(std::sync::Arc, usize)>, +} + +impl<'a> PageWalk<'a> { + fn new(doc: &'a Document, top: ObjRef) -> Self { + let top = std::sync::Arc::new(Object::Array(vec![Object::Ref(top)])); + Self { doc, seen: Default::default(), pending: vec![(top, 0)] } + } +} + +impl Iterator for PageWalk<'_> { + type Item = ObjRef; + + fn next(&mut self) -> Option { + while let Some((kids, next)) = self.pending.last_mut() { + let Some(kid) = kids.as_array().and_then(|a| a.get(*next)) else { + self.pending.pop(); + continue; + }; + let node = kid.as_ref(); + *next += 1; + let Some(node) = node else { continue }; + if self.seen.len() >= 1_000_000 { + self.pending.clear(); + return None; + } + if !self.seen.insert(node) { + continue; + } + let obj = self.doc.get(node); + let Some(d) = obj.as_dict() else { continue }; + match d.get(b"Kids").map(|k| self.doc.resolve(k)) { + Some(kids) if d.name(b"Type") != Some(b"Page") => self.pending.push((kids, 0)), + _ => return Some(node), } - _ => out.push(node), } + None } - out } /// The AcroForm dictionary. diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index c62f09ff3..b2e4994ec 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -2965,3 +2965,19 @@ fn the_field_appearance_cache_sees_indirect_resources() { doc.set(r(8), Object::String(PdfString::text("/Helv 9 Tf 0 g"))); assert_eq!(redraw(&doc), 1, "the form's indirect /DA"); } + +#[test] +fn page_walk_skips_repeated_and_cyclic_kids_without_queueing_them() { + let mut doc = fixture(); + let root = ObjRef { num: 2, generation: 0 }; + let page = ObjRef { num: 3, generation: 0 }; + // A cycle back to the root, then the page 128 times over. + let mut kids = vec![Object::Ref(root)]; + kids.extend(std::iter::repeat_n(Object::Ref(page), 128)); + doc.update_dict(root, |d| d.set(b"Kids".to_vec(), Object::Array(kids))).unwrap(); + let mut walk = PageWalk::new(&doc, root); + assert_eq!(walk.next(), Some(page)); + assert!(walk.pending.len() <= 2, "repeated kids retained {} pending entries", walk.pending.len()); + assert_eq!(walk.next(), None); + assert_eq!(page_refs(&doc), [page]); +} diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rs index d4e032b46..fd4476f94 100644 --- a/crates/organize/src/lib.rs +++ b/crates/organize/src/lib.rs @@ -72,36 +72,74 @@ fn pages_root(doc: &Document) -> Result { /// All leaf pages in order, with their effective inherited attributes. fn walk(doc: &Document) -> Result, OrganizeError> { - let root = pages_root(doc)?; - let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); - // (node, inherited attributes from ancestors) - let mut stack: Vec<(ObjRef, Dict)> = vec![(root, Dict::new())]; - while let Some((node, inherited)) = stack.pop() { - if !seen.insert(node) || seen.len() > 1_000_000 { - continue; // cycles in broken trees - } - let obj = doc.get(node); - let Some(d) = obj.as_dict() else { continue }; - let mut attrs = inherited.clone(); - for k in INHERITABLE { - if let Some(v) = d.get(k) { - attrs.set(k.to_vec(), v.clone()); + Ok(PageWalk::new(doc, pages_root(doc)?).collect()) +} + +/// For each of `INHERITABLE`, the nearest node that sets it, shared rather than copied. +type Owners = [Option>; 4]; + +/// Depth-first walk over the leaf pages under `top`. It keeps one cursor per open `/Kids` array, +/// never one entry per child, and carries inherited attributes as the nodes that set them, so a +/// child listed many times or shared between nodes is skipped by the seen check before anything +/// is queued or copied (`pdfcraft_model::pages` walks the same way). Cycles in broken trees end +/// at the seen check and at most a million nodes are visited. +struct PageWalk<'a> { + doc: &'a Document, + seen: std::collections::HashSet, + pending: Vec<(std::sync::Arc, usize, Owners)>, +} + +impl<'a> PageWalk<'a> { + fn new(doc: &'a Document, top: ObjRef) -> Self { + let top = std::sync::Arc::new(Object::Array(vec![Object::Ref(top)])); + Self { doc, seen: Default::default(), pending: vec![(top, 0, Default::default())] } + } +} + +impl Iterator for PageWalk<'_> { + type Item = (ObjRef, Dict); + + fn next(&mut self) -> Option<(ObjRef, Dict)> { + while let Some((kids, next, inherited)) = self.pending.last_mut() { + let Some(kid) = kids.as_array().and_then(|a| a.get(*next)) else { + self.pending.pop(); + continue; + }; + let node = kid.as_ref(); + *next += 1; + let Some(node) = node else { continue }; + if self.seen.len() >= 1_000_000 { + self.pending.clear(); + return None; } - } - let is_pages = d.name(b"Type") == Some(b"Pages") || (d.contains(b"Kids") && d.name(b"Type") != Some(b"Page")); - if is_pages { - let kids = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default(); - for k in kids.iter().rev() { - if let Some(r) = k.as_ref() { - stack.push((r, attrs.clone())); + if !self.seen.insert(node) { + continue; + } + let obj = self.doc.get(node); + let Some(d) = obj.as_dict() else { continue }; + let mut owners = inherited.clone(); + for (k, owner) in INHERITABLE.iter().zip(&mut owners) { + if d.contains(k) { + *owner = Some(obj.clone()); } } - } else { - out.push((node, attrs)); + let is_pages = d.name(b"Type") == Some(b"Pages") || (d.contains(b"Kids") && d.name(b"Type") != Some(b"Page")); + if is_pages { + if let Some(kids) = d.get(b"Kids") { + self.pending.push((self.doc.resolve(kids), 0, owners)); + } + } else { + let mut attrs = Dict::new(); + for (k, owner) in INHERITABLE.iter().zip(&owners) { + if let Some(v) = owner.as_ref().and_then(|o| o.as_dict()).and_then(|o| o.get(k)) { + attrs.set(k.to_vec(), v.clone()); + } + } + return Some((node, attrs)); + } } + None } - Ok(out) } /// Leaf pages in document order. diff --git a/crates/organize/src/tests.rs b/crates/organize/src/tests.rs index aed8eae85..8bd80569f 100644 --- a/crates/organize/src/tests.rs +++ b/crates/organize/src/tests.rs @@ -774,6 +774,33 @@ fn resources_split_between_page_and_tree_travel_together() { } } +#[test] +fn a_scan_whose_xref_misses_the_image_combines_with_the_image() { + // A cheap image-to-PDF converter's table: "0 5" followed by the entries of objects 1 to 5, + // so the image (object 5) has none. Viewers rebuild the table and show the scan; the + // combined copy got a null image and came out blank (#1628). + let b: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>".into(), + "<< /Length 26 >>\nstream\n100 0 0 100 0 0 cm /Im0 Do\nendstream".into(), + "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\nA\nendstream".into(), + ]; + let good = build(&b, "/Root 1 0 R"); + let text = String::from_utf8_lossy(&good).into_owned(); + let at = text.rfind("\nxref\n").unwrap() + 1; + let entries: Vec<&str> = text[at..].lines().skip(3).take(5).collect(); + let mut bytes = good[..at].to_vec(); + bytes.extend_from_slice(format!("xref\n0 5\n{}\ntrailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{at}\n%%EOF\n", entries.join("\n")).as_bytes()); + let src = open(bytes); + let out = full_roundtrip(&combine(&[("scan", &src)]).unwrap()); + let res = out.dict(page_dict(&out, 0).get(b"Resources").unwrap()).unwrap(); + let image = res.get(b"XObject").and_then(|x| out.dict(x)).and_then(|d| d.get(b"Im0").map(|v| out.resolve(v))).expect("the page lists its image"); + let Object::Stream(image) = &*image else { panic!("the image is a stream, not {image:?}") }; + assert_eq!(image.dict.name(b"Subtype"), Some(&b"Image"[..])); + assert_eq!(image.decoded().unwrap(), b"A"); +} + #[test] fn links_are_rewired_to_copied_pages_or_dropped() { let a = doc_a(); @@ -2858,3 +2885,27 @@ fn a_bookmark_position_that_is_not_a_number_is_refused_and_changes_nothing() { assert_eq!(crate::add_bookmark_at(&mut d, &[], 9, " ", 0, Some(1.0), Some(1.0)), Err(crate::OutlineError::EmptyTitle)); assert_eq!(titles(&crate::bookmarks(&d)), ["Keep"]); } + +#[test] +fn page_walk_skips_repeated_and_cyclic_kids_without_copying_attributes() { + let mut doc = open(fixture()); + let (root, branch) = (ObjRef { num: 2, generation: 0 }, ObjRef { num: 3, generation: 0 }); + let (first, second) = (ObjRef { num: 4, generation: 0 }, ObjRef { num: 5, generation: 0 }); + // The branch node carries Resources for its pages: a cycle back to it, then both pages + // 128 times over. + let mut kids = vec![Object::Ref(branch)]; + kids.extend([Object::Ref(first), Object::Ref(second)].into_iter().cycle().take(256)); + doc.update_dict(branch, |d| d.set(b"Kids".to_vec(), Object::Array(kids))).unwrap(); + let mut walk = PageWalk::new(&doc, root); + let (page, attrs) = walk.next().unwrap(); + assert_eq!(page, first); + assert!(walk.pending.len() <= 3, "repeated kids retained {} pending entries", walk.pending.len()); + assert!(attrs.get(b"Resources").and_then(|r| r.as_dict()).is_some_and(|r| r.contains(b"Font")), "Resources from the branch"); + assert_eq!(attrs.get(b"Rotate").and_then(Object::as_int), Some(90), "Rotate from the root"); + assert_eq!(walk.next().map(|(p, _)| p), Some(second)); + let (_, last) = walk.next().unwrap(); + let media_box = last.get(b"MediaBox").and_then(Object::as_array).map(|m| m.iter().filter_map(Object::as_int).collect::>()); + assert_eq!(media_box, Some(vec![0, 0, 500, 500]), "own MediaBox kept over the root's"); + assert!(walk.next().is_none()); + assert_eq!(labels(&doc), ["Page 1", "Page 2", "Page 3"]); +} diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs index 402dadae1..9a5a7fefc 100644 --- a/crates/render/src/inspect.rs +++ b/crates/render/src/inspect.rs @@ -2625,6 +2625,71 @@ trailer << /Root 1 0 R >> assert!(reads < 20 * (PAGES + PAGES * PER_PAGE), "{reads} object reads"); } + /// #2365: the issue's fixture is two PDFs concatenated, the second cut off before its + /// cross-reference data, and the first's only trailer is a cross-reference stream. The + /// lazy reader refuses a file that needed repair, and lopdf's rebuild found no `trailer` + /// keyword and failed, so Document Properties showed every field empty. The rebuild now + /// takes the cross-reference stream's dictionary as the trailer. + #[test] + fn rebuilt_file_keeps_the_info_of_its_cross_reference_stream() { + let header = "%PDF-1.5\n"; + let obj1 = "1 0 obj<>endobj\n"; + let obj2 = "2 0 obj<>endobj\n"; + let obj3 = "3 0 obj<>endobj\n"; + let obj4 = "4 0 obj<>endobj\n"; + let o1 = header.len(); + let o2 = o1 + obj1.len(); + let o3 = o2 + obj2.len(); + let o4 = o3 + obj3.len(); + let o5 = o4 + obj4.len(); + let rows: Vec = + [[0u8, 0, 0, 255], [1, 0, o1 as u8, 0], [1, 0, o2 as u8, 0], [1, 0, o3 as u8, 0], [1, 0, o4 as u8, 0], [1, (o5 >> 8) as u8, o5 as u8, 0]] + .concat(); + let mut bytes = format!("{header}{obj1}{obj2}{obj3}{obj4}").into_bytes(); + bytes.extend_from_slice(format!("5 0 obj<>stream\n", rows.len()).as_bytes()); + bytes.extend_from_slice(&rows); + // A wrong startxref, and a second file after %%EOF: every reader rebuilds the table. + bytes.extend_from_slice(b"\nendstream\nendobj\nstartxref\n999999\n%%EOF\n%PDF-1.3\n"); + bytes.extend_from_slice(&[b'x'; 1024]); + + let info = inspect(Arc::new(bytes), None).unwrap(); + assert_eq!(info.pages.len(), 1); + assert_eq!(info.title.as_deref(), Some("Kept")); + assert_eq!(info.creator.as_deref(), Some("Me")); + } + + /// #2365 review: the rebuild prefers a trailer whose /Root is the catalog. A later + /// cross-reference stream whose /Root points at the Info dictionary used to replace the + /// earlier `trailer`, so Document Properties lost the catalog it should have read. + #[test] + fn rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog() { + let mut bytes = b"%PDF-1.5\n".to_vec(); + for body in [ + "<>", + "<>", + "<>", + "<>", + ] { + let n = bytes.iter().filter(|b| **b == b'\n').count(); + bytes.extend_from_slice(format!("{n} 0 obj{body}endobj\n").as_bytes()); + } + bytes.extend_from_slice(b"trailer\n<>\n"); + bytes.extend_from_slice(b"5 0 obj<>stream\n\x01\x00\x09\x00\nendstream\nendobj\n"); + // A wrong startxref, and a second file after %%EOF: every reader rebuilds the table. + bytes.extend_from_slice(b"startxref\n999999\n%%EOF\n%PDF-1.3\n"); + bytes.extend_from_slice(&[b'x'; 1024]); + + let info = inspect(Arc::new(bytes.clone()), None).unwrap(); + assert_eq!(info.pages.len(), 1); + assert_eq!(info.title.as_deref(), Some("Kept")); + // A later stream whose /Root names the catalog's number with another generation does + // not count either: loading `1 1 R` finds no such object. + let at = bytes.windows(10).position(|w| w == b"/Root 4 0 ").unwrap(); + bytes[at..at + 10].copy_from_slice(b"/Root 1 1 "); + let info = inspect(Arc::new(bytes), None).unwrap(); + assert_eq!((info.pages.len(), info.title.as_deref()), (1, Some("Kept"))); + } + #[test] fn lazy_structure_matches_the_compatibility_inspector() { // Each fixture as lopdf writes it, and with its objects in object streams. diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 1e989714f..45c87bfea 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -1871,6 +1871,18 @@ mod tests { extract_page(pdf, page, &InterpreterSettings::default()).unwrap() } + #[test] + fn text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei() { + // Everyday content both ways: a string with a byte above 0x7F, and a later word holding + // a capital "EI". The end-of-data look-ahead used to read the string's bytes as image + // data, so the image swallowed the rest of the page. + let pdf = marked_pages(&[ + "BI /W 1 /H 1 /BPC 8 /CS /DeviceGray ID \0 EI BT /F1 20 Tf 1 0 0 1 20 200 Tm (Gr\u{fc}\u{df}e) Tj 1 0 0 1 20 150 Tm (EINGANG) Tj ET", + ]); + + assert!(marked_text(&pdf, 0).plain_text().contains("EINGANG"), "the text after the inline image was not extracted"); + } + #[test] fn actual_text_replaces_the_glyphs_it_marks_in_every_writing_direction() { // Chrome marks each shaped Thai cluster this way: "น้ำ" (U+0E19 U+0E49 U+0E33) here stands diff --git a/vendor/README.md b/vendor/README.md index f472ba4a0..d8518ca8f 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -23,15 +23,16 @@ Other resource categories retain their existing parent-chain lookup. | hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option` 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 the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971) | (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`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_samples_the_same_columns`, `raster::tests::non_integer_minification_samples_colour_and_mask_from_the_same_columns`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path` |; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover` | 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` | | 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) | (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` | -| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text) | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time` +| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset` | hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it. | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed` -| 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 | (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` | +| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` | | hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it` | | 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) | (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` | | hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references` | | winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, non-repeated first key whose one callback inserts that same jamo, with IME enabled and nothing composed, focus and input source unchanged, is retried (`ime_startup.rs`). Port of [winit#4744](https://github.com/rust-windowing/winit/pull/4744), with its policy tests.; (11) on X11 without `Xft.dpi`, the scale factor comes from the X screen's configured DPI (its size in pixels and millimetres) before the output's physical density from RandR: Xorg can deliberately run a dense panel at 96 DPI, and only winit applications then looked zoomed; `Xft.dpi` still wins, `WINIT_X11_SCALE_FACTOR` still overrides, and a screen reporting no size keeps the RandR fallback. PdfCraft patch (#1150, replacing the launcher pin proposed in #908). (12) on macOS, `WinitView` answers `mouseDownCanMoveWindow` with the window's `movable_by_window_background` attribute (NO unless asked): NSView answers YES for a view that isn't opaque, so with the transparent title bar and full-size content view PdfCraft uses, AppKit moved the window for any drag that began in the 28 pt title-bar band before the app saw it, and document tabs (which live in that band) could not be dragged to reorder them. The empty strip still moves the window through `ViewportCommand::StartDrag`. PdfCraft patch. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build; (13) on Wayland, pixel-only wheel, wheel-tilt and continuous-source scroll events report `Moved` rather than starting an unterminated finger gesture, so egui follows modifier release instead of keeping Ctrl zoom latched (#991). Finger gestures and unknown sources retain their existing phase policy | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors on Windows 11; (2) `pdfcraft` `tests/winit_wayland_text_input.rs`; the capability change itself needs a Wayland session and an input method; (3) `pdfcraft` `tests/winit_windows_ime_cursor.rs`; composing itself needs the Microsoft Korean IME; (4) `pdfcraft` `tests/winit_windows_hidden_maximized.rs`; the start-up itself needs Windows and a window that was closed maximized; (5) `pdfcraft` `tests/winit_x11_ime_focus.rs`; switching fields itself needs an X11 session and an input method (IBus, fcitx5); (6) `pdfcraft` `tests/winit_macos_ime_commit.rs`; composing itself needs macOS and an input method; (7) `pdfcraft` `tests/winit_macos_ime_discard.rs`; composing itself needs macOS and an input method; (8) `pdfcraft` `tests/winit_macos_emoji_picker.rs`; the picker itself needs macOS; (9) `pdfcraft` `tests/winit_macos_korean_space.rs`; composing itself needs macOS and Apple Korean; (10) `pdfcraft` `tests/winit_macos_korean_first_key.rs` and `ime_startup.rs`'s own tests (run them with `rustc --test`); typing itself needs macOS and Apple Korean; (11) `pdfcraft` `tests/winit_x11_dpi.rs` keeps the patch in the build, and `util::randr` tests the policy (run them in the vendored crate); the scale itself needs an X11 session; (12) `pdfcraft` `tests/winit_macos_title_bar_drag.rs` keeps the patch in the build; the drag itself needs macOS and a pointer; (13) `pdfcraft` `tests/winit_wayland_scroll.rs` compiles the production phase policy and exercises modifier release through egui; live COSMIC confirmation remains open | | egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::egui_wgpu_carries_the_surface_size_fit`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error`, which keeps it around `add_surface`'s configure | | vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate | +| hayro-cmap | 0.1.0 | Apache-2.0 OR MIT | malformed parts of a CMap (bad bfchar/bfrange entries, unresolvable `usecmap`, unparseable tail) are skipped instead of discarding the whole map, so search and redaction find text the edit layer can read (#3177) | `hayro-cmap::tests::bad_bfchar_entry_is_skipped`, `unresolvable_usecmap_is_skipped` | Renderer startup errors: `egui-wgpu::RenderState::create` also wraps `Renderer::new` in `winit::catch_errors` when the winit feature is enabled. A rejected shader or render pipeline diff --git a/vendor/hayro-cmap/Cargo.lock b/vendor/hayro-cmap/Cargo.lock new file mode 100644 index 000000000..b19a6c70f --- /dev/null +++ b/vendor/hayro-cmap/Cargo.lock @@ -0,0 +1,53 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "hayro-cmap" +version = "0.1.0" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-postscript" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa" diff --git a/vendor/hayro-cmap/Cargo.toml b/vendor/hayro-cmap/Cargo.toml new file mode 100644 index 000000000..3818d177b --- /dev/null +++ b/vendor/hayro-cmap/Cargo.toml @@ -0,0 +1,87 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +name = "hayro-cmap" +version = "0.1.0" +authors = ["Laurenz Stampfl "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A parser for CMap files." +readme = "README.md" +license = "Apache-2.0 OR MIT" +repository = "https://github.com/LaurenzV/hayro" +resolver = "2" + +[features] +default = ["embed-cmaps"] +embed-cmaps = [ + "std", + "dep:brotli", +] +std = [] + +[lib] +name = "hayro_cmap" +path = "src/lib.rs" + +[dependencies.brotli] +version = "8" +features = [ + "std", + "std", +] +optional = true +default-features = false + +[dependencies.hayro-postscript] +version = "0.1.0" +default-features = false + +[lints.clippy] +collection_is_never_read = "warn" +dbg_macro = "warn" +debug_assert_with_mut_call = "warn" +default_trait_access = "warn" +doc_markdown = "warn" +fn_to_numeric_cast_any = "warn" +infinite_loop = "warn" +large_stack_arrays = "warn" +mismatching_type_param_order = "warn" +negative_feature_names = "warn" +redundant_feature_names = "warn" +same_functions_in_if_condition = "warn" +semicolon_if_nothing_returned = "warn" +todo = "warn" +too_many_arguments = "allow" +unseparated_literal_suffix = "warn" +use_self = "warn" +wildcard_dependencies = "warn" + +[lints.rust] +elided_lifetimes_in_paths = "warn" +keyword_idents_2024 = "forbid" +missing_docs = "warn" +non_ascii_idents = "forbid" +non_local_definitions = "forbid" +trivial_numeric_casts = "warn" +unnameable_types = "warn" +unreachable_pub = "warn" +unsafe_op_in_unsafe_fn = "forbid" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" +unused_qualifications = "warn" diff --git a/vendor/hayro-cmap/Cargo.toml.orig b/vendor/hayro-cmap/Cargo.toml.orig new file mode 100644 index 000000000..59f5c99d3 --- /dev/null +++ b/vendor/hayro-cmap/Cargo.toml.orig @@ -0,0 +1,21 @@ +[package] +name = "hayro-cmap" +version = "0.1.0" +description = "A parser for CMap files." +authors = { workspace = true } +edition = { workspace = true } +repository = { workspace = true } +license = { workspace = true } + +[features] +default = ["embed-cmaps"] +std = [] +# Embed the 61 predefined cmaps into the binary. Adds about ~250KB of brotli-encoded data. +embed-cmaps = ["std", "dep:brotli"] + +[dependencies] +hayro-postscript = { workspace = true } +brotli = { workspace = true, optional = true, features = ["std"] } + +[lints] +workspace = true diff --git a/vendor/hayro-cmap/LICENSE-APACHE b/vendor/hayro-cmap/LICENSE-APACHE new file mode 100644 index 000000000..4947287f7 --- /dev/null +++ b/vendor/hayro-cmap/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/vendor/hayro-cmap/LICENSE-MIT b/vendor/hayro-cmap/LICENSE-MIT new file mode 100644 index 000000000..ae3742de4 --- /dev/null +++ b/vendor/hayro-cmap/LICENSE-MIT @@ -0,0 +1,7 @@ +Copyright (c) The Hayro Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/hayro-cmap/README.md b/vendor/hayro-cmap/README.md new file mode 100644 index 000000000..bc93f93da --- /dev/null +++ b/vendor/hayro-cmap/README.md @@ -0,0 +1,25 @@ +# hayro-cmap + +[![Crates.io](https://img.shields.io/crates/v/hayro-cmap.svg)](https://crates.io/crates/hayro-cmap) +[![Documentation](https://docs.rs/hayro-cmap/badge.svg)](https://docs.rs/hayro-cmap) + + + +A parser for cmap files, as they are found in PDFs. + +This crate provides a parser for CMap files and allows you to +- Map character codes from text-showing operators to CID identifiers. +- Map CIDs to Unicode characters or strings. + +### Safety +This crate forbids unsafe code via a crate-level attribute. + + + +## License +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. diff --git a/vendor/hayro-cmap/assets/LICENSE.txt b/vendor/hayro-cmap/assets/LICENSE.txt new file mode 100644 index 000000000..2552cc990 --- /dev/null +++ b/vendor/hayro-cmap/assets/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 1990-2023 Adobe. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +Neither the name of Adobe nor the names of its contributors may be +used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/hayro-cmap/assets/README.md b/vendor/hayro-cmap/assets/README.md new file mode 100644 index 000000000..4cedb1ff6 --- /dev/null +++ b/vendor/hayro-cmap/assets/README.md @@ -0,0 +1,2 @@ +See https://github.com/LaurenzV/cmap-resources/tree/hayro for information on how this blob was generated and how +it can be parsed. \ No newline at end of file diff --git a/vendor/hayro-cmap/assets/cmaps.brotli b/vendor/hayro-cmap/assets/cmaps.brotli new file mode 100644 index 000000000..ba74bd32f Binary files /dev/null and b/vendor/hayro-cmap/assets/cmaps.brotli differ diff --git a/vendor/hayro-cmap/src/bcmap/embedded.rs b/vendor/hayro-cmap/src/bcmap/embedded.rs new file mode 100644 index 000000000..0f5c241a0 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/embedded.rs @@ -0,0 +1,129 @@ +use std::ops::Range; +use std::sync::LazyLock; + +use super::huffman::{self, HuffmanTable}; +use super::reader::Reader; +use crate::CMapName; + +pub(super) static BUNDLE: LazyLock = LazyLock::new(|| { + // We already know the bundle is valid, so we can skip validation and just + // unwrap everywhere. + + let compressed = include_bytes!("../../assets/cmaps.brotli"); + let mut decompressed = Vec::new(); + let mut reader = compressed.as_slice(); + + brotli::BrotliDecompress(&mut reader, &mut decompressed) + .ok() + .unwrap(); + + let mut reader = Reader::new(&decompressed); + let huff_size = reader.read_u32().unwrap() as usize; + let huff_data = reader.read_bytes(huff_size).unwrap(); + let (delta_table, count_table) = huffman::decode_tables(huff_data).unwrap(); + + let mut entries = Vec::new(); + + while !reader.at_end() { + let start = reader.position(); + + // Skip file magic and version. + reader.read_bytes(6).unwrap(); + let file_len = reader.read_u32().unwrap() as usize; + + reader.read_bytes(file_len - 10).unwrap(); + entries.push(start..start + file_len); + } + + Bundle { + data: decompressed, + delta_table, + count_table, + entries, + } +}); + +pub(super) struct Bundle { + data: Vec, + pub(super) delta_table: HuffmanTable, + pub(super) count_table: HuffmanTable, + entries: Vec>, +} + +/// Load the data for a cmap file, by name. +pub fn load_embedded(name: CMapName<'_>) -> Option<&'static [u8]> { + // Get the index of the font of the cmap in the bundle. They are sorted + // alphabetically. + let idx = match name { + CMapName::N83pvRksjH => 0, + CMapName::N90msRksjH => 1, + CMapName::N90msRksjV => 2, + CMapName::N90mspRksjH => 3, + CMapName::N90mspRksjV => 4, + CMapName::N90pvRksjH => 5, + CMapName::AddRksjH => 6, + CMapName::AddRksjV => 7, + CMapName::AdobeCns1Ucs2 => 8, + CMapName::AdobeGb1Ucs2 => 9, + CMapName::AdobeJapan1Ucs2 => 10, + CMapName::AdobeKorea1Ucs2 => 11, + CMapName::B5pcH => 12, + CMapName::B5pcV => 13, + CMapName::CnsEucH => 14, + CMapName::CnsEucV => 15, + CMapName::ETenB5H => 16, + CMapName::ETenB5V => 17, + CMapName::ETenmsB5H => 18, + CMapName::ETenmsB5V => 19, + CMapName::EucH => 20, + CMapName::EucV => 21, + CMapName::ExtRksjH => 22, + CMapName::ExtRksjV => 23, + CMapName::GbEucH => 24, + CMapName::GbEucV => 25, + CMapName::GbkEucH => 26, + CMapName::GbkEucV => 27, + CMapName::Gbk2kH => 28, + CMapName::Gbk2kV => 29, + CMapName::GbkpEucH => 30, + CMapName::GbkpEucV => 31, + CMapName::GbpcEucH => 32, + CMapName::GbpcEucV => 33, + CMapName::H => 34, + CMapName::HKscsB5H => 35, + CMapName::HKscsB5V => 36, + CMapName::IdentityH => 37, + CMapName::IdentityV => 38, + CMapName::KscEucH => 39, + CMapName::KscEucV => 40, + CMapName::KscmsUhcH => 41, + CMapName::KscmsUhcHwH => 42, + CMapName::KscmsUhcHwV => 43, + CMapName::KscmsUhcV => 44, + CMapName::KscpcEucH => 45, + CMapName::UniCnsUcs2H => 46, + CMapName::UniCnsUcs2V => 47, + CMapName::UniCnsUtf16H => 48, + CMapName::UniCnsUtf16V => 49, + CMapName::UniGbUcs2H => 50, + CMapName::UniGbUcs2V => 51, + CMapName::UniGbUtf16H => 52, + CMapName::UniGbUtf16V => 53, + CMapName::UniJisUcs2H => 54, + CMapName::UniJisUcs2HwH => 55, + CMapName::UniJisUcs2HwV => 56, + CMapName::UniJisUcs2V => 57, + CMapName::UniJisUtf16H => 58, + CMapName::UniJisUtf16V => 59, + CMapName::UniKsUcs2H => 60, + CMapName::UniKsUcs2V => 61, + CMapName::UniKsUtf16H => 62, + CMapName::UniKsUtf16V => 63, + CMapName::V => 64, + CMapName::Custom(_) => return None, + }; + + let range = BUNDLE.entries.get(idx)?; + + Some(&BUNDLE.data[range.clone()]) +} diff --git a/vendor/hayro-cmap/src/bcmap/huffman.rs b/vendor/hayro-cmap/src/bcmap/huffman.rs new file mode 100644 index 000000000..b6e8e9ab5 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/huffman.rs @@ -0,0 +1,180 @@ +use alloc::vec; +use alloc::vec::Vec; +use core::num::NonZeroU32; + +use super::reader::Reader; + +#[derive(Debug, Clone, Copy)] +pub(super) enum HuffmanNode { + /// Intermediate node with optional children. + Intermediate { + /// Index of the zero-child. + zero: Option, + /// Index of the one-child. + one: Option, + }, + /// Leaf node holding a decoded symbol value. + Leaf(u32), +} + +/// A Huffman table built from canonical codes. +#[derive(Debug)] +pub(super) struct HuffmanTable { + nodes: Vec, +} + +impl HuffmanTable { + /// Decode a single symbol from the bit reader. + pub(super) fn decode(&self, reader: &mut Reader<'_>) -> Option { + let mut idx = 0_u32; + + loop { + match self.nodes[idx as usize] { + HuffmanNode::Intermediate { zero, one } => { + let bit = reader.read_bit()?; + let child = if bit == 0 { zero } else { one }; + idx = child?.get(); + } + HuffmanNode::Leaf(symbol) => return Some(symbol), + } + } + } + + fn insert_code( + nodes: &mut Vec, + node_index: u32, + code: u32, + length: u8, + symbol: u32, + ) { + if length == 0 { + nodes[node_index as usize] = HuffmanNode::Leaf(symbol); + + return; + } + + let bit = (code >> (length - 1)) & 1; + let remaining = code & ((1 << (length - 1)) - 1); + + let child_index = match &nodes[node_index as usize] { + HuffmanNode::Intermediate { zero, one } => { + let existing = if bit == 0 { *zero } else { *one }; + match existing { + Some(idx) => idx, + None => { + let new_idx = NonZeroU32::new(nodes.len() as u32).unwrap(); + nodes.push(HuffmanNode::Intermediate { + zero: None, + one: None, + }); + + match &mut nodes[node_index as usize] { + HuffmanNode::Intermediate { zero, one } => { + if bit == 0 { + *zero = Some(new_idx); + } else { + *one = Some(new_idx); + } + } + _ => unreachable!(), + } + new_idx + } + } + } + _ => return, + }; + + Self::insert_code(nodes, child_index.get(), remaining, length - 1, symbol); + } + + fn build(code_lengths: &[u8], symbols: &[u32]) -> Self { + debug_assert_eq!(code_lengths.len(), symbols.len()); + + if symbols.is_empty() { + return Self { + nodes: vec![HuffmanNode::Intermediate { + zero: None, + one: None, + }], + }; + } + + let max_length = *code_lengths.iter().max().unwrap_or(&0) as usize; + + let mut codes = vec![0_u32; symbols.len()]; + let mut code = 0_u32; + + for length in 1..=max_length { + for (i, &cl) in code_lengths.iter().enumerate() { + if cl as usize == length { + codes[i] = code; + code += 1; + } + } + code <<= 1; + } + + let mut nodes = vec![HuffmanNode::Intermediate { + zero: None, + one: None, + }]; + + for (i, &symbol) in symbols.iter().enumerate() { + if code_lengths[i] == 0 { + continue; + } + + Self::insert_code(&mut nodes, 0, codes[i], code_lengths[i], symbol); + } + + Self { nodes } + } +} + +pub(super) fn decode_tables(data: &[u8]) -> Option<(HuffmanTable, HuffmanTable)> { + let mut reader = Reader::new(data); + let delta = decode_single_table(&mut reader, |r| r.read_u32())?; + let count = decode_single_table(&mut reader, |r| r.read_u8().map(u32::from))?; + + Some((delta, count)) +} + +fn decode_single_table( + reader: &mut Reader<'_>, + read_sym: fn(&mut Reader<'_>) -> Option, +) -> Option { + let n_symbols = reader.read_u16()? as usize; + + if n_symbols == 0 { + let _max_len = reader.read_u8()?; + + return Some(HuffmanTable { + nodes: vec![HuffmanNode::Intermediate { + zero: None, + one: None, + }], + }); + } + + let max_code_length = reader.read_u8()? as usize; + + let mut counts = Vec::with_capacity(max_code_length); + for _ in 0..max_code_length { + counts.push(reader.read_u16()?); + } + + let mut code_lengths = Vec::with_capacity(n_symbols); + let mut symbols = Vec::with_capacity(n_symbols); + + for (length_idx, &count) in counts.iter().enumerate() { + let code_len = (length_idx + 1) as u8; + + for _ in 0..count { + symbols.push(read_sym(reader)?); + code_lengths.push(code_len); + } + } + + Some(HuffmanTable::build(&code_lengths, &symbols)) +} diff --git a/vendor/hayro-cmap/src/bcmap/mod.rs b/vendor/hayro-cmap/src/bcmap/mod.rs new file mode 100644 index 000000000..997bc00d8 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/mod.rs @@ -0,0 +1,416 @@ +//! Inspired by pdf.js, we use a custom binary format to optionally embed +//! the required cmaps in a space-efficient manner. However, we don't use +//! their format description but have a custom one. For more information, +//! see . + +pub(crate) mod embedded; +pub(crate) mod huffman; +pub(crate) mod reader; + +use alloc::boxed::Box; +use alloc::vec::Vec; + +pub use embedded::load_embedded; + +use crate::bcmap::embedded::BUNDLE; +use crate::{ + BfRange, CMap, CMapName, CharacterCollection, CidFamily, CidRange, CodespaceRange, Metadata, + PartitionedRanges, Range, WritingMode, parse, +}; +use huffman::HuffmanTable; +use reader::Reader; + +const BCMAP_MAGIC: &[u8] = b"bcmap"; +const BCMAP_VERSION: u8 = 0x01; +const BCMAP_FILE_HEADER_SIZE: usize = 10; +const SEG_HEADER_SIZE: usize = 5; + +const SEGMENT_RANGE_1B: u8 = 0x01; +const SEGMENT_SINGLE_1B: u8 = 0x02; +const SEGMENT_RANGE_2B: u8 = 0x03; +const SEGMENT_SINGLE_2B: u8 = 0x04; +const SEGMENT_RANGE_3B: u8 = 0x05; +const SEGMENT_SINGLE_3B: u8 = 0x06; +const SEGMENT_RANGE_4B: u8 = 0x07; +const SEGMENT_SINGLE_4B: u8 = 0x08; +const SEGMENT_USECMAP: u8 = 0x09; +const SEGMENT_NOTDEF: u8 = 0x0A; +const SEGMENT_WMODE: u8 = 0x0B; +const SEGMENT_CODESPACE: u8 = 0x0C; +const SEGMENT_NAME: u8 = 0x0D; +const SEGMENT_CID_SYSTEM_INFO: u8 = 0x0E; +const SEGMENT_BF_RANGE_VARIABLE: u8 = 0x0F; +const SEGMENT_BF_SINGLE_VARIABLE: u8 = 0x10; +const SEGMENT_BF_SINGLE_1U: u8 = 0x11; +const SEGMENT_BF_SINGLE_2U: u8 = 0x12; +const SEGMENT_BF_SINGLE_3U: u8 = 0x13; +const SEGMENT_BF_SINGLE_4U: u8 = 0x14; +const SEGMENT_BF_RANGE_1U: u8 = 0x15; +const SEGMENT_BF_RANGE_2U: u8 = 0x16; + +pub(crate) fn parse<'a>( + data: &[u8], + get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, + depth: u32, +) -> Option { + // While in theory we can assume that all binary cmaps are valid, it can + // of course happen that an invalid one has been passed from outside, so + // we still need to do proper validation. + + if data.get(..5)? != BCMAP_MAGIC || *data.get(5)? != BCMAP_VERSION { + return None; + } + + let mut reader = Reader::new(data); + reader.read_bytes(6)?; // Skip magic + version. + + let file_len = reader.read_u32()? as usize; + + let delta_table = &BUNDLE.delta_table; + let count_table = &BUNDLE.count_table; + + let mut cmap_name = None; + let mut character_collection = None; + let mut writing_mode = None; + let mut base: Option> = None; + let mut _codespace_ranges = Vec::new(); + let mut cid_ranges = PartitionedRanges::new(); + let mut notdef_ranges = PartitionedRanges::new(); + let mut bf_entries = Vec::new(); + + // Start parsing all segments of the file. + let mut reader = Reader::new(data.get(BCMAP_FILE_HEADER_SIZE..file_len)?); + + while !reader.at_end() { + let seg_type = reader.read_u8()?; + let seg_len = reader.read_u32()? as usize; + + let payload = reader.read_bytes(seg_len.checked_sub(SEG_HEADER_SIZE)?)?; + + match seg_type { + SEGMENT_NAME => { + cmap_name = Some(Vec::from(payload)); + } + SEGMENT_CID_SYSTEM_INFO => { + // Format: Each string is 0-terminated. + let mut r = Reader::new(payload); + let registry = Vec::from(r.eat_until(|b| b == 0)); + r.read_u8()?; + + let ordering = Vec::from(r.eat_until(|b| b == 0)); + r.read_u8()?; + let supplement = r.read_u16()? as i32; + + character_collection = Some(CharacterCollection { + family: CidFamily::from_registry_ordering(®istry, &ordering), + supplement, + }); + } + SEGMENT_USECMAP => { + let base_data = get_cmap(CMapName::from_bytes(payload))?; + + base = Some(Box::new(parse::parse_inner( + base_data, + get_cmap.clone(), + depth, + )?)); + } + SEGMENT_WMODE => { + writing_mode = match payload.first()? { + 0 => Some(WritingMode::Horizontal), + 1 => Some(WritingMode::Vertical), + _ => None, + }; + } + SEGMENT_CODESPACE => { + parse_codespace(payload, &mut _codespace_ranges)?; + } + SEGMENT_NOTDEF => { + parse_notdef(payload, &mut notdef_ranges)?; + } + SEGMENT_RANGE_1B | SEGMENT_RANGE_2B | SEGMENT_RANGE_3B | SEGMENT_RANGE_4B => { + let bw = seg_type.div_ceil(2) as usize; + parse_cid_segment(payload, &mut cid_ranges, bw, delta_table, Some(count_table))?; + } + SEGMENT_SINGLE_1B | SEGMENT_SINGLE_2B | SEGMENT_SINGLE_3B | SEGMENT_SINGLE_4B => { + let bw = seg_type.div_ceil(2) as usize; + parse_cid_segment(payload, &mut cid_ranges, bw, delta_table, None)?; + } + SEGMENT_BF_RANGE_VARIABLE => { + parse_bf_segment( + payload, + &mut bf_entries, + delta_table, + Some(count_table), + None, + )?; + } + SEGMENT_BF_SINGLE_VARIABLE => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, None)?; + } + SEGMENT_BF_RANGE_1U => { + parse_bf_segment( + payload, + &mut bf_entries, + delta_table, + Some(count_table), + Some(1), + )?; + } + SEGMENT_BF_RANGE_2U => { + parse_bf_segment( + payload, + &mut bf_entries, + delta_table, + Some(count_table), + Some(2), + )?; + } + SEGMENT_BF_SINGLE_1U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(1))?; + } + SEGMENT_BF_SINGLE_2U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(2))?; + } + SEGMENT_BF_SINGLE_3U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(3))?; + } + SEGMENT_BF_SINGLE_4U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(4))?; + } + _ => { + return None; + } + } + } + + cid_ranges.sort(); + notdef_ranges.sort(); + bf_entries.sort_by(|a, b| a.range.start.cmp(&b.range.start)); + + Some(CMap { + metadata: Metadata { + character_collection, + name: cmap_name, + writing_mode, + }, + _codespace_ranges, + cid_ranges, + notdef_ranges, + bf_entries, + base, + }) +} + +fn parse_codespace(payload: &[u8], ranges: &mut Vec) -> Option<()> { + let mut r = Reader::new(payload); + let n_ranges = r.read_u8()? as usize; + + for _ in 0..n_ranges { + let bw = r.read_u8()? as usize; + let low = r.read_n_bytes(bw)?; + let high = r.read_n_bytes(bw)?; + + ranges.push(CodespaceRange { + number_bytes: bw as u8, + low, + high, + }); + } + + Some(()) +} + +fn parse_notdef(payload: &[u8], ranges: &mut PartitionedRanges) -> Option<()> { + let mut r = Reader::new(payload); + let bw = r.read_u8()? as usize; + let n_entries = r.read_u16()? as usize; + + for _ in 0..n_entries { + let start = r.read_n_bytes(bw)?; + let end = r.read_n_bytes(bw)?; + let cid = r.read_u16()? as u32; + + ranges.push( + bw, + CidRange { + range: Range { start, end }, + cid_start: cid, + }, + ); + } + + Some(()) +} + +fn parse_cid_segment( + payload: &[u8], + ranges: &mut PartitionedRanges, + byte_width: usize, + delta_table: &HuffmanTable, + count_table: Option<&HuffmanTable>, +) -> Option<()> { + let mut r = Reader::new(payload); + let n_entries = r.read_u16()? as usize; + + if n_entries == 0 { + return Some(()); + } + + // There are two types of CID segments, all of which are stored in a columnar + // fastion in the file: + // For the first type, we have a simple mapping from a single code to a single + // CID. In this case, the data stream first contains all codes using delta-coding, + // encoded using huffman coding. This is followed by all CIDs, stored as + // u16 (either as a raw CID, or as `0` in case the CID is +1 the previous CID). + // + // For the second type, we have a range of consecutive codes, which map + // to a range of consecutive CIDs. In this case, we have an additional "count" + // column that stores how many codes are mapped consecutively. These are also + // encoded using huffman coding. + + // Read deltas for the start code points. + let delta_len = r.read_u32()? as usize; + let delta_data = r.read_bytes(delta_len)?; + + let mut delta_reader = Reader::new(delta_data); + let mut deltas = Vec::with_capacity(n_entries); + + for _ in 0..n_entries { + deltas.push(delta_table.decode(&mut delta_reader)?); + } + + // Read the counts for each consecutive code range. + let mut counts = Vec::new(); + if let Some(ct) = count_table { + let count_len = r.read_u32()? as usize; + let count_data = r.read_bytes(count_len)?; + + let mut count_reader = Reader::new(count_data); + counts.reserve(n_entries); + for _ in 0..n_entries { + counts.push(ct.decode(&mut count_reader)?); + } + } + + // Read the CIDs and reconstruct the character codes that map to them. + let is_range = count_table.is_some(); + let mut prev_end: Option = None; + let mut prev_cid: Option = None; + let mut prev_range_len: u32 = 0; + + for i in 0..n_entries { + let raw_cid = r.read_u16()?; + + // Note that start deltas and counts are encoded minus one, so we + // need to add one when reconstructing them. + + // Reconstruct start code. + let start = if let Some(pe) = prev_end { + pe + 1 + deltas[i] + } else { + deltas[i] + }; + + // Reconstruct end code. + let end = if is_range { + start + counts[i] + 1 + } else { + start + }; + + // CID 0 means it's consecutive to the last seen CID, plus 1. + let cid = if raw_cid == 0 { + if let Some(pc) = prev_cid { + pc + prev_range_len + 1 + } else { + 0 + } + } else { + raw_cid as u32 + }; + + ranges.push( + byte_width, + CidRange { + range: Range { start, end }, + cid_start: cid, + }, + ); + + prev_end = Some(end); + prev_cid = Some(cid); + prev_range_len = end - start; + } + + Some(()) +} + +fn parse_bf_segment( + payload: &[u8], + entries: &mut Vec, + delta_table: &HuffmanTable, + count_table: Option<&HuffmanTable>, + fixed_units: Option, +) -> Option<()> { + let mut r = Reader::new(payload); + let n_entries = r.read_u16()? as usize; + + let delta_len = r.read_u32()? as usize; + let delta_data = r.read_bytes(delta_len)?; + + let mut delta_reader = Reader::new(delta_data); + let mut deltas = Vec::with_capacity(n_entries); + for _ in 0..n_entries { + deltas.push(delta_table.decode(&mut delta_reader)?); + } + + // Read counts for range segments. + let mut counts = Vec::new(); + if let Some(ct) = count_table { + let count_len = r.read_u32()? as usize; + let count_data = r.read_bytes(count_len)?; + + let mut count_reader = Reader::new(count_data); + counts.reserve(n_entries); + for _ in 0..n_entries { + counts.push(ct.decode(&mut count_reader)?); + } + } + + let is_range = count_table.is_some(); + let mut prev_end: Option = None; + + for i in 0..n_entries { + // Fixed-width segments encode destinations without a length prefix. + let n_units = match fixed_units { + Some(nu) => nu, + None => r.read_u8()? as usize, + }; + let mut dst_base = Vec::with_capacity(n_units); + for _ in 0..n_units { + dst_base.push(r.read_u16()?); + } + + let start = if let Some(pe) = prev_end { + pe + 1 + deltas[i] + } else { + deltas[i] + }; + + let end = if is_range { + start + counts[i] + 1 + } else { + start + }; + + entries.push(BfRange { + range: Range { start, end }, + dst_base, + }); + + prev_end = Some(end); + } + + Some(()) +} diff --git a/vendor/hayro-cmap/src/bcmap/reader.rs b/vendor/hayro-cmap/src/bcmap/reader.rs new file mode 100644 index 000000000..25d663910 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/reader.rs @@ -0,0 +1,123 @@ +pub(super) struct Reader<'a> { + data: &'a [u8], + byte_pos: usize, + bit_pos: u8, +} + +impl<'a> Reader<'a> { + #[inline] + pub(super) fn new(data: &'a [u8]) -> Self { + Self { + data, + byte_pos: 0, + bit_pos: 0, + } + } + + #[inline] + pub(super) fn read_bit(&mut self) -> Option { + let byte = *self.data.get(self.byte_pos)?; + let bit = (byte >> (7 - self.bit_pos)) & 1; + + self.bit_pos += 1; + + if self.bit_pos == 8 { + self.bit_pos = 0; + self.byte_pos += 1; + } + + Some(bit) + } + + #[inline] + pub(super) fn read_u16(&mut self) -> Option { + debug_assert_eq!(self.bit_pos, 0, "read_u16 called at non-byte boundary"); + + let bytes: [u8; 2] = self + .data + .get(self.byte_pos..self.byte_pos + 2)? + .try_into() + .ok()?; + self.byte_pos += 2; + + Some(u16::from_be_bytes(bytes)) + } + + #[inline] + pub(super) fn read_u32(&mut self) -> Option { + debug_assert_eq!(self.bit_pos, 0, "read_u32 called at non-byte boundary"); + + let bytes: [u8; 4] = self + .data + .get(self.byte_pos..self.byte_pos + 4)? + .try_into() + .ok()?; + self.byte_pos += 4; + + Some(u32::from_be_bytes(bytes)) + } + + #[inline] + pub(super) fn read_u8(&mut self) -> Option { + debug_assert_eq!(self.bit_pos, 0, "read_u8 called at non-byte boundary"); + + let val = *self.data.get(self.byte_pos)?; + self.byte_pos += 1; + + Some(val) + } + + #[inline] + pub(super) fn read_n_bytes(&mut self, n: usize) -> Option { + debug_assert_eq!( + self.bit_pos, 0, + "read_n_bytes_be called at non-byte boundary" + ); + + match n { + 1 => Some(self.read_u8()? as u32), + 2 => Some(self.read_u16()? as u32), + 3 => { + let bytes = self.read_bytes(3)?; + Some((bytes[0] as u32) << 16 | (bytes[1] as u32) << 8 | bytes[2] as u32) + } + 4 => self.read_u32(), + _ => None, + } + } + + #[inline] + pub(super) fn read_bytes(&mut self, n: usize) -> Option<&'a [u8]> { + debug_assert_eq!(self.bit_pos, 0, "read_bytes called at non-byte boundary"); + + let bytes = self.data.get(self.byte_pos..self.byte_pos + n)?; + self.byte_pos += n; + + Some(bytes) + } + + #[inline] + pub(super) fn position(&self) -> usize { + self.byte_pos + } + + #[inline] + pub(super) fn at_end(&self) -> bool { + self.byte_pos >= self.data.len() + } + + #[inline] + pub(super) fn eat_until(&mut self, f: impl Fn(u8) -> bool) -> &'a [u8] { + debug_assert_eq!(self.bit_pos, 0, "eat_until called at non-byte boundary"); + + let start = self.byte_pos; + while let Some(&b) = self.data.get(self.byte_pos) { + if f(b) { + break; + } + self.byte_pos += 1; + } + + &self.data[start..self.byte_pos] + } +} diff --git a/vendor/hayro-cmap/src/lib.rs b/vendor/hayro-cmap/src/lib.rs new file mode 100644 index 000000000..fb42ff37e --- /dev/null +++ b/vendor/hayro-cmap/src/lib.rs @@ -0,0 +1,1699 @@ +/*! +A parser for cmap files, as they are found in PDFs. + +This crate provides a parser for cmap files and allows you to +- Map character codes from text-showing operators to CID identifiers. +- Map CIDs to Unicode characters or strings. + +## Safety +This crate forbids unsafe code via a crate-level attribute. +*/ + +#![cfg_attr(not(feature = "std"), no_std)] +#![forbid(unsafe_code)] +#![deny(missing_docs)] + +extern crate alloc; + +#[cfg(feature = "embed-cmaps")] +mod bcmap; +mod parse; + +#[cfg(feature = "embed-cmaps")] +pub use bcmap::load_embedded; + +/// Look up an embedded binary cmap by name. +/// +/// Returns `None` when the `embed-cmaps` feature is not enabled. +#[cfg(not(feature = "embed-cmaps"))] +pub fn load_embedded(_name: CMapName<'_>) -> Option<&'static [u8]> { + None +} + +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; + +/// A CID (Character Identifier). +pub type Cid = u32; + +/// The name of the cmap. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CMapName<'a> { + // ── Adobe-Japan1 (Japanese) ── Shift-JIS (RKSJ) encodings ── + /// `83pv-RKSJ-H` — Adobe-Japan1, Mac Shift-JIS (`KanjiTalk` 6), horizontal. + N83pvRksjH, + /// `90ms-RKSJ-H` — Adobe-Japan1, Windows Shift-JIS (code page 932), horizontal. + N90msRksjH, + /// `90ms-RKSJ-V` — Adobe-Japan1, Windows Shift-JIS (code page 932), vertical. + N90msRksjV, + /// `90msp-RKSJ-H` — Adobe-Japan1, Windows Shift-JIS with proportional Roman, horizontal. + N90mspRksjH, + /// `90msp-RKSJ-V` — Adobe-Japan1, Windows Shift-JIS with proportional Roman, vertical. + N90mspRksjV, + /// `90pv-RKSJ-H` — Adobe-Japan1, Mac Shift-JIS (`KanjiTalk` 7), horizontal. + N90pvRksjH, + /// `Add-RKSJ-H` — Adobe-Japan1, Fujitsu FMR Shift-JIS, horizontal. + AddRksjH, + /// `Add-RKSJ-V` — Adobe-Japan1, Fujitsu FMR Shift-JIS, vertical. + AddRksjV, + + // ── Adobe UCS2 (CID → Unicode) ── + // Note that these are not part of the predefined CMaps, but we use them + // so we can more easily map CIDs back to Unicode. + /// `Adobe-CNS1-UCS2` — Adobe-CNS1, CID-to-Unicode mapping. + AdobeCns1Ucs2, + /// `Adobe-GB1-UCS2` — Adobe-GB1, CID-to-Unicode mapping. + AdobeGb1Ucs2, + /// `Adobe-Japan1-UCS2` — Adobe-Japan1, CID-to-Unicode mapping. + AdobeJapan1Ucs2, + /// `Adobe-Korea1-UCS2` — Adobe-Korea1, CID-to-Unicode mapping. + AdobeKorea1Ucs2, + + // ── Adobe-CNS1 (Traditional Chinese) ── Big Five encodings ── + /// `B5pc-H` — Adobe-CNS1, Mac Big Five (`ETen` extensions), horizontal. + B5pcH, + /// `B5pc-V` — Adobe-CNS1, Mac Big Five (`ETen` extensions), vertical. + B5pcV, + /// `CNS-EUC-H` — Adobe-CNS1, CNS 11643 EUC encoding, horizontal. + CnsEucH, + /// `CNS-EUC-V` — Adobe-CNS1, CNS 11643 EUC encoding, vertical. + CnsEucV, + /// `ETen-B5-H` — Adobe-CNS1, `ETen` Big Five extensions, horizontal. + ETenB5H, + /// `ETen-B5-V` — Adobe-CNS1, `ETen` Big Five extensions, vertical. + ETenB5V, + /// `ETenms-B5-H` — Adobe-CNS1, `ETen` Big Five with Microsoft symbol extensions, horizontal. + ETenmsB5H, + /// `ETenms-B5-V` — Adobe-CNS1, `ETen` Big Five with Microsoft symbol extensions, vertical. + ETenmsB5V, + + // ── Adobe-Japan1 (Japanese) ── EUC and extended Shift-JIS encodings ── + /// `EUC-H` — Adobe-Japan1, JIS X 0208 EUC-JP encoding, horizontal. + EucH, + /// `EUC-V` — Adobe-Japan1, JIS X 0208 EUC-JP encoding, vertical. + EucV, + /// `Ext-RKSJ-H` — Adobe-Japan1, Shift-JIS with NEC/IBM extensions, horizontal. + ExtRksjH, + /// `Ext-RKSJ-V` — Adobe-Japan1, Shift-JIS with NEC/IBM extensions, vertical. + ExtRksjV, + + // ── Adobe-GB1 (Simplified Chinese) ── + /// `GB-EUC-H` — Adobe-GB1, GB 2312-80 EUC encoding, horizontal. + GbEucH, + /// `GB-EUC-V` — Adobe-GB1, GB 2312-80 EUC encoding, vertical. + GbEucV, + /// `GBK-EUC-H` — Adobe-GB1, GBK encoding (Microsoft code page 936), horizontal. + GbkEucH, + /// `GBK-EUC-V` — Adobe-GB1, GBK encoding (Microsoft code page 936), vertical. + GbkEucV, + /// `GBK2K-H` — Adobe-GB1, GB 18030-2000 encoding, horizontal. + Gbk2kH, + /// `GBK2K-V` — Adobe-GB1, GB 18030-2000 encoding, vertical. + Gbk2kV, + /// `GBKp-EUC-H` — Adobe-GB1, GBK with proportional Roman, horizontal. + GbkpEucH, + /// `GBKp-EUC-V` — Adobe-GB1, GBK with proportional Roman, vertical. + GbkpEucV, + /// `GBpc-EUC-H` — Adobe-GB1, Mac GB 2312 (simplified) EUC encoding, horizontal. + GbpcEucH, + /// `GBpc-EUC-V` — Adobe-GB1, Mac GB 2312 (simplified) EUC encoding, vertical. + GbpcEucV, + + // ── Adobe-Japan1 (Japanese) ── JIS encoding ── + /// `H` — Adobe-Japan1, JIS X 0208 row-cell encoding, horizontal. + H, + + // ── Adobe-CNS1 (Traditional Chinese) ── Hong Kong SCS ── + /// `HKscs-B5-H` — Adobe-CNS1, Hong Kong SCS (Big Five with HKSCS extensions), horizontal. + HKscsB5H, + /// `HKscs-B5-V` — Adobe-CNS1, Hong Kong SCS (Big Five with HKSCS extensions), vertical. + HKscsB5V, + + // ── Adobe-Identity ── + /// `Identity-H` — Adobe-Identity, two-byte identity mapping, horizontal. + /// Character codes map directly to CIDs (i.e. CID = character code). + IdentityH, + /// `Identity-V` — Adobe-Identity, two-byte identity mapping, vertical. + /// Character codes map directly to CIDs (i.e. CID = character code). + IdentityV, + + // ── Adobe-Korea1 (Korean) ── + /// `KSC-EUC-H` — Adobe-Korea1, KS X 1001:1992 EUC-KR encoding, horizontal. + KscEucH, + /// `KSC-EUC-V` — Adobe-Korea1, KS X 1001:1992 EUC-KR encoding, vertical. + KscEucV, + /// `KSCms-UHC-H` — Adobe-Korea1, Microsoft UHC (Unified Hangul Code, code page 949), horizontal. + KscmsUhcH, + /// `KSCms-UHC-HW-H` — Adobe-Korea1, Microsoft UHC with half-width Roman, horizontal. + KscmsUhcHwH, + /// `KSCms-UHC-HW-V` — Adobe-Korea1, Microsoft UHC with half-width Roman, vertical. + KscmsUhcHwV, + /// `KSCms-UHC-V` — Adobe-Korea1, Microsoft UHC (Unified Hangul Code, code page 949), vertical. + KscmsUhcV, + /// `KSCpc-EUC-H` — Adobe-Korea1, Mac KS X 1001:1992 EUC-KR encoding, horizontal. + KscpcEucH, + + // ── Adobe-CNS1 (Traditional Chinese) ── Unicode encodings ── + /// `UniCNS-UCS2-H` — Adobe-CNS1, Unicode UCS-2 encoding, horizontal. + UniCnsUcs2H, + /// `UniCNS-UCS2-V` — Adobe-CNS1, Unicode UCS-2 encoding, vertical. + UniCnsUcs2V, + /// `UniCNS-UTF16-H` — Adobe-CNS1, Unicode UTF-16 encoding, horizontal. + UniCnsUtf16H, + /// `UniCNS-UTF16-V` — Adobe-CNS1, Unicode UTF-16 encoding, vertical. + UniCnsUtf16V, + + // ── Adobe-GB1 (Simplified Chinese) ── Unicode encodings ── + /// `UniGB-UCS2-H` — Adobe-GB1, Unicode UCS-2 encoding, horizontal. + UniGbUcs2H, + /// `UniGB-UCS2-V` — Adobe-GB1, Unicode UCS-2 encoding, vertical. + UniGbUcs2V, + /// `UniGB-UTF16-H` — Adobe-GB1, Unicode UTF-16 encoding, horizontal. + UniGbUtf16H, + /// `UniGB-UTF16-V` — Adobe-GB1, Unicode UTF-16 encoding, vertical. + UniGbUtf16V, + + // ── Adobe-Japan1 (Japanese) ── Unicode encodings ── + /// `UniJIS-UCS2-H` — Adobe-Japan1, Unicode UCS-2 encoding, horizontal. + UniJisUcs2H, + /// `UniJIS-UCS2-HW-H` — Adobe-Japan1, Unicode UCS-2 with half-width Roman, horizontal. + UniJisUcs2HwH, + /// `UniJIS-UCS2-HW-V` — Adobe-Japan1, Unicode UCS-2 with half-width Roman, vertical. + UniJisUcs2HwV, + /// `UniJIS-UCS2-V` — Adobe-Japan1, Unicode UCS-2 encoding, vertical. + UniJisUcs2V, + /// `UniJIS-UTF16-H` — Adobe-Japan1, Unicode UTF-16 encoding, horizontal. + UniJisUtf16H, + /// `UniJIS-UTF16-V` — Adobe-Japan1, Unicode UTF-16 encoding, vertical. + UniJisUtf16V, + + // ── Adobe-Korea1 (Korean) ── Unicode encodings ── + /// `UniKS-UCS2-H` — Adobe-Korea1, Unicode UCS-2 encoding, horizontal. + UniKsUcs2H, + /// `UniKS-UCS2-V` — Adobe-Korea1, Unicode UCS-2 encoding, vertical. + UniKsUcs2V, + /// `UniKS-UTF16-H` — Adobe-Korea1, Unicode UTF-16 encoding, horizontal. + UniKsUtf16H, + /// `UniKS-UTF16-V` — Adobe-Korea1, Unicode UTF-16 encoding, vertical. + UniKsUtf16V, + + // ── Adobe-Japan1 (Japanese) ── JIS encoding ── + /// `V` — Adobe-Japan1, JIS X 0208 row-cell encoding, vertical. + V, + + /// A custom (non-predefined) `CMap` name. + Custom(&'a [u8]), +} + +impl<'a> CMapName<'a> { + /// Create a `CMapType` from raw bytes. + pub fn from_bytes(name: &'a [u8]) -> Self { + match name { + b"83pv-RKSJ-H" => Self::N83pvRksjH, + b"90ms-RKSJ-H" => Self::N90msRksjH, + b"90ms-RKSJ-V" => Self::N90msRksjV, + b"90msp-RKSJ-H" => Self::N90mspRksjH, + b"90msp-RKSJ-V" => Self::N90mspRksjV, + b"90pv-RKSJ-H" => Self::N90pvRksjH, + b"Add-RKSJ-H" => Self::AddRksjH, + b"Add-RKSJ-V" => Self::AddRksjV, + b"Adobe-CNS1-UCS2" => Self::AdobeCns1Ucs2, + b"Adobe-GB1-UCS2" => Self::AdobeGb1Ucs2, + b"Adobe-Japan1-UCS2" => Self::AdobeJapan1Ucs2, + b"Adobe-Korea1-UCS2" => Self::AdobeKorea1Ucs2, + b"B5pc-H" => Self::B5pcH, + b"B5pc-V" => Self::B5pcV, + b"CNS-EUC-H" => Self::CnsEucH, + b"CNS-EUC-V" => Self::CnsEucV, + b"ETen-B5-H" => Self::ETenB5H, + b"ETen-B5-V" => Self::ETenB5V, + b"ETenms-B5-H" => Self::ETenmsB5H, + b"ETenms-B5-V" => Self::ETenmsB5V, + b"EUC-H" => Self::EucH, + b"EUC-V" => Self::EucV, + b"Ext-RKSJ-H" => Self::ExtRksjH, + b"Ext-RKSJ-V" => Self::ExtRksjV, + b"GB-EUC-H" => Self::GbEucH, + b"GB-EUC-V" => Self::GbEucV, + b"GBK-EUC-H" => Self::GbkEucH, + b"GBK-EUC-V" => Self::GbkEucV, + b"GBK2K-H" => Self::Gbk2kH, + b"GBK2K-V" => Self::Gbk2kV, + b"GBKp-EUC-H" => Self::GbkpEucH, + b"GBKp-EUC-V" => Self::GbkpEucV, + b"GBpc-EUC-H" => Self::GbpcEucH, + b"GBpc-EUC-V" => Self::GbpcEucV, + b"H" => Self::H, + b"HKscs-B5-H" => Self::HKscsB5H, + b"HKscs-B5-V" => Self::HKscsB5V, + b"Identity-H" => Self::IdentityH, + b"Identity-V" => Self::IdentityV, + b"KSC-EUC-H" => Self::KscEucH, + b"KSC-EUC-V" => Self::KscEucV, + b"KSCms-UHC-H" => Self::KscmsUhcH, + b"KSCms-UHC-HW-H" => Self::KscmsUhcHwH, + b"KSCms-UHC-HW-V" => Self::KscmsUhcHwV, + b"KSCms-UHC-V" => Self::KscmsUhcV, + b"KSCpc-EUC-H" => Self::KscpcEucH, + b"UniCNS-UCS2-H" => Self::UniCnsUcs2H, + b"UniCNS-UCS2-V" => Self::UniCnsUcs2V, + b"UniCNS-UTF16-H" => Self::UniCnsUtf16H, + b"UniCNS-UTF16-V" => Self::UniCnsUtf16V, + b"UniGB-UCS2-H" => Self::UniGbUcs2H, + b"UniGB-UCS2-V" => Self::UniGbUcs2V, + b"UniGB-UTF16-H" => Self::UniGbUtf16H, + b"UniGB-UTF16-V" => Self::UniGbUtf16V, + b"UniJIS-UCS2-H" => Self::UniJisUcs2H, + b"UniJIS-UCS2-HW-H" => Self::UniJisUcs2HwH, + b"UniJIS-UCS2-HW-V" => Self::UniJisUcs2HwV, + b"UniJIS-UCS2-V" => Self::UniJisUcs2V, + b"UniJIS-UTF16-H" => Self::UniJisUtf16H, + b"UniJIS-UTF16-V" => Self::UniJisUtf16V, + b"UniKS-UCS2-H" => Self::UniKsUcs2H, + b"UniKS-UCS2-V" => Self::UniKsUcs2V, + b"UniKS-UTF16-H" => Self::UniKsUtf16H, + b"UniKS-UTF16-V" => Self::UniKsUtf16V, + b"V" => Self::V, + _ => Self::Custom(name), + } + } + + /// Convert the `CMapType` back to its raw byte representation. + pub fn to_bytes(&self) -> &[u8] { + match self { + Self::N83pvRksjH => b"83pv-RKSJ-H", + Self::N90msRksjH => b"90ms-RKSJ-H", + Self::N90msRksjV => b"90ms-RKSJ-V", + Self::N90mspRksjH => b"90msp-RKSJ-H", + Self::N90mspRksjV => b"90msp-RKSJ-V", + Self::N90pvRksjH => b"90pv-RKSJ-H", + Self::AddRksjH => b"Add-RKSJ-H", + Self::AddRksjV => b"Add-RKSJ-V", + Self::AdobeCns1Ucs2 => b"Adobe-CNS1-UCS2", + Self::AdobeGb1Ucs2 => b"Adobe-GB1-UCS2", + Self::AdobeJapan1Ucs2 => b"Adobe-Japan1-UCS2", + Self::AdobeKorea1Ucs2 => b"Adobe-Korea1-UCS2", + Self::B5pcH => b"B5pc-H", + Self::B5pcV => b"B5pc-V", + Self::CnsEucH => b"CNS-EUC-H", + Self::CnsEucV => b"CNS-EUC-V", + Self::ETenB5H => b"ETen-B5-H", + Self::ETenB5V => b"ETen-B5-V", + Self::ETenmsB5H => b"ETenms-B5-H", + Self::ETenmsB5V => b"ETenms-B5-V", + Self::EucH => b"EUC-H", + Self::EucV => b"EUC-V", + Self::ExtRksjH => b"Ext-RKSJ-H", + Self::ExtRksjV => b"Ext-RKSJ-V", + Self::GbEucH => b"GB-EUC-H", + Self::GbEucV => b"GB-EUC-V", + Self::GbkEucH => b"GBK-EUC-H", + Self::GbkEucV => b"GBK-EUC-V", + Self::Gbk2kH => b"GBK2K-H", + Self::Gbk2kV => b"GBK2K-V", + Self::GbkpEucH => b"GBKp-EUC-H", + Self::GbkpEucV => b"GBKp-EUC-V", + Self::GbpcEucH => b"GBpc-EUC-H", + Self::GbpcEucV => b"GBpc-EUC-V", + Self::H => b"H", + Self::HKscsB5H => b"HKscs-B5-H", + Self::HKscsB5V => b"HKscs-B5-V", + Self::IdentityH => b"Identity-H", + Self::IdentityV => b"Identity-V", + Self::KscEucH => b"KSC-EUC-H", + Self::KscEucV => b"KSC-EUC-V", + Self::KscmsUhcH => b"KSCms-UHC-H", + Self::KscmsUhcHwH => b"KSCms-UHC-HW-H", + Self::KscmsUhcHwV => b"KSCms-UHC-HW-V", + Self::KscmsUhcV => b"KSCms-UHC-V", + Self::KscpcEucH => b"KSCpc-EUC-H", + Self::UniCnsUcs2H => b"UniCNS-UCS2-H", + Self::UniCnsUcs2V => b"UniCNS-UCS2-V", + Self::UniCnsUtf16H => b"UniCNS-UTF16-H", + Self::UniCnsUtf16V => b"UniCNS-UTF16-V", + Self::UniGbUcs2H => b"UniGB-UCS2-H", + Self::UniGbUcs2V => b"UniGB-UCS2-V", + Self::UniGbUtf16H => b"UniGB-UTF16-H", + Self::UniGbUtf16V => b"UniGB-UTF16-V", + Self::UniJisUcs2H => b"UniJIS-UCS2-H", + Self::UniJisUcs2HwH => b"UniJIS-UCS2-HW-H", + Self::UniJisUcs2HwV => b"UniJIS-UCS2-HW-V", + Self::UniJisUcs2V => b"UniJIS-UCS2-V", + Self::UniJisUtf16H => b"UniJIS-UTF16-H", + Self::UniJisUtf16V => b"UniJIS-UTF16-V", + Self::UniKsUcs2H => b"UniKS-UCS2-H", + Self::UniKsUcs2V => b"UniKS-UCS2-V", + Self::UniKsUtf16H => b"UniKS-UTF16-H", + Self::UniKsUtf16V => b"UniKS-UTF16-V", + Self::V => b"V", + Self::Custom(name) => name, + } + } +} + +/// Let's limit the number of nested `usecmap` references to 16. +const MAX_NESTING_DEPTH: u32 = 16; + +/// A parsed cmap. +#[derive(Debug, Clone)] +pub struct CMap { + metadata: Metadata, + // Note that we don't actually use this, because Acrobat _seems_ to ignore + // it, too. + _codespace_ranges: Vec, + cid_ranges: PartitionedRanges, + notdef_ranges: PartitionedRanges, + bf_entries: Vec, + base: Option>, +} + +impl CMap { + /// Parse a cmap from raw bytes. + /// + /// The `get_cmap` callback is used to recursively resolve cmaps that + /// are referenced via `usecmap`. + pub fn parse<'a>( + data: &[u8], + get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, + ) -> Option { + parse::parse_inner(data, get_cmap, 0) + } + + /// Create an Identity-H cmap. + pub fn identity_h() -> Self { + Self::identity(WritingMode::Horizontal, b"Identity-H") + } + + /// Create an Identity-V cmap. + pub fn identity_v() -> Self { + Self::identity(WritingMode::Vertical, b"Identity-V") + } + + fn identity(writing_mode: WritingMode, name: &[u8]) -> Self { + Self { + metadata: Metadata { + character_collection: Some(CharacterCollection { + family: CidFamily::AdobeIdentity, + supplement: 0, + }), + name: Some(Vec::from(name)), + writing_mode: Some(writing_mode), + }, + _codespace_ranges: Vec::new(), + cid_ranges: { + let mut r = PartitionedRanges::new(); + r.push( + 2, + CidRange { + range: Range { + start: 0, + end: 0xFFFF, + }, + cid_start: 0, + }, + ); + r + }, + notdef_ranges: PartitionedRanges::new(), + bf_entries: Vec::new(), + base: None, + } + } + + /// Return the metadata of this cmap. + pub fn metadata(&self) -> &Metadata { + &self.metadata + } + + /// Look up the CID code of a character code. + /// + /// Returns `None` if the code does not match any range for the given byte length. + pub fn lookup_cid_code(&self, code: u32, byte_len: u8) -> Option { + // Note that, in theory, we are supposed to first check the code space range + // whether the entry exists in the first place. However, from my experiments + // Acrobat mostly seems to ignore this, so we do that as well. + + let cid_ranges = self.cid_ranges.get(byte_len)?; + let notdef_ranges = self.notdef_ranges.get(byte_len)?; + + if let Some(entry) = find_in_ranges(cid_ranges, code) { + let offset = code.checked_sub(entry.range.start)?; + return entry.cid_start.checked_add(offset); + } else if let Some(entry) = find_in_ranges(notdef_ranges, code) { + // For `.notdef` ranges, all codes map to the same `.notdef` CID, so + // no adding of the offset here. + return Some(entry.cid_start); + } + + // See pdfjs_bug920426, it uses bf chars for encoding the characters + // of a text-showing operator, so try that as well. We don't want to + // recurse though, only check the bf chars of this level. + if let Some(BfString::Char(lookup)) = self.lookup_bf_string_inner(code, false) { + return Some(lookup as u32); + } + + // If we still haven't found anything, check the base cmap. + self.base + .as_ref() + .and_then(|b| b.lookup_cid_code(code, byte_len)) + } + + /// Look up a bf string in the cmap. This is usually + /// used for mapping character codes to Unicode codepoints in a + /// `ToUnicode` cmap. + /// + /// Returns `None` if no mapping is available. + pub fn lookup_bf_string(&self, code: u32) -> Option { + self.lookup_bf_string_inner(code, true) + } + + fn lookup_bf_string_inner(&self, code: u32, recurse: bool) -> Option { + if let Some(entry) = find_in_ranges(&self.bf_entries, code) { + let offset = u16::try_from(code - entry.range.start).ok()?; + + fn decode_utf16(units: &[u16]) -> Option { + let mut iter = core::char::decode_utf16(units.iter().copied()); + let first = iter.next()?.ok()?; + + if iter.next().is_none() { + Some(BfString::Char(first)) + } else { + let s = String::from_utf16(units).ok()?; + Some(BfString::String(s)) + } + } + + return if offset == 0 { + Some(decode_utf16(&entry.dst_base)?) + } else { + let mut units = entry.dst_base.clone(); + *units.last_mut()? = units.last()?.checked_add(offset)?; + Some(decode_utf16(&units)?) + }; + } + + if recurse { + self.base.as_ref()?.lookup_bf_string(code) + } else { + None + } + } +} + +trait HasRange { + fn range(&self) -> &Range; +} + +fn find_in_ranges(entries: &[T], code: u32) -> Option<&T> { + let idx = entries + .binary_search_by(|entry| { + let r = entry.range(); + if code < r.start { + core::cmp::Ordering::Greater + } else if code > r.end { + core::cmp::Ordering::Less + } else { + core::cmp::Ordering::Equal + } + }) + .ok()?; + + Some(&entries[idx]) +} + +/// A range with a start and end code. +#[derive(Debug, Clone)] +pub(crate) struct Range { + pub(crate) start: u32, + pub(crate) end: u32, +} + +/// A range of character codes mapped to CIDs. +#[derive(Debug, Clone)] +pub struct CidRange { + pub(crate) range: Range, + pub(crate) cid_start: Cid, +} + +impl HasRange for CidRange { + fn range(&self) -> &Range { + &self.range + } +} + +#[derive(Debug, Clone)] +pub(crate) struct PartitionedRanges { + buckets: [Vec; 4], +} + +impl PartitionedRanges { + pub(crate) fn new() -> Self { + Self { + buckets: [Vec::new(), Vec::new(), Vec::new(), Vec::new()], + } + } + + // PdfCraft patch: needed by the truncated-stream guard in parse.rs. + pub(crate) fn is_empty(&self) -> bool { + self.buckets.iter().all(|b| b.is_empty()) + } + + pub(crate) fn push(&mut self, byte_len: usize, range: CidRange) { + if let Some(bucket) = byte_len + .checked_sub(1) + .and_then(|i| self.buckets.get_mut(i)) + { + bucket.push(range); + } + } + + pub(crate) fn get(&self, byte_len: u8) -> Option<&[CidRange]> { + let idx = (byte_len as usize).checked_sub(1)?; + self.buckets.get(idx).map(|v| v.as_slice()) + } + + pub(crate) fn sort(&mut self) { + for bucket in &mut self.buckets { + bucket.sort_by(|a, b| a.range.start.cmp(&b.range.start)); + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct BfRange { + pub(crate) range: Range, + pub(crate) dst_base: Vec, +} + +impl HasRange for BfRange { + fn range(&self) -> &Range { + &self.range + } +} + +/// A codespace range defining valid character code byte sequences. +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub(crate) struct CodespaceRange { + pub(crate) number_bytes: u8, + pub(crate) low: u32, + pub(crate) high: u32, +} + +/// A Unicode value decoded from a cmap. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BfString { + /// A single character. + Char(char), + /// A UTF-8 string. + String(String), +} + +/// Metadata extracted from a cmap file. +#[derive(Debug, Clone)] +pub struct Metadata { + /// The referenced character collection. + pub character_collection: Option, + /// The cmap name. + pub name: Option>, + /// The writing mode. + pub writing_mode: Option, +} + +/// The registry+ordering family of a CID character collection. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CidFamily { + /// Adobe-Japan1 + AdobeJapan1, + /// Adobe-GB1 + AdobeGB1, + /// Adobe-CNS1 + AdobeCNS1, + /// Adobe-Korea1 + AdobeKorea1, + /// Adobe-Identity + AdobeIdentity, + /// A non-predefined registry/ordering pair. + Custom { + /// The registry name. + registry: Vec, + /// The ordering name. + ordering: Vec, + }, +} + +impl CidFamily { + /// Create a `CidFamily` from raw registry and ordering byte strings. + pub fn from_registry_ordering(registry: &[u8], ordering: &[u8]) -> Self { + if registry == b"Adobe" { + match ordering { + b"Japan1" => Self::AdobeJapan1, + b"GB1" => Self::AdobeGB1, + b"CNS1" => Self::AdobeCNS1, + b"Korea1" => Self::AdobeKorea1, + b"Identity" => Self::AdobeIdentity, + _ => Self::Custom { + registry: registry.to_vec(), + ordering: ordering.to_vec(), + }, + } + } else { + Self::Custom { + registry: registry.to_vec(), + ordering: ordering.to_vec(), + } + } + } + + /// Return the predefined UTF-16 `CMap` that maps Unicode code points to CIDs + /// for this family, if one exists. + pub fn unicode_cmap(&self) -> Option> { + match self { + Self::AdobeJapan1 => Some(CMapName::UniJisUtf16H), + Self::AdobeGB1 => Some(CMapName::UniGbUtf16H), + Self::AdobeCNS1 => Some(CMapName::UniCnsUtf16H), + Self::AdobeKorea1 => Some(CMapName::UniKsUtf16H), + Self::AdobeIdentity | Self::Custom { .. } => None, + } + } + + /// Return the `UCS2` cmap corresponding to the given character collection. + pub fn ucs2_cmap(&self) -> Option> { + match self { + Self::AdobeJapan1 => Some(CMapName::AdobeJapan1Ucs2), + Self::AdobeGB1 => Some(CMapName::AdobeGb1Ucs2), + Self::AdobeCNS1 => Some(CMapName::AdobeCns1Ucs2), + Self::AdobeKorea1 => Some(CMapName::AdobeKorea1Ucs2), + Self::AdobeIdentity | Self::Custom { .. } => None, + } + } +} + +/// A CID character collection identifying the character set and ordering. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CharacterCollection { + /// The registry+ordering family. + pub family: CidFamily, + /// The supplement number. + pub supplement: i32, +} + +/// The writing mode of a cmap. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WritingMode { + /// Horizontal writing mode. + #[default] + Horizontal, + /// Vertical writing mode. + Vertical, +} + +#[cfg(test)] +mod tests { + use super::*; + + // Note that those cmaps might not be completely valid according to the rules + // of cmap/Postscript, but since our parser is very lenient and doesn't run a real + // interpreter we can shorten them by a lot. + + const PREAMBLE: &[u8] = br#"/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Test def +/WMode 0 def +2 begincodespacerange +<00> +<0000> +endcodespacerange +"#; + + fn parse_with_preamble(body: &[u8]) -> CMap { + let mut data = Vec::new(); + data.extend_from_slice(PREAMBLE); + data.extend_from_slice(body); + CMap::parse(&data, |_| None).unwrap() + } + + #[test] + fn metadata_parsing() { + let data = br#" +/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 6 def +end def +/CMapName /Adobe-Japan1-H def +/CMapType 1 def +/WMode 0 def +endcmap"#; + + let cmap = CMap::parse(data, |_| None).unwrap(); + let cc = cmap.metadata().character_collection.as_ref().unwrap(); + assert_eq!(cc.family, CidFamily::AdobeJapan1); + assert_eq!(cc.supplement, 6); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Adobe-Japan1-H".as_slice()) + ); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Horizontal)); + } + + #[test] + fn vertical_writing_mode() { + let data = br#" +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 6 def +end def +/CMapName /Adobe-Japan1-V def +/WMode 1 def +"#; + + let cmap = CMap::parse(data, |_| None).unwrap(); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Adobe-Japan1-V".as_slice()) + ); + } + + #[test] + fn cid_range_lookup() { + let cmap = parse_with_preamble( + br#" +3 begincidrange +<0000> <00FF> 0 +<0100> <01FF> 256 +<8140> <817E> 633 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0042, 2), Some(0x42)); + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), Some(0xFF)); + + assert_eq!(cmap.lookup_cid_code(0x0100, 2), Some(256)); + assert_eq!(cmap.lookup_cid_code(0x01FF, 2), Some(511)); + + assert_eq!(cmap.lookup_cid_code(0x8140, 2), Some(633)); + assert_eq!(cmap.lookup_cid_code(0x817E, 2), Some(633 + 62)); + } + + #[test] + fn cid_char_lookup() { + let cmap = parse_with_preamble( + br#" +3 begincidchar +<03> 1 +<04> 2 +<20> 50 +endcidchar +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x03, 1), Some(1)); + assert_eq!(cmap.lookup_cid_code(0x04, 1), Some(2)); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(50)); + } + + #[test] + fn lookup_miss() { + let cmap = parse_with_preamble( + br#" +1 begincidrange +<0100> <01FF> 0 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), None); + assert_eq!(cmap.lookup_cid_code(0x0200, 2), None); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), None); + } + + #[test] + fn multiple_sections() { + let cmap = parse_with_preamble( + br#" +2 begincidrange +<0000> <00FF> 0 +<0100> <01FF> 256 +endcidrange +1 begincidchar +<0200> 600 +endcidchar +1 begincidrange +<8140> <817E> 633 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0100, 2), Some(256)); + assert_eq!(cmap.lookup_cid_code(0x0200, 2), Some(600)); + assert_eq!(cmap.lookup_cid_code(0x8140, 2), Some(633)); + } + + #[test] + fn single_byte_codes() { + let cmap = parse_with_preamble( + br#" +2 begincidrange +<00> <7F> 0 +<80> 200 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x00, 1), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0x80, 1), Some(200)); + assert_eq!(cmap.lookup_cid_code(0xFF, 1), Some(200 + 127)); + } + + #[test] + fn dict_style_cidsysteminfo() { + let data = br#" +/CIDInit /ProcSet findresource begin +10 dict begin +begincmap +/CIDSystemInfo +<< /Registry (Adobe) +/Ordering (UCS) +/Supplement 0 +>> def +/CMapName /Adobe-Identity-UCS def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +2 beginbfchar +<001F> +<002A> +endbfchar +endcmap +CMapName currentdict /CMap defineresource pop +end +end +"#; + let cmap = CMap::parse(data, |_| None).unwrap(); + let cc = cmap.metadata().character_collection.as_ref().unwrap(); + assert_eq!( + cc.family, + CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"UCS".to_vec(), + } + ); + assert_eq!(cc.supplement, 0); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Adobe-Identity-UCS".as_slice()) + ); + assert_eq!( + cmap.lookup_bf_string(0x001F), + Some(BfString::Char('\u{F049}')) + ); + assert_eq!( + cmap.lookup_bf_string(0x002A), + Some(BfString::Char('\u{F055}')) + ); + } + + #[test] + fn usecmap_chaining() { + let base_data = br#" +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Base def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0000> <00FF> 0 +endcidrange +"#; + + let child_data = br#" +/Base usecmap +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Child def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0100> <01FF> 256 +endcidrange +"#; + + let cmap = CMap::parse(child_data, |name| { + if name.to_bytes() == b"Base" { + Some(base_data.as_slice()) + } else { + None + } + }) + .unwrap(); + + assert_eq!(cmap.lookup_cid_code(0x0100, 2), Some(256)); + assert_eq!(cmap.lookup_cid_code(0x01FF, 2), Some(511)); + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), Some(0xFF)); + + assert_eq!(cmap.lookup_cid_code(0x0200, 2), None); + } + + #[test] + fn usecmap_partial_override() { + let base_data = br#" +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Base def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0000> <00FF> 0 +endcidrange +"#; + + let child_data = br#" +/Base usecmap +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Child def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0040> <007F> 500 +endcidrange +"#; + + let cmap = CMap::parse(child_data, |name| { + if name.to_bytes() == b"Base" { + Some(base_data.as_slice()) + } else { + None + } + }) + .unwrap(); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x003F, 2), Some(0x3F)); + assert_eq!(cmap.lookup_cid_code(0x0040, 2), Some(500)); + assert_eq!(cmap.lookup_cid_code(0x007F, 2), Some(563)); + assert_eq!(cmap.lookup_cid_code(0x0080, 2), Some(0x80)); + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), Some(0xFF)); + } + + #[test] + fn notdef_char_lookup() { + let cmap = parse_with_preamble( + br#" +2 beginnotdefchar +<03> 10 +<20> 20 +endnotdefchar +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x03, 1), Some(10)); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(20)); + assert_eq!(cmap.lookup_cid_code(0x04, 1), None); + } + + #[test] + fn notdef_range_lookup() { + let cmap = parse_with_preamble( + br#" +1 beginnotdefrange +<0000> <001F> 100 +endnotdefrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(100)); + assert_eq!(cmap.lookup_cid_code(0x0001, 2), Some(100)); + assert_eq!(cmap.lookup_cid_code(0x001F, 2), Some(100)); + assert_eq!(cmap.lookup_cid_code(0x0020, 2), None); + } + + #[test] + fn bfchar_lookup() { + let cmap = parse_with_preamble( + br#" +2 beginbfchar +<0041> <0048> +<0042> <0065> +endbfchar +"#, + ); + + assert_eq!(cmap.lookup_bf_string(0x0041), Some(BfString::Char('H'))); + assert_eq!(cmap.lookup_bf_string(0x0042), Some(BfString::Char('e'))); + assert_eq!(cmap.lookup_bf_string(0x0043), None); + } + + #[test] + fn bfchar_ligature() { + let cmap = parse_with_preamble( + br#" +1 beginbfchar +<005F> <00660066> +endbfchar +"#, + ); + + assert_eq!( + cmap.lookup_bf_string(0x005F), + Some(BfString::String(String::from("ff"))) + ); + } + + // PdfCraft patch: malformed pieces of a CMap are skipped, not fatal - the reading + // path used to discard the whole CMap and fall back to the font encoding for every + // code, so search and search-redaction missed text the edit layer could see (#3177). + + #[test] + fn bad_bfchar_entry_is_skipped() { + let cmap = parse_with_preamble( + br#" +2 beginbfchar +<41> +<42> <0059> +endbfchar +"#, + ); + assert_eq!(cmap.lookup_bf_string(0x41), None); + assert_eq!( + cmap.lookup_bf_string(0x42), + Some(BfString::Char('Y')) + ); + } + + #[test] + fn stream_cut_off_inside_a_block_keeps_the_entries_before_it() { + let cmap = parse_with_preamble(b"1 beginbfchar <41> <0058>\n<42> <00"); + assert_eq!(cmap.lookup_bf_string(0x41), Some(BfString::Char('X'))); + assert_eq!(cmap.lookup_bf_string(0x42), None); + } + + #[test] + fn truncated_stream_with_no_entries_reports_failure() { + // The tolerant parser keeps collected entries, but a stream that + // breaks before any entry must still report failure so callers + // fall back to the font's own encoding. + assert!(CMap::parse(b"<00", |_| None).is_none()); + } + + #[test] + fn truncated_stream_with_only_metadata_reports_failure() { + // Character-collection metadata alone is not a usable CMap: an empty + // metadata-only map would block the caller's fallback paths, so a + // truncated stream with no mappings must report failure here too. + assert!(CMap::parse( + b"/Registry (Adobe) /Ordering (Japan1) /Supplement 0 <00", + |_| None + ) + .is_none()); + } + + #[test] + fn unresolved_usecmap_with_no_mappings_reports_failure() { + // A stream whose only content is a `usecmap` reference that cannot be + // resolved yields no mappings at all; returning an empty map here + // would block the caller's encoding fallback paths, so it must + // report failure exactly as a full parse failure did before. + assert!(CMap::parse(b"/Bogus usecmap", |_| None).is_none()); + } + + #[test] + fn unresolved_usecmap_keeps_local_mappings() { + // The same unresolved reference must not discard mappings the stream + // carries itself: only the missing base is dropped. + let cmap = CMap::parse( + b"/Bogus usecmap 1 beginbfchar <41> <0041> endbfchar", + |_| None, + ) + .expect("local mappings survive an unresolved usecmap"); + assert!(cmap.lookup_bf_string(0x41).is_some()); + } + + #[test] + fn bad_bfchar_code_keeps_later_entries_aligned() { + // The malformed 5-byte code still has a destination object; both + // must be skipped or every later pair shifts by one object. + let cmap = parse_with_preamble( + br#" +2 beginbfchar +<0102030405> <0041> +<42> <0059> +endbfchar +"#, + ); + assert_eq!(cmap.lookup_bf_string(0x41), None); + assert_eq!(cmap.lookup_bf_string(0x42), Some(BfString::Char('Y'))); + } + + #[test] + fn bfrange_array_stops_at_exhaustion() { + // One member for 256 codes: the array cannot be resynced, so the + // loop must stop rather than spin over the remaining codes. + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<0000> <00FF> [<0041>] +endbfrange +"#, + ); + assert_eq!(cmap.lookup_bf_string(0x00), Some(BfString::Char('A'))); + assert_eq!(cmap.lookup_bf_string(0x01), None); + } + + #[test] + fn unresolvable_usecmap_is_skipped() { + let cmap = parse_with_preamble( + br#" +/Bogus usecmap +1 beginbfchar +<41> <0058> +endbfchar +"#, + ); + assert_eq!( + cmap.lookup_bf_string(0x41), + Some(BfString::Char('X')) + ); + } + + #[test] + fn bfchar_surrogate_pair() { + let cmap = parse_with_preamble( + br#" +1 beginbfchar +<3A51> +endbfchar +"#, + ); + + assert_eq!( + cmap.lookup_bf_string(0x3A51), + Some(BfString::Char('\u{2003E}')) + ); + } + + #[test] + fn bfrange_incrementing() { + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<0000> <0004> <0041> +endbfrange +"#, + ); + + assert_eq!(cmap.lookup_bf_string(0x0000), Some(BfString::Char('A'))); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char('B'))); + assert_eq!(cmap.lookup_bf_string(0x0004), Some(BfString::Char('E'))); + assert_eq!(cmap.lookup_bf_string(0x0005), None); + } + + #[test] + fn bfrange_array() { + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<005F> <0061> [<00660066> <00660069> <0066006C>] +endbfrange +"#, + ); + + // ff, fi, fl ligatures + assert_eq!( + cmap.lookup_bf_string(0x005F), + Some(BfString::String(String::from("ff"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x0060), + Some(BfString::String(String::from("fi"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x0061), + Some(BfString::String(String::from("fl"))) + ); + } + + #[test] + fn unicode_lookup_miss() { + let cmap = parse_with_preamble( + br#" +1 beginbfchar +<0041> <0048> +endbfchar +"#, + ); + + assert_eq!(cmap.lookup_bf_string(0x0000), None); + assert_eq!(cmap.lookup_bf_string(0x0042), None); + } + + #[test] + fn identity_h() { + let cmap = CMap::identity_h(); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Identity-H".as_slice()) + ); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Horizontal)); + + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x0041)); + assert_eq!(cmap.lookup_cid_code(0x1234, 2), Some(0x1234)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + + assert_eq!(cmap.lookup_cid_code(0x0041, 1), None); + assert_eq!(cmap.lookup_cid_code(0x0041, 3), None); + } + + #[test] + fn identity_v() { + let cmap = CMap::identity_v(); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Identity-V".as_slice()) + ); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x0041)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + } + + #[test] + fn minimal_cmap_no_name_no_wmode() { + // Extracted from corpus PDF 0500013. + let data = br#" +/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CMapType 2 def +1 begincodespacerange +<00> +endcodespacerange +1 beginbfrange +<01><01><0020> +endbfrange +endcmap +"#; + let cmap = CMap::parse(data, |_| None).unwrap(); + assert_eq!(cmap.metadata().name, None); + assert_eq!(cmap.metadata().character_collection, None); + assert_eq!(cmap.metadata().writing_mode, None); + assert_eq!(cmap.lookup_bf_string(0x01), Some(BfString::Char(' '))); + } + + #[test] + fn registry_as_name() { + // Extracted from corpus PDF 0875241, uses names instead of strings for + // strings for metadata. + let data = br#" +/CIDSystemInfo +<< /Registry /ABCDEF+SimSun +/Ordering (pdfbeaninc) +/Supplement 0 +>> def +/CMapName /ABCDEF+SimSun def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +1 beginbfrange +<0000> <0000> <6881> +endbfrange +"#; + let cmap = CMap::parse(data, |_| None).unwrap(); + let cc = cmap.metadata().character_collection.as_ref().unwrap(); + assert_eq!( + cc.family, + CidFamily::Custom { + registry: b"ABCDEF+SimSun".to_vec(), + ordering: b"pdfbeaninc".to_vec(), + } + ); + assert_eq!(cc.supplement, 0); + assert_eq!( + cmap.lookup_bf_string(0x0000), + Some(BfString::Char('\u{6881}')) + ); + } + + #[test] + fn single_byte_bfrange_destination() { + // See for example corpus test case 0625248. + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<00> <7f> <00> +endbfrange +"#, + ); + + assert_eq!( + cmap.lookup_bf_string(0x00), + Some(BfString::Char('\u{0000}')) + ); + assert_eq!(cmap.lookup_bf_string(0x41), Some(BfString::Char('A'))); + assert_eq!( + cmap.lookup_bf_string(0x7f), + Some(BfString::Char('\u{007F}')) + ); + } +} + +#[cfg(all(test, feature = "embed-cmaps"))] +mod bcmap_tests { + use super::*; + + fn get_embedded_cmap(name: CMapName<'_>) -> Option<&'static [u8]> { + load_embedded(name) + } + + #[test] + fn embedded_h_cmap() { + let data = load_embedded(CMapName::H).expect("embedded H cmap not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse H cmap"); + assert_eq!(cmap.metadata().writing_mode, None); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 1, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x2121, 2), Some(633)); + assert_eq!(cmap.lookup_cid_code(0x2221, 2), Some(727)); + } + + #[test] + fn embedded_90ms_rksj_h() { + let data = + load_embedded(CMapName::N90msRksjH).expect("embedded 90ms-RKSJ-H cmap not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse 90ms-RKSJ-H cmap"); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 2, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(231)); + assert_eq!(cmap.lookup_cid_code(0x8140, 2), Some(633)); + } + + #[test] + fn embedded_v_cmap() { + let data = load_embedded(CMapName::V).expect("embedded V cmap not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse V cmap"); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 1, + }) + ); + // Inherited from base "H" via usecmap. + assert_eq!(cmap.lookup_cid_code(0x2121, 2), Some(633)); + } + + #[test] + fn embedded_gbk_euc_h() { + let data = load_embedded(CMapName::GbkEucH).expect("embedded GBK-EUC-H not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse GBK-EUC-H"); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeGB1, + supplement: 2, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(7716)); + assert_eq!(cmap.lookup_cid_code(0x21, 1), Some(814)); + assert_eq!(cmap.lookup_cid_code(0x7E, 1), Some(814 + 0x7E - 0x21)); + assert_eq!(cmap.lookup_cid_code(0xFE80, 2), Some(22094)); + assert_eq!(cmap.lookup_cid_code(0xFEA0, 2), Some(22094 + 0xA0 - 0x80)); + } + + #[test] + fn embedded_ksc_euc_h() { + let data = load_embedded(CMapName::KscEucH).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeKorea1, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(8094)); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(8094 + 0x41 - 0x20)); + assert_eq!(cmap.lookup_cid_code(0xA1A1, 2), Some(101)); + assert_eq!(cmap.lookup_cid_code(0xA1FE, 2), Some(101 + 0xFE - 0xA1)); + assert_eq!(cmap.lookup_cid_code(0xFDA1, 2), Some(7962)); + } + + #[test] + fn embedded_b5pc_h() { + let data = load_embedded(CMapName::B5pcH).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeCNS1, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(1)); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(1 + 0x41 - 0x20)); + assert_eq!(cmap.lookup_cid_code(0x80, 1), Some(61)); + assert_eq!(cmap.lookup_cid_code(0xD140, 2), Some(7251)); + assert_eq!(cmap.lookup_cid_code(0xD17E, 2), Some(7251 + 0x7E - 0x40)); + assert_eq!(cmap.lookup_cid_code(0xF9D5, 2), Some(13642 + 3)); + } + + #[test] + fn embedded_unijis_utf16_h() { + let data = load_embedded(CMapName::UniJisUtf16H).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 7, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 2), Some(1)); + assert_eq!(cmap.lookup_cid_code(0x41, 2), Some(1 + 0x41 - 0x20)); + assert_eq!(cmap.lookup_cid_code(0x5C, 2), Some(97)); + assert_eq!(cmap.lookup_cid_code(0x5BCC, 2), Some(3531)); + assert_eq!(cmap.lookup_cid_code(0xD884DF50, 4), Some(19130)); + } + + #[test] + fn embedded_identity_h() { + let data = load_embedded(CMapName::IdentityH).expect("embedded Identity-H not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse Identity-H cmap"); + assert_eq!(cmap.metadata().writing_mode, None); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeIdentity, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + } + + #[test] + fn embedded_identity_v() { + let data = load_embedded(CMapName::IdentityV).expect("embedded Identity-V not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse Identity-V cmap"); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeIdentity, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + } + + // Note: Some tests AI-generated, haven't double-checked them. + + #[test] + fn embedded_adobe_gb1_ucs2() { + let data = load_embedded(CMapName::AdobeGb1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_GB1_UCS2".to_vec(), + }, + supplement: 5, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x0063), + Some(BfString::Char('\u{00B7}')) + ); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char(' '))); + assert_eq!(cmap.lookup_bf_string(0x0022), Some(BfString::Char('A'))); + assert_eq!(cmap.lookup_bf_string(0x005F), Some(BfString::Char('~'))); + assert_eq!( + cmap.lookup_bf_string(0x560F), + Some(BfString::String(String::from("\u{90CE}\u{FE00}"))) + ); + } + + #[test] + fn embedded_adobe_japan1_ucs2() { + let data = load_embedded(CMapName::AdobeJapan1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_Japan1_UCS2".to_vec(), + }, + supplement: 7, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x003D), + Some(BfString::Char('\u{00A5}')) + ); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char(' '))); + assert_eq!(cmap.lookup_bf_string(0x003C), Some(BfString::Char('['))); + assert_eq!( + cmap.lookup_bf_string(0x0476), + Some(BfString::String(String::from("\u{82A6}\u{E0100}"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x265B), + Some(BfString::String(String::from("10/11"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x2E6B), + Some(BfString::String(String::from("オングストローム"))) + ); + } + + #[test] + fn embedded_adobe_korea1_ucs2() { + let data = load_embedded(CMapName::AdobeKorea1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_Korea1_UCS2".to_vec(), + }, + supplement: 2, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x0060), + Some(BfString::Char('\u{20A9}')) + ); + assert_eq!( + cmap.lookup_bf_string(0x2072), + Some(BfString::String(String::from("[10]"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x2073), + Some(BfString::String(String::from("[11]"))) + ); + } + + #[test] + fn embedded_adobe_cns1_ucs2() { + let data = load_embedded(CMapName::AdobeCns1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_CNS1_UCS2".to_vec(), + }, + supplement: 7, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x0060), + Some(BfString::Char('\u{00A9}')) + ); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char(' '))); + assert_eq!(cmap.lookup_bf_string(0x005F), Some(BfString::Char('~'))); + assert_eq!( + cmap.lookup_bf_string(0x36B0), + Some(BfString::Char('\u{200CC}')) + ); + } + + #[test] + fn embedded_eten_b5_h() { + let data = load_embedded(CMapName::ETenB5H).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeCNS1, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(13648)); + assert_eq!(cmap.lookup_cid_code(0x7E, 1), Some(13648 + 0x7E - 0x20)); + assert_eq!(cmap.lookup_cid_code(0xA140, 2), Some(99)); + assert_eq!(cmap.lookup_cid_code(0xA158, 2), Some(99 + 0x58 - 0x40)); + assert_eq!(cmap.lookup_cid_code(0xD040, 2), Some(7094)); + assert_eq!(cmap.lookup_cid_code(0xF9FE, 2), Some(14056 + 0xFE - 0xD6)); + } +} diff --git a/vendor/hayro-cmap/src/parse.rs b/vendor/hayro-cmap/src/parse.rs new file mode 100644 index 000000000..a93620927 --- /dev/null +++ b/vendor/hayro-cmap/src/parse.rs @@ -0,0 +1,469 @@ +use alloc::boxed::Box; +use alloc::vec::Vec; + +use hayro_postscript::{Object, Scanner}; + +#[cfg(feature = "embed-cmaps")] +use crate::bcmap; +use crate::{ + BfRange, CMap, CMapName, CharacterCollection, CidFamily, CidRange, CodespaceRange, + MAX_NESTING_DEPTH, Metadata, PartitionedRanges, Range, WritingMode, +}; + +struct Context { + buf: Vec, + get_cmap: F, +} + +pub(crate) fn parse_inner<'a>( + data: &[u8], + get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, + depth: u32, +) -> Option { + // Prevent stack overflow for malicious cmap files or circular references. + if depth >= MAX_NESTING_DEPTH { + return None; + } + + // Check if it's in our custom embedded cmap format. + #[cfg(feature = "embed-cmaps")] + if data.starts_with(b"bcmap") { + return bcmap::parse(data, get_cmap, depth); + } + + let mut scanner = Scanner::new(data); + let mut ctx = Context { + buf: Vec::new(), + get_cmap, + }; + let mut _codespace_ranges = Vec::new(); + let mut ranges = PartitionedRanges::new(); + let mut notdef_ranges = PartitionedRanges::new(); + let mut bf_entries = Vec::new(); + let mut base = None; + + let mut registry = None; + let mut ordering = None; + let mut supplement = None; + let mut cmap_name = None; + let mut writing_mode = None; + let mut last_name: Option> = None; + + // PdfCraft patch: track whether the scan was cut short. A CMap with an + // unparseable tail, including one that ends inside a `begin…` block, + // keeps the entries read so far (the block parsers push into the shared + // lists as they go) instead of being discarded wholesale; one that + // yielded nothing still reports failure. + let mut truncated = false; + + // PdfCraft patch: track a `usecmap` reference that could not be resolved + // or parsed. When the stream yields no mappings of its own, the caller + // must see failure rather than an empty map, so its encoding fallback + // paths run exactly as they did before the tolerant-usecmap change. + let mut usecmap_failed = false; + while !scanner.at_end() { + let Ok(obj) = scanner.parse_object() else { + truncated = true; + break; + }; + + let Object::Name(name) = &obj else { continue }; + + if name.is_literal() { + match name.as_str() { + // Strictly speaking, Registry and Ordering should be strings, + // but some PDF generators emit names instead, so be lenient + // and try both. + Some("Registry") => { + registry = parse_string_or_name(&mut scanner); + } + Some("Ordering") => { + ordering = parse_string_or_name(&mut scanner); + } + Some("Supplement") => { + supplement = scanner.parse_number().ok().map(|n| n.as_i32()); + } + Some("CMapName") => { + cmap_name = scanner.parse_name().ok().and_then(|n| n.decode().ok()); + } + Some("WMode") => { + writing_mode = parse_writing_mode(&mut scanner); + } + _ => { + last_name = name.decode().ok(); + } + } + } else { + match name.as_str() { + Some("begincodespacerange") => { + if parse_codespace_range(&mut scanner, &mut _codespace_ranges, &mut ctx).is_none() { + truncated = true; + break; + } + } + Some("begincidrange") => { + if parse_range(&mut scanner, &mut ranges, &mut ctx, "endcidrange").is_none() { + truncated = true; + break; + } + } + Some("begincidchar") => { + if parse_char(&mut scanner, &mut ranges, &mut ctx, "endcidchar").is_none() { + truncated = true; + break; + } + } + Some("beginnotdefrange") => { + if parse_range(&mut scanner, &mut notdef_ranges, &mut ctx, "endnotdefrange").is_none() { + truncated = true; + break; + } + } + Some("beginnotdefchar") => { + if parse_char(&mut scanner, &mut notdef_ranges, &mut ctx, "endnotdefchar").is_none() { + truncated = true; + break; + } + } + Some("beginbfchar") => { + if parse_bf_char(&mut scanner, &mut bf_entries, &mut ctx).is_none() { + truncated = true; + break; + } + } + Some("beginbfrange") => { + if parse_bf_range(&mut scanner, &mut bf_entries, &mut ctx).is_none() { + truncated = true; + break; + } + } + Some("usecmap") => { + // PdfCraft patch: an unresolvable or unparseable `usecmap` + // reference drops only the base, not the whole CMap, but + // is remembered so a stream that then yields no mappings + // at all still reports failure. + let resolved = last_name.as_deref().and_then(|name| { + (ctx.get_cmap)(CMapName::from_bytes(name)) + }); + match resolved { + Some(nested_data) => { + match parse_inner(nested_data, ctx.get_cmap.clone(), depth + 1) { + Some(nested) => base = Some(Box::new(nested)), + None => usecmap_failed = true, + } + } + None => usecmap_failed = true, + } + } + _ => {} + } + } + } + + + // Since we will use binary search for finding the correct entry, sort now. + ranges.sort(); + notdef_ranges.sort(); + bf_entries.sort_by(|a, b| a.range.start.cmp(&b.range.start)); + + // See PDFJS-3323, which has an invalid CIDSystemInfo entry. + // We ignore it if it's invalid. + let character_collection = if let (Some(registry), Some(ordering), Some(supplement)) = + (registry, ordering, supplement) + { + Some(CharacterCollection { + family: CidFamily::from_registry_ordering(®istry, &ordering), + supplement, + }) + } else { + None + }; + + let metadata = Metadata { + character_collection, + name: cmap_name, + writing_mode, + }; + + // PdfCraft patch: a CMap that was cut short or whose `usecmap` base could + // not be resolved, and that yielded no mappings of its own, still reports + // failure, so callers fall back to the font's own encoding exactly as + // before. + if (truncated || usecmap_failed) + && ranges.is_empty() + && notdef_ranges.is_empty() + && bf_entries.is_empty() + && base.is_none() + { + return None; + } + + Some(CMap { + metadata, + _codespace_ranges, + cid_ranges: ranges, + notdef_ranges, + bf_entries, + base, + }) +} + +fn parse_writing_mode(scanner: &mut Scanner<'_>) -> Option { + match scanner.parse_number().ok()?.as_i32() { + 0 => Some(WritingMode::Horizontal), + 1 => Some(WritingMode::Vertical), + _ => None, + } +} + +fn parse_string_or_name(scanner: &mut Scanner<'_>) -> Option> { + match scanner.parse_object().ok()? { + Object::String(s) => s.decode().ok(), + Object::Name(n) => n.decode().ok(), + _ => None, + } +} + +fn parse_codespace_range( + scanner: &mut Scanner<'_>, + ranges: &mut Vec, + ctx: &mut Context, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, "endcodespacerange") { + return Some(()); + } + + // PdfCraft patch: a malformed codespace entry is skipped, not fatal. + let Some(low) = extract_u32_code(&obj, &mut ctx.buf) else { continue }; + let Ok(n_bytes) = u8::try_from(ctx.buf.len()) else { continue }; + let Some(high) = read_u32_code(scanner, &mut ctx.buf) else { continue }; + + if ctx.buf.len() != usize::from(n_bytes) { + continue; + } + + ranges.push(CodespaceRange { + number_bytes: n_bytes, + low, + high, + }); + } +} + +fn parse_range( + scanner: &mut Scanner<'_>, + ranges: &mut PartitionedRanges, + ctx: &mut Context, + end_marker: &str, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, end_marker) { + return Some(()); + } + + // PdfCraft patch: a malformed range entry is skipped, not fatal. + let Some(start) = extract_u32_code(&obj, &mut ctx.buf) else { continue }; + let byte_len = ctx.buf.len(); + let Some(end) = read_u32_code(scanner, &mut ctx.buf) else { continue }; + let Some(cid_start) = scanner.parse_number().ok().and_then(|n| u32::try_from(n.as_i32()).ok()) else { continue }; + + ranges.push( + byte_len, + CidRange { + range: Range { start, end }, + cid_start, + }, + ); + } +} + +fn parse_char( + scanner: &mut Scanner<'_>, + ranges: &mut PartitionedRanges, + ctx: &mut Context, + end_marker: &str, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, end_marker) { + return Some(()); + } + + // PdfCraft patch: a malformed char entry is skipped, not fatal. + let Some(code) = extract_u32_code(&obj, &mut ctx.buf) else { continue }; + let byte_len = ctx.buf.len(); + let Some(cid_start) = scanner.parse_number().ok().and_then(|n| u32::try_from(n.as_i32()).ok()) else { continue }; + + ranges.push( + byte_len, + CidRange { + range: Range { + start: code, + end: code, + }, + cid_start, + }, + ); + } +} + +fn parse_bf_char( + scanner: &mut Scanner<'_>, + entries: &mut Vec, + ctx: &mut Context, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, "endbfchar") { + return Some(()); + } + + // PdfCraft patch: a malformed bfchar entry (e.g. a non-hex destination) + // is skipped, not fatal - the entries after it still apply. + let Some(code) = extract_u32_code(&obj, &mut ctx.buf) else { + // The malformed code is still followed by its destination + // object; skip it so later entries stay aligned. + let _ = scanner.parse_object(); + continue; + }; + let Ok(dst) = scanner.parse_string() else { continue }; + if dst.decode_into(&mut ctx.buf).is_err() { continue } + let Some(dst_base) = decode_be(&ctx.buf) else { continue }; + + entries.push(BfRange { + range: Range { + start: code, + end: code, + }, + dst_base, + }); + } +} + +fn parse_bf_range( + scanner: &mut Scanner<'_>, + entries: &mut Vec, + ctx: &mut Context, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, "endbfrange") { + return Some(()); + } + + // PdfCraft patch: a malformed bfrange entry is skipped, not fatal. + let Some(start) = extract_u32_code(&obj, &mut ctx.buf) else { + // Skip the range's end and destination objects too, so later + // entries stay aligned. + let _ = scanner.parse_object(); + let _ = scanner.parse_object(); + continue; + }; + let Some(end) = read_u32_code(scanner, &mut ctx.buf) else { + // Skip the destination object as well to stay aligned. + let _ = scanner.parse_object(); + continue; + }; + + let Ok(next) = scanner.parse_object() else { continue }; + + match &next { + Object::String(s) => { + if s.decode_into(&mut ctx.buf).is_err() { continue } + let Some(dst_base) = decode_be(&ctx.buf) else { continue }; + + entries.push(BfRange { + range: Range { start, end }, + dst_base, + }); + } + Object::Array(array) => { + let mut array_scanner = array.objects(); + + for code in start..=end { + // An exhausted or broken array cannot be resynced to a + // member boundary; stop instead of spinning over the + // remaining codes. A decodable-but-bad member still + // drops only itself. + let Ok(s) = array_scanner.parse_string() else { break }; + if s.decode_into(&mut ctx.buf).is_err() { continue } + let Some(dst_base) = decode_be(&ctx.buf) else { continue }; + + entries.push(BfRange { + range: Range { + start: code, + end: code, + }, + dst_base, + }); + } + } + _ => continue, + } + } +} + +/// Convert the buffer into native-endian u16, so that we can use `String::from_utf16`. +fn decode_be(bytes: &[u8]) -> Option> { + if bytes.is_empty() { + return None; + } + + let mut out = Vec::with_capacity(bytes.len().div_ceil(2)); + let mut i = 0; + + // My understanding is that the bf strings should always be UTF16-BE encoded, + // but it seems like some PDFs only have a single byte there? I guess we just + // pad them? Wasn't able to find anything specific in the specifications. + if !bytes.len().is_multiple_of(2) { + out.push(u16::from(bytes[0])); + i = 1; + } + + while i < bytes.len() { + out.push(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + i += 2; + } + + Some(out) +} + +#[inline] +fn read_u32_code(scanner: &mut Scanner<'_>, buf: &mut Vec) -> Option { + let s = scanner.parse_string().ok()?; + s.decode_into(buf).ok()?; + bytes_to_u32(buf) +} + +#[inline] +fn extract_u32_code(obj: &Object<'_>, buf: &mut Vec) -> Option { + let Object::String(s) = obj else { return None }; + s.decode_into(buf).ok()?; + bytes_to_u32(buf) +} + +#[inline] +fn bytes_to_u32(bytes: &[u8]) -> Option { + if bytes.is_empty() || bytes.len() > 4 { + return None; + } + + let mut val = 0_u32; + for &b in bytes { + val = (val << 8) | b as u32; + } + + Some(val) +} + +fn name_matches(obj: &Object<'_>, expected: &str) -> bool { + matches!(obj, Object::Name(name) if !name.is_literal() && name.as_str() == Some(expected)) +} diff --git a/vendor/hayro-syntax/src/content/mod.rs b/vendor/hayro-syntax/src/content/mod.rs index 4dfc9eb6b..886383ede 100644 --- a/vendor/hayro-syntax/src/content/mod.rs +++ b/vendor/hayro-syntax/src/content/mod.rs @@ -272,11 +272,12 @@ impl<'a> UntypedIter<'a> { self.reader.read_bytes(pos)?; if self.reader.peek_bytes(2) == Some(b"EI") { - // If the following character is not a whitespace character, then we are in a ASCII-85 stream. + // If the following character is a regular character, then the token + // is not `EI` (white space and delimiters both end it). if self .reader .peek_bytes(3) - .is_some_and(|b| !is_white_space_character(b[2])) + .is_some_and(|b| is_regular_character(b[2])) { self.reader.read_bytes(3)?; @@ -325,16 +326,21 @@ impl<'a> UntypedIter<'a> { find_reader.read_bytes(next_pos)?; if is_ei { - let analyze_data = &tail[..find_reader.offset()]; + // PdfCraft patch: a byte above 0x7F between the two "EI"s + // used to reject the candidate ("binary data in-between, so + // we for sure have not reached the end"). When the candidate + // is the real end, those bytes are the content stream that + // follows the image, and a content stream carries bytes above + // 0x7F inside its strings: WinAnsi text such as `(Grüße) Tj`, + // or the two-byte codes of any Type 0 font. A page whose text + // held one, with a capital "EI" in a later word (EINGANG, + // BEI, KLEIN), had no valid candidate left, so the image data + // ran to the end of the stream and nothing after the image + // was drawn or extracted. The operator check below is the + // discriminator, and `MAX_EI_CANDIDATES` already bounds how + // often it runs. - // If there is any binary data in-between, we for sure - // have not reached the end. - if analyze_data.iter().any(|c| !c.is_ascii()) { - self.reader.read_bytes(2)?; - continue 'outer; - } - - // Otherwise, the only possibility that we reached an + // The only possibility that we reached an // "EI", even though the previous one was valid, is // that it's part of a string in the content // stream that follows the inline image. Therefore, @@ -1052,6 +1058,64 @@ mod tests { assert_eq!(operators(data), [b"TJ".to_vec(), b"BI".to_vec(), b"q".to_vec(), b"Q".to_vec()]); } + #[test] + fn an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte() { + // `(Grüße)` in WinAnsi, then a word holding a capital "EI": both are everyday content, + // and the look-ahead used to read the non-ASCII bytes of the string as image data. + let data = b"BI /W 1 /H 1 /BPC 8 /CS /DeviceGray ID \x00 EI BT /F1 12 Tf (Gr\xFC\xDFe) Tj (EINGANG) Tj ET"; + + assert_eq!( + operators(data), + [ + b"BI".to_vec(), + b"BT".to_vec(), + b"Tf".to_vec(), + b"Tj".to_vec(), + b"Tj".to_vec(), + b"ET".to_vec() + ] + ); + } + + #[test] + fn inline_image_ei_may_be_followed_by_a_delimiter() { + let mut image = b"BI /W 16 /H 4 /BPC 8 /CS /G ID ".to_vec(); + image.extend([0x80; 64]); + image.extend(b"\nEI"); + let tail = b" Q BT /F1 24 Tf 72 200 Td (AFTER) Tj ET"; + let ops = |suffix: &[u8]| { + let mut data = image.clone(); + data.extend(suffix); + data.extend(tail); + operators(&data) + }; + let control = ops(b""); + assert_eq!(control.len(), 7); + assert_eq!(ops(b"%c\n"), control); + assert_eq!(ops(b"[] 0 d"), [&control[..1], &[b"d".to_vec()], &control[1..]].concat()); + } + + #[test] + fn inline_image_ei_followed_by_a_regular_character_is_not_the_end() { + let data = b"BI /W 1 /H 1 /BPC 8 /CS /G ID \x80 EIQ \x81 EI Q BT (a) Tj ET"; + // `EIQ` is one token and stays part of the image data. + let expected: Vec> = + ["BI", "Q", "BT", "Tj", "ET"].iter().map(|s| s.as_bytes().to_vec()).collect(); + assert_eq!(operators(data), expected); + } + + #[test] + fn ascii85_inline_image_data_may_contain_ei_before_a_delimiter() { + for glue in [&b"EI["[..], b"EI/", b"EI%", b"EI(", b"EI<"] { + let mut data = b"BI /W 4 /H 4 /BPC 8 /CS /G /F /A85 ID 9jqo^".to_vec(); + data.extend(glue); + data.extend(b"87cURD]i,\"Ebo80~>EI Q BT /F1 12 Tf (AFTER) Tj ET"); + let expected: Vec> = + ["BI", "Q", "BT", "Tf", "Tj", "ET"].iter().map(|s| s.as_bytes().to_vec()).collect(); + assert_eq!(operators(&data), expected, "{}", String::from_utf8_lossy(glue)); + } + } + #[test] fn tokenizer_interface_preserves_every_byte_boundary() { let data = b"% comment\n1 -2.5 /Name /A#20B (a\\(b\\) \\101) <4869> [1 2] << /Key (value) >> [(a) 1] TJ BI /W 1 /H 1 /BPC 8 /CS /DeviceGray ID \x00 EI q Q"; diff --git a/vendor/hayro-syntax/src/object/number.rs b/vendor/hayro-syntax/src/object/number.rs index bd37b19c3..9b89ed709 100644 --- a/vendor/hayro-syntax/src/object/number.rs +++ b/vendor/hayro-syntax/src/object/number.rs @@ -70,6 +70,13 @@ impl Number { impl Skippable for Number { fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> { let has_sign = r.forward_if(|b| b == b'+' || b == b'-').is_some(); + // PdfCraft patch: one more sign, so that skipping a number covers what `read_inner` + // reads. `--280` was already covered by the `b'-'` arm below, but `-+280` and `++280` + // were not, and a skip that fails where a read succeeds puts the reader back where it + // started (#3630 review). + if has_sign { + r.forward_if(|b| b == b'+' || b == b'-'); + } // Some PDFs have weird trailing minuses, so try to accept those as well. match r.peek_byte()? { @@ -113,17 +120,24 @@ impl Readable<'_> for Number { #[inline(always)] fn read_inner(r: &mut Reader<'_>) -> Option { - let negative = match r.peek_byte()? { - b'-' => { - r.forward(); - true - } - b'+' => { - r.forward(); - false - } - _ => false, - }; + // PdfCraft patch: a doubled sign is one number, not two. `--280` left `negative` set with no + // digits read, so it returned 0 and the reader stopped on `-280`, which became a second + // number: a `cm` with it got seven operands, kept the last six, and the matrix + // `0 0 1 0 -280 10` hid everything drawn under it (#3565). `Number::skip` above already + // consumes the whole token, so read and skip disagreed about where the number ended. + // + // One extra sign is absorbed and the value is negative if either sign was a minus, which is + // what the COS lexer does since #3299 (`--280` and `+-280` are both -280). A third sign is + // left to the digit loop's trailing-minus arm, as before. + let mut negative = false; + let mut signs = 0; + while signs < 2 + && let Some(b @ (b'-' | b'+')) = r.peek_byte() + { + r.forward(); + negative |= b == b'-'; + signs += 1; + } // PdfCraft patch: high-precision float mantissa overflow (jsPDF double-precision coordinates). // Digits that don't fit in `mantissa` are dropped: past the dot they are only precision; @@ -348,6 +362,30 @@ mod tests { use crate::reader::Reader; use crate::reader::ReaderExt; + /// PdfCraft patch: a doubled sign is one number. `--280` returned 0 and left `-280` to be + /// read as a second number, so a `cm` carrying it got seven operands and a degenerate matrix + /// (#3565). The COS lexer reads these the same way since #3299. + #[test] + fn a_doubled_sign_is_one_number() { + for (src, want) in [("--280", -280), ("+-280", -280), ("-+280", -280), ("++280", 280), ("-280", -280), ("+280", 280)] { + let mut r = Reader::new(src.as_bytes()); + assert_eq!(r.read_without_context::().unwrap(), want, "{src}"); + assert!(r.at_end(), "{src}: the whole number was read, leaving nothing for a second one"); + } + // The fraction too, and a lone sign is still zero. + assert_eq!(Reader::new("--280.5".as_bytes()).read_without_context::().unwrap(), -280.5); + assert_eq!(Reader::new("-".as_bytes()).read_without_context::().unwrap(), 0); + + // Skipping covers what reading accepts: a skip that fails where a read succeeds puts the + // reader back where it started, so `Object::skip` would leave the number in place + // (#3630 review). + for src in ["--280", "+-280", "-+280", "++280", "-280", "+280", "--280.5"] { + let mut r = Reader::new(src.as_bytes()); + assert!(r.skip::(false).is_some(), "{src}: not skipped"); + assert!(r.at_end(), "{src}: only part of the number was skipped"); + } + } + #[test] fn int_1() { assert_eq!( diff --git a/vendor/hayro-syntax/src/xref.rs b/vendor/hayro-syntax/src/xref.rs index 673d516d2..2d9df169b 100644 --- a/vendor/hayro-syntax/src/xref.rs +++ b/vendor/hayro-syntax/src/xref.rs @@ -807,6 +807,34 @@ fn populate_xref_impl<'a>(data: &'a [u8], pos: usize, xref_map: &mut XrefMap) -> populate_xref_impl_inner(data, pos, xref_map, &mut visited) } +/// The offset of the previous xref section (`Prev`). +// PdfCraft patch: (#2366) some writers give `Prev` as a reference `N G R`. When this section's +// own entries (`own`) place that object and it holds an offset (iText's `indirectPrev.pdf`), that +// is the offset; otherwise its object number is (tiff2pdf, in JHOVE's PDF-HUL-157 files), as +// `pdfcraft-cos` and other readers take it. +fn prev_offset(data: &[u8], trailer: &Dict<'_>, own: &XrefMap) -> Option { + if let Some(prev) = trailer.get::(PREV) { + return usize::try_from(prev).ok(); + } + + let r = trailer.get_ref(PREV)?; + let id = ObjectIdentifier::new(r.obj_number, r.gen_number); + let held = match own.get(&id) { + Some(EntryType::Normal(at)) => { + let mut reader = Reader::new(data); + reader.jump(*at); + reader + .read_with_context::>(&ReaderContext::dummy()) + .filter(|o| o.id() == &id) + .map(|o| o.get()) + .filter(|p| *p >= 0) + } + _ => None, + }; + + usize::try_from(held.unwrap_or(r.obj_number)).ok() +} + /// Maximum number of allowed xref `Prev` pointers before we abort. const MAX_XREF_CHAIN_DEPTH: usize = 256; @@ -882,17 +910,8 @@ fn populate_from_xref_table<'a>( reader.skip_white_spaces(); let mut max_obj = 0; - - if let Some(prev) = trailer.get::(PREV) { - // First insert the entries from any previous xref tables. - populate_xref_impl_inner(data, prev as usize, insert_map, visited)?; - } - - // In hybrid files, entries in `XRefStm` should have higher priority, therefore we insert them - // after looking at `PREV`. - if let Some(xref_stm) = trailer.get::(XREF_STM) { - populate_xref_impl_inner(data, xref_stm as usize, insert_map, visited)?; - } + // PdfCraft patch: (#2366) this section's entries are read first, for `prev_offset`. + let mut own = XrefMap::default(); while let Some(header) = reader.read_without_context::() { reader.skip_white_spaces(); @@ -908,7 +927,7 @@ fn populate_from_xref_table<'a>( // Specification says we should ignore any object number > SIZE, but probably // not important? if entry.used { - insert_map.insert( + own.insert( ObjectIdentifier::new(obj_number as i32, entry.gen_number), EntryType::Normal(entry.offset), ); @@ -916,6 +935,19 @@ fn populate_from_xref_table<'a>( } } + if let Some(prev) = prev_offset(data, &trailer, &own) { + // First insert the entries from any previous xref tables. + populate_xref_impl_inner(data, prev, insert_map, visited)?; + } + + // In hybrid files, entries in `XRefStm` should have higher priority, therefore we insert them + // after looking at `PREV`. + if let Some(xref_stm) = trailer.get::(XREF_STM) { + populate_xref_impl_inner(data, xref_stm as usize, insert_map, visited)?; + } + + insert_map.extend(own); + Some(trailer.data()) } @@ -929,11 +961,6 @@ fn populate_from_xref_stream<'a>( .read_with_context::>>(&ReaderContext::dummy())? .get(); - if let Some(prev) = stream.dict().get::(PREV) { - // First insert the entries from any previous xref tables. - let _ = populate_xref_impl_inner(data, prev as usize, insert_map, visited)?; - } - let size = stream.dict().get::(SIZE)?; let [f1_len, f2_len, f3_len] = stream.dict().get::<[u8; 3]>(W)?; @@ -950,6 +977,8 @@ fn populate_from_xref_stream<'a>( } let xref_data = stream.decoded().ok()?; + // PdfCraft patch: (#2366) this section's entries are read first, for `prev_offset`. + let mut own = XrefMap::default(); let mut xref_reader = Reader::new(xref_data.as_ref()); if let Some(arr) = stream.dict().get::>(INDEX) { @@ -963,21 +992,20 @@ fn populate_from_xref_stream<'a>( f1_len, f2_len, f3_len, - insert_map, + &mut own, )?; } } else { - xref_stream_subsection( - &mut xref_reader, - 0, - size, - f1_len, - f2_len, - f3_len, - insert_map, - )?; + xref_stream_subsection(&mut xref_reader, 0, size, f1_len, f2_len, f3_len, &mut own)?; } + if let Some(prev) = prev_offset(data, stream.dict(), &own) { + // First insert the entries from any previous xref tables. + let _ = populate_xref_impl_inner(data, prev, insert_map, visited)?; + } + + insert_map.extend(own); + Some(stream.dict().data()) } @@ -1434,6 +1462,78 @@ mod tests { let _result = populate_xref_impl(pdf.as_ref(), xref_pos, &mut xref_map); } + #[test] + fn prev_as_reference_reaches_the_earlier_section() { + let mut pdf = b"%PDF-1.0\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(); + let first_xref_pos = pdf.len(); + pdf.extend_from_slice( + format!( + "xref\n\ + 0 2\n\ + 0000000000 65535 f \n\ + 0000000009 00000 n \n\ + trailer\n<< /Size 2 /Root 1 0 R >>\n\ + startxref\n{first_xref_pos}\n%%EOF\n" + ) + .as_bytes(), + ); + let second_xref_pos = pdf.len(); + pdf.extend_from_slice( + format!( + "xref\n\ + 0 1\n\ + 0000000000 65535 f \n\ + trailer\n<< /Size 2 /Root 1 0 R /Prev {first_xref_pos} 0 R >>\n\ + startxref\n{second_xref_pos}\n%%EOF" + ) + .as_bytes(), + ); + + let mut xref_map = FxHashMap::default(); + let xref_pos = find_last_xref_pos(pdf.as_ref()).unwrap(); + assert_eq!(xref_pos, second_xref_pos); + populate_xref_impl(pdf.as_ref(), xref_pos, &mut xref_map).unwrap(); + assert!(xref_map.contains_key(&ObjectIdentifier::new(1, 0))); + } + + #[test] + fn prev_as_reference_to_an_object_holding_the_offset_reads_that_offset() { + let mut pdf = b"%PDF-1.0\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(); + let first_xref_pos = pdf.len(); + pdf.extend_from_slice( + format!( + "xref\n\ + 0 2\n\ + 0000000000 65535 f \n\ + 0000000009 00000 n \n\ + trailer\n<< /Size 2 /Root 1 0 R >>\n\ + startxref\n{first_xref_pos}\n%%EOF\n" + ) + .as_bytes(), + ); + // Object 3 holds the offset; read as offset 3, `Prev` would point inside the header. + let held_pos = pdf.len(); + pdf.extend_from_slice(format!("3 0 obj\n{first_xref_pos}\nendobj\n").as_bytes()); + let second_xref_pos = pdf.len(); + pdf.extend_from_slice( + format!( + "xref\n\ + 3 1\n\ + {held_pos:010} 00000 n \n\ + trailer\n<< /Size 4 /Root 1 0 R /Prev 3 0 R >>\n\ + startxref\n{second_xref_pos}\n%%EOF" + ) + .as_bytes(), + ); + + let mut xref_map = FxHashMap::default(); + let xref_pos = find_last_xref_pos(pdf.as_ref()).unwrap(); + assert_eq!(xref_pos, second_xref_pos); + populate_xref_impl(pdf.as_ref(), xref_pos, &mut xref_map).unwrap(); + assert!(xref_map.contains_key(&ObjectIdentifier::new(1, 0))); + assert!(xref_map.contains_key(&ObjectIdentifier::new(3, 0))); + } + #[test] fn find_last_xref_uses_last_startxref() { let pdf = b"%PDF-1.0\nstartxref\n5\n%%EOF\nstartxref\n42\n%%EOF"; diff --git a/vendor/lopdf/src/reader.rs b/vendor/lopdf/src/reader.rs index df471371d..d7e33b7dc 100644 --- a/vendor/lopdf/src/reader.rs +++ b/vendor/lopdf/src/reader.rs @@ -1627,8 +1627,38 @@ impl Reader<'_> { Some((number, generation)) } - /// Newest backwards-scanned `trailer` whose `/Root` references a scanned object. + /// Newest backwards-scanned `trailer` whose `/Root` references a scanned object, one whose + /// `/Root` is the catalog first. fn find_latest_trailer(&self, xref: &Xref) -> Option<(usize, Dictionary)> { + // PdfCraft patch: (#2365) an in-file /Root must also match its generation, as + // `get_offset` requires when the root is loaded. + let usable = |dict: &Dictionary| { + dict.get(b"Root") + .and_then(Object::as_reference) + .is_ok_and(|root| match xref.entries.get(&root.0) { + Some(XrefEntry::Normal { generation, .. }) => *generation == root.1, + entry => entry.is_some(), + }) + }; + // PdfCraft patch: (#2365) a candidate whose /Root is the catalog (`/Type /Catalog` or + // `/Pages`) beats one whose /Root is another dictionary, such as /Info, wherever it is; + // the other kind is still taken when nothing better is there (an FDF's /Root). + let is_catalog = |dict: &Dictionary| { + let Ok(root) = dict.get(b"Root").and_then(Object::as_reference) else { + return false; + }; + let Some(XrefEntry::Normal { offset, generation }) = xref.entries.get(&root.0) else { + return false; + }; + if *generation != root.1 { + return false; + } + parser::indirect_object(self.buffer, *offset as usize, None, self, &mut HashSet::new(), None) + .ok() + .and_then(|(_, object)| object.as_dict().map(|d| d.has_type(b"Catalog") || d.has(b"Pages")).ok()) + .unwrap_or(false) + }; + let mut latest: Option<(bool, usize, Dictionary)> = None; let mut bound = self.buffer.len(); for _ in 0..MAX_TRAILER_CANDIDATES { let Some(pos) = Reader::search_substring(&self.buffer[..bound], b"trailer", 0) else { @@ -1643,15 +1673,54 @@ impl Reader<'_> { let Ok((_, dict)) = parser::dictionary(&after_keyword[dict_start..]) else { continue; }; - if dict - .get(b"Root") - .and_then(Object::as_reference) - .is_ok_and(|root| xref.entries.contains_key(&root.0)) - { - return Some((pos, dict)); + if usable(&dict) { + let catalog = is_catalog(&dict); + if latest.is_none() || catalog { + latest = Some((catalog, pos, dict)); + } + if catalog { + break; + } } } - None + // PdfCraft patch: (#2365) a file whose only trailer is a cross-reference stream has + // no `trailer` keyword, so the scan above found nothing and the rebuild failed; its + // /Info and /ID were then lost. Such a stream's dictionary is the trailer, and the + // latest one in the file wins, as a later `trailer` keyword would. + const HEADER_WINDOW: usize = 32; + const DICT_WINDOW: usize = 4096; + for entry in xref.entries.values() { + let XrefEntry::Normal { offset, .. } = entry else { + continue; + }; + let offset = *offset as usize; + if latest.as_ref().is_some_and(|(catalog, pos, _)| *catalog && *pos >= offset) { + continue; + } + let Some(head) = self.buffer.get(offset..) else { + continue; + }; + let Some(dict_start) = head[..cmp::min(head.len(), HEADER_WINDOW)] + .windows(2) + .position(|window| window == b"<<") + else { + continue; + }; + let dict_bytes = &head[dict_start..cmp::min(head.len(), dict_start + DICT_WINDOW)]; + if !dict_bytes.windows(5).any(|window| window == b"/XRef") { + continue; + } + let Ok((_, dict)) = parser::dictionary(&head[dict_start..]) else { + continue; + }; + if dict.has_type(b"XRef") && usable(&dict) { + let rank = (is_catalog(&dict), offset); + if latest.as_ref().is_none_or(|(catalog, pos, _)| rank > (*catalog, *pos)) { + latest = Some((rank.0, offset, dict)); + } + } + } + latest.map(|(_, pos, dict)| (pos, dict)) } /// Some generators write `startxref` (or trailer `Prev`) values that are diff --git a/xtask/src/assets.rs b/xtask/src/assets.rs index 1352a64c8..abd5f070c 100644 --- a/xtask/src/assets.rs +++ b/xtask/src/assets.rs @@ -47,7 +47,7 @@ pub const ADOBE_DATA_ALLOWED: &[(&str, &str)] = &[("hayro-cmap", "assets/cmaps.b /// technical data we hold ourselves rather than through a dependency. Each still needs an /// `[[asset]]` entry with `adobe_data = true`, so its SHA-256 is checked and any change to the /// table has to be re-attested deliberately. -pub const ADOBE_DATA_FILES: &[&str] = &["crates/fonts/src/std14_metrics.rs"]; +pub const ADOBE_DATA_FILES: &[&str] = &["crates/fonts/src/std14_metrics.rs", "vendor/hayro-cmap/assets/cmaps.brotli"]; /// File extensions that count as assets wherever they appear in the repository. const ASSET_EXTENSIONS: &[&str] = &[