mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-10-24 02:13:12 +00:00
Merge r2 track t13: cos-parse, vendored-crate fixes
# Conflicts: # ATTRIBUTION.md # crates/annot/src/tests.rs # crates/forms/src/tests.rs # crates/organize/src/tests.rs
This commit is contained in:
+3
-3
@@ -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)
|
||||
|
||||
+4
-5
@@ -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"
|
||||
|
||||
Generated
-2
@@ -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",
|
||||
|
||||
@@ -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" }
|
||||
|
||||
+47
-18
@@ -659,25 +659,54 @@ impl ReviewState {
|
||||
pub fn page_refs(doc: &Document) -> Result<Vec<ObjRef>, 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()));
|
||||
}
|
||||
}
|
||||
_ => out.push(node),
|
||||
}
|
||||
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<ObjRef>,
|
||||
pending: Vec<(std::sync::Arc<Object>, 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<ObjRef> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn page_ref(doc: &Document, page: usize) -> Result<ObjRef, AnnotError> {
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
@@ -219,19 +219,40 @@ fn inline_image(data: &[u8], pos: usize) -> Result<(Dict, Vec<u8>, 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 };
|
||||
|
||||
@@ -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<u8> = (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<u8> {
|
||||
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 !!~>");
|
||||
}
|
||||
}
|
||||
|
||||
+639
-68
@@ -268,6 +268,20 @@ impl XrefIndex {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every entry, newest section first, as the materialized reader keeps them.
|
||||
fn to_map(&self, file: &[u8]) -> BTreeMap<u32, XrefEntry> {
|
||||
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<Option<(u32, usize)>>,
|
||||
data: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// 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<usize>, 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<Vec<Revision>>,
|
||||
/// See [`Self::xref_oddities`].
|
||||
xref_oddities: Arc<Vec<(u64, u32)>>,
|
||||
/// 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<BTreeMap<u32, (u64, u16)>>,
|
||||
repair_log: Arc<Vec<String>>,
|
||||
cache: Arc<Mutex<HashMap<u32, Arc<Object>>>>,
|
||||
objstms: Arc<Mutex<HashMap<u32, Arc<ObjStm>>>>,
|
||||
@@ -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::<Option<(u32, usize)>>()))
|
||||
});
|
||||
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::<Option<(u32, usize)>>()))
|
||||
});
|
||||
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<String>) {
|
||||
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<u32> = 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<u32> = 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<String>) -> Result<(), CosError> {
|
||||
let data = self.data.clone();
|
||||
let mut entries: BTreeMap<u32, XrefEntry> = 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::<u32>().ok());
|
||||
let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::<u16>().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<u32> {
|
||||
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::<u64>().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::<u32>().ok());
|
||||
let generation = std::str::from_utf8(g).ok().and_then(|s| s.parse::<u16>().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<XrefEntry>, log: &mut Vec<String>) -> Option<u64> {
|
||||
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<usize> {
|
||||
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<u8> {
|
||||
/// 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<u8> {
|
||||
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<u8> {
|
||||
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<String> {
|
||||
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<Object> {
|
||||
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::<Option<(u32, usize)>>()).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<u8> {
|
||||
let mut out = b"%PDF-1.5\n".to_vec();
|
||||
let mut offs = [0usize; 6];
|
||||
let mut obj = |out: &mut Vec<u8>, 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<String> {
|
||||
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");
|
||||
|
||||
+47
-18
@@ -457,25 +457,54 @@ fn nums(doc: &Document, o: Option<&Object>) -> Option<Vec<f64>> {
|
||||
pub(crate) fn page_refs(doc: &Document) -> Vec<ObjRef> {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
_ => out.push(node),
|
||||
}
|
||||
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<ObjRef>,
|
||||
pending: Vec<(std::sync::Arc<Object>, 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<ObjRef> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The AcroForm dictionary.
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
+63
-25
@@ -72,36 +72,74 @@ fn pages_root(doc: &Document) -> Result<ObjRef, OrganizeError> {
|
||||
|
||||
/// All leaf pages in order, with their effective inherited attributes.
|
||||
fn walk(doc: &Document) -> Result<Vec<(ObjRef, Dict)>, 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<std::sync::Arc<Object>>; 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<ObjRef>,
|
||||
pending: Vec<(std::sync::Arc<Object>, 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.
|
||||
|
||||
@@ -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<String> = 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::<Vec<_>>());
|
||||
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"]);
|
||||
}
|
||||
|
||||
@@ -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<</Type/Catalog/Pages 2 0 R>>endobj\n";
|
||||
let obj2 = "2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n";
|
||||
let obj3 = "3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 10 10]>>endobj\n";
|
||||
let obj4 = "4 0 obj<</Title(Kept)/Creator(Me)>>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<u8> =
|
||||
[[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<</Type/XRef/Root 1 0 R/Info 4 0 R/Size 6/W[1 2 1]/Length {}>>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 [
|
||||
"<</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]>>",
|
||||
"<</Title(Kept)/Creator(Me)>>",
|
||||
] {
|
||||
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<</Size 5/Root 1 0 R/Info 4 0 R>>\n");
|
||||
bytes.extend_from_slice(b"5 0 obj<</Type/XRef/Root 4 0 R/Size 6/W[1 2 1]/Length 4>>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.
|
||||
|
||||
@@ -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
|
||||
|
||||
Vendored
+3
-2
File diff suppressed because one or more lines are too long
+53
@@ -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"
|
||||
Vendored
+87
@@ -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 <laurenz.stampfl@gmail.com>"]
|
||||
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"
|
||||
+21
@@ -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
|
||||
Vendored
+177
@@ -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
|
||||
Vendored
+7
@@ -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.
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
# hayro-cmap
|
||||
|
||||
[](https://crates.io/crates/hayro-cmap)
|
||||
[](https://docs.rs/hayro-cmap)
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
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.
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
||||
## License
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
Vendored
+28
@@ -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.
|
||||
Vendored
+2
@@ -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.
|
||||
BIN
Binary file not shown.
+129
@@ -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<Bundle> = 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<u8>,
|
||||
pub(super) delta_table: HuffmanTable,
|
||||
pub(super) count_table: HuffmanTable,
|
||||
entries: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
/// 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()])
|
||||
}
|
||||
+180
@@ -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<NonZeroU32>,
|
||||
/// Index of the one-child.
|
||||
one: Option<NonZeroU32>,
|
||||
},
|
||||
/// Leaf node holding a decoded symbol value.
|
||||
Leaf(u32),
|
||||
}
|
||||
|
||||
/// A Huffman table built from canonical codes.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct HuffmanTable {
|
||||
nodes: Vec<HuffmanNode>,
|
||||
}
|
||||
|
||||
impl HuffmanTable {
|
||||
/// Decode a single symbol from the bit reader.
|
||||
pub(super) fn decode(&self, reader: &mut Reader<'_>) -> Option<u32> {
|
||||
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<HuffmanNode>,
|
||||
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<u32>,
|
||||
) -> Option<HuffmanTable> {
|
||||
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))
|
||||
}
|
||||
Vendored
+416
@@ -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 <https://github.com/LaurenzV/cmap-resources/tree/hayro>.
|
||||
|
||||
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<CMap> {
|
||||
// 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<Box<CMap>> = 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<CodespaceRange>) -> 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<u32> = None;
|
||||
let mut prev_cid: Option<u32> = 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<BfRange>,
|
||||
delta_table: &HuffmanTable,
|
||||
count_table: Option<&HuffmanTable>,
|
||||
fixed_units: Option<usize>,
|
||||
) -> 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<u32> = 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(())
|
||||
}
|
||||
+123
@@ -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<u8> {
|
||||
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<u16> {
|
||||
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<u32> {
|
||||
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<u8> {
|
||||
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<u32> {
|
||||
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]
|
||||
}
|
||||
}
|
||||
Vendored
+1699
File diff suppressed because it is too large
Load Diff
Vendored
+469
@@ -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<F> {
|
||||
buf: Vec<u8>,
|
||||
get_cmap: F,
|
||||
}
|
||||
|
||||
pub(crate) fn parse_inner<'a>(
|
||||
data: &[u8],
|
||||
get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a,
|
||||
depth: u32,
|
||||
) -> Option<CMap> {
|
||||
// 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<Vec<u8>> = 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<WritingMode> {
|
||||
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<Vec<u8>> {
|
||||
match scanner.parse_object().ok()? {
|
||||
Object::String(s) => s.decode().ok(),
|
||||
Object::Name(n) => n.decode().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_codespace_range<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
ranges: &mut Vec<CodespaceRange>,
|
||||
ctx: &mut Context<F>,
|
||||
) -> 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<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
ranges: &mut PartitionedRanges,
|
||||
ctx: &mut Context<F>,
|
||||
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<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
ranges: &mut PartitionedRanges,
|
||||
ctx: &mut Context<F>,
|
||||
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<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
entries: &mut Vec<BfRange>,
|
||||
ctx: &mut Context<F>,
|
||||
) -> 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<F>(
|
||||
scanner: &mut Scanner<'_>,
|
||||
entries: &mut Vec<BfRange>,
|
||||
ctx: &mut Context<F>,
|
||||
) -> 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<Vec<u16>> {
|
||||
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<u8>) -> Option<u32> {
|
||||
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<u8>) -> Option<u32> {
|
||||
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<u32> {
|
||||
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))
|
||||
}
|
||||
+75
-11
@@ -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<Vec<u8>> =
|
||||
["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<Vec<u8>> =
|
||||
["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";
|
||||
|
||||
+49
-11
@@ -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<Number> {
|
||||
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::<i32>().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::<f64>().unwrap(), -280.5);
|
||||
assert_eq!(Reader::new("-".as_bytes()).read_without_context::<i32>().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::<Number>(false).is_some(), "{src}: not skipped");
|
||||
assert!(r.at_end(), "{src}: only part of the number was skipped");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn int_1() {
|
||||
assert_eq!(
|
||||
|
||||
Vendored
+127
-27
@@ -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<usize> {
|
||||
if let Some(prev) = trailer.get::<i32>(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::<IndirectObject<i32>>(&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::<i32>(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::<i32>(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::<SubsectionHeader>() {
|
||||
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::<i32>(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::<IndirectObject<Stream<'_>>>(&ReaderContext::dummy())?
|
||||
.get();
|
||||
|
||||
if let Some(prev) = stream.dict().get::<i32>(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::<u32>(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::<Array<'_>>(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";
|
||||
|
||||
Vendored
+77
-8
@@ -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
|
||||
|
||||
+1
-1
@@ -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] = &[
|
||||
|
||||
Reference in New Issue
Block a user