pdf: fix issue #321 open-recovery, image OOM, prim cap; add repro harness
- Commit
f2d7ddb2b548812295554900e78e669885201e74- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-08 00:21 UTC (4 months ago)
- Parents
98026d5
Diff
.gitignore
diff --git a/.gitignore b/.gitignoreindex a366b6e2c6..5b85b7f061 100644--- a/.gitignore+++ b/.gitignore@@ -24,6 +24,10 @@ distribution_apks/ __pycache__/ scratch/LiteRT-LM/ +# Issue #321 reproduction PDFs (potential copyright; harness reads them locally,+# see pdf/src/main/rust/src/issue321_tests.rs). Not committed.+issue321_pdfs/+ # Personal / private app modules (kept out of the public repo) /personal/
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktindex c1a191131c..29bfe9f6f6 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -43,8 +43,14 @@ class SafePdfDocument private constructor( /** Decode page [index] (0-based), or `null` if the native render fails. */ suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) { synchronized(cache) { cache[index] }?.let { return@withContext it }- val bytes = PdfNative.renderPage(handle, index) ?: return@withContext null- val page = SafePdfParser.parse(bytes)+ // A single unrenderable page must not take down the viewer: the native+ // side throws a RuntimeException on an uncaught panic (see the+ // catch_unwind boundary in jni_bindings.rs), and a corrupt wire buffer+ // could throw during parse. Degrade either to a skipped (null) page.+ val bytes = runCatching { PdfNative.renderPage(handle, index) }.getOrNull()+ ?: return@withContext null+ val page = runCatching { SafePdfParser.parse(bytes) }.getOrNull()+ ?: return@withContext null synchronized(cache) { // Budget-based eviction in addition to count-based var pixels = page.primitives.sumOf { prim ->
pdf/src/main/rust/src/debug_ishi_test.rs
diff --git a/pdf/src/main/rust/src/debug_ishi_test.rs b/pdf/src/main/rust/src/debug_ishi_test.rsindex a89039bf4d..b189da24cb 100644--- a/pdf/src/main/rust/src/debug_ishi_test.rs+++ b/pdf/src/main/rust/src/debug_ishi_test.rs@@ -9,8 +9,18 @@ mod ishi_tests { let path = match std::env::var("ISHI_PDF") { Ok(p) => PathBuf::from(p), Err(_) => {- let home = std::env::var("HOME").unwrap();- PathBuf::from(home).join("Downloads/Ishihara_Tests.pdf")+ // Optional local fixture: skip when no home dir is set (e.g. HOME+ // is not defined on Windows hosts) rather than panicking.+ let home = std::env::var("HOME")+ .or_else(|_| std::env::var("USERPROFILE"))+ .ok();+ match home {+ Some(h) => PathBuf::from(h).join("Downloads/Ishihara_Tests.pdf"),+ None => {+ println!("ISHI_PDF unset and no home dir; skipping");+ return;+ }+ } } }; if !path.exists() {
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex 59cf3b60a0..b12cc5d308 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -319,7 +319,13 @@ pub(crate) fn extract_page(handle: i64, index: i32) -> Option<Vec<u8>> { /// Serialize page `index` (0-based) of the document behind `handle` into the /// wire buffer, or `None` on any error. pub(crate) fn render_page(handle: i64, index: i32) -> Option<Vec<u8>> {- let reg = registry().lock().unwrap();+ // Poison-tolerant lock: if a prior page's interpretation panicked while this+ // lock was held, recover the guard instead of cascading a panic to every+ // subsequent page (the "crashes halfway" failure mode). Matches the recovery+ // policy documented in registry.rs.+ let reg = registry()+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner()); let doc = reg.get(&handle)?; let pages = doc.get_pages(); let page_id = *pages.get(&((index as u32) + 1))?;
pdf/src/main/rust/src/graphics_state.rs
diff --git a/pdf/src/main/rust/src/graphics_state.rs b/pdf/src/main/rust/src/graphics_state.rsindex bd9f3c5065..4f98d11b79 100644--- a/pdf/src/main/rust/src/graphics_state.rs+++ b/pdf/src/main/rust/src/graphics_state.rs@@ -143,11 +143,16 @@ impl Default for GraphicsState { pub(crate) const BEZIER_STEPS: usize = 16; pub(crate) const MAX_CLIP_DEPTH: usize = 64; pub(crate) const MAX_GRAPHICS_STACK: usize = 128;-pub(crate) const MAX_PRIMITIVES: usize = 50000;+pub(crate) const MAX_PRIMITIVES: usize = 300000; pub(crate) const MAX_ANNOTATIONS: usize = 10000; pub(crate) const MAX_IMAGE_DIM: u32 = 20000; pub(crate) const MAX_IMAGE_BYTES: usize = 16 * 1024 * 1024; pub(crate) const MAX_IMAGE_PIXELS: usize = 16 * 1024 * 1024; // ~16 MP cap+/// Decoded raster images are downscaled (preserving aspect) so their longer side+/// does not exceed this, capping per-image RGBA memory on device. 2048px is well+/// above a full page's on-screen pixel width, so quality is preserved while a+/// large source (e.g. 2480×3452 ≈ 33 MB) drops to ≈ 12 MB.+pub(crate) const IMAGE_DOWNSCALE_MAX_DIM: u32 = 2048; pub(crate) const MAX_SHADING_PATCHES: usize = 1000; pub(crate) const MAX_TYPE3_GLYPHS: usize = 500; pub(crate) const MAX_TYPE3_PRIMS_PER_GLYPH: usize = 1000;
pdf/src/main/rust/src/images.rs
diff --git a/pdf/src/main/rust/src/images.rs b/pdf/src/main/rust/src/images.rsindex 6d91b91597..8dccb79227 100644--- a/pdf/src/main/rust/src/images.rs+++ b/pdf/src/main/rust/src/images.rs@@ -549,7 +549,65 @@ fn stencilize(rgba: &mut [u8], fill_argb: u32, invert: bool) { } } +/// Area-average downscale of an RGBA8888 buffer so its longer side is at most+/// `max_dim`, preserving aspect. Returns `None` when no downscale is needed.+fn downscale_rgba(data: &[u8], w: u32, h: u32, max_dim: u32) -> Option<(u32, u32, Vec<u8>)> {+ if w == 0 || h == 0 || (w <= max_dim && h <= max_dim) {+ return None;+ }+ if data.len() < (w as usize) * (h as usize) * 4 {+ return None; // malformed buffer; leave as-is+ }+ let scale = max_dim as f64 / w.max(h) as f64;+ let nw = ((w as f64 * scale).round() as u32).clamp(1, w);+ let nh = ((h as f64 * scale).round() as u32).clamp(1, h);+ let mut out = vec![0u8; (nw as usize) * (nh as usize) * 4];+ for oy in 0..nh {+ let sy0 = ((oy as u64) * (h as u64) / (nh as u64)) as u32;+ let sy1 = ((((oy + 1) as u64) * (h as u64) / (nh as u64)) as u32).clamp(sy0 + 1, h);+ for ox in 0..nw {+ let sx0 = ((ox as u64) * (w as u64) / (nw as u64)) as u32;+ let sx1 = ((((ox + 1) as u64) * (w as u64) / (nw as u64)) as u32).clamp(sx0 + 1, w);+ let (mut r, mut g, mut b, mut a, mut cnt) = (0u64, 0u64, 0u64, 0u64, 0u64);+ for sy in sy0..sy1 {+ let row = (sy as usize) * (w as usize) * 4;+ for sx in sx0..sx1 {+ let i = row + (sx as usize) * 4;+ r += data[i] as u64;+ g += data[i + 1] as u64;+ b += data[i + 2] as u64;+ a += data[i + 3] as u64;+ cnt += 1;+ }+ }+ let o = ((oy as usize) * (nw as usize) + ox as usize) * 4;+ if cnt > 0 {+ out[o] = (r / cnt) as u8;+ out[o + 1] = (g / cnt) as u8;+ out[o + 2] = (b / cnt) as u8;+ out[o + 3] = (a / cnt) as u8;+ }+ }+ }+ Some((nw, nh, out))+}++/// Decode an image XObject to [`ImageData`], downscaling oversized decoded+/// rasters (format 0) so a single image cannot blow the device bitmap budget.+/// JPEG passthrough (format 1) is left untouched; Kotlin subsamples it on decode. pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u32, cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<ImageData> {+ let mut img = extract_image_inner(doc, stream, fill_argb, cs_resources)?;+ if img.format == 0 {+ if let Some((nw, nh, ndata)) = downscale_rgba(&img.data, img.w, img.h, IMAGE_DOWNSCALE_MAX_DIM) {+ img.w = nw;+ img.h = nh;+ img.data = ndata;+ }+ }+ Some(img)+}++fn extract_image_inner(doc: &Document, stream: &lopdf::Stream, fill_argb: u32, cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<ImageData> { let dict = &stream.dict; let w = dict.get(b"Width").ok().and_then(num)? as u32; let h = dict.get(b"Height").ok().and_then(num)? as u32;
pdf/src/main/rust/src/issue321_tests.rs
diff --git a/pdf/src/main/rust/src/issue321_tests.rs b/pdf/src/main/rust/src/issue321_tests.rsnew file mode 100644index 0000000000..1dd40743e0--- /dev/null+++ b/pdf/src/main/rust/src/issue321_tests.rs@@ -0,0 +1,274 @@+//! Host-side reproduction harness for GitHub issue #321 rendering bugs.+//!+//! Drives the real rendering pipeline (`open_document` → `interpret_page`) on the+//! host target so each of the 13 example PDFs from the issue can be reproduced+//! and verified with `cargo test`, without needing a device/emulator.+//!+//! The fixture PDFs are NOT committed (potential copyright). Point the harness at+//! them with the `ISSUE321_DIR` env var, or drop them in `<repo>/issue321_pdfs/`.+//! When the directory is absent the tests print a notice and pass, mirroring the+//! `ISHI_PDF` skip pattern in `debug_ishi_test.rs`.+//!+//! Run with output:+//! cargo test -p pdf_render issue321 -- --nocapture++#[cfg(test)]+mod issue321 {+ use crate::*;+ use std::panic::AssertUnwindSafe;+ use std::path::PathBuf;+ use std::time::Instant;++ /// The 13 fixtures attached to issue #321, each named after the symptom it+ /// triggers (see the plan). `Ishihara_Tests.pdf` is covered separately.+ const FIXTURES: &[&str] = &[+ "bleedexample",+ "colorrenderexample",+ "crasheshalfway",+ "crashexample",+ "doesntopenexample",+ "doesntrenderfully",+ "doesntrenderimages",+ "doesntzoomfully-stopsrenderhalfway",+ "doesntzoomfully2",+ "missinggraphic",+ "pagerotationexample",+ "slowdownexample",+ "slowdownexample2",+ ];++ /// Locate the fixtures directory: `ISSUE321_DIR` env override, else the repo's+ /// `issue321_pdfs/` resolved relative to this crate's manifest dir.+ fn fixtures_dir() -> Option<PathBuf> {+ if let Ok(p) = std::env::var("ISSUE321_DIR") {+ let pb = PathBuf::from(p);+ return if pb.is_dir() { Some(pb) } else { None };+ }+ // CARGO_MANIFEST_DIR = <repo>/pdf/src/main/rust ; repo root is 4 levels up.+ let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ let candidate = manifest+ .ancestors()+ .nth(4)+ .map(|root| root.join("issue321_pdfs"));+ candidate.filter(|c| c.is_dir())+ }++ /// Per-page primitive tally, split by the categories relevant to the issue.+ #[derive(Default)]+ struct PageStats {+ fills: usize,+ strokes: usize,+ text_paint: usize, // substitute glyphs actually painted+ text_outline: usize, // real outlines emitted as fills (outline=true)+ images_ok: usize, // decoded RGBA (format 0) with a non-empty buffer+ images_jpeg: usize, // JPEG passthrough (format 1)+ images_empty: usize, // image prim with an empty / zero-size buffer+ clip_push: usize,+ max_clip_depth: usize,+ groups: usize,+ soft_masks: usize,+ total: usize,+ max_img_w: u32, // largest single decoded image (RGBA) dimensions+ max_img_h: u32,+ decoded_img_bytes: usize, // sum of RGBA bytes across format-0 images+ }++ fn tally(prims: &[Prim]) -> PageStats {+ let mut s = PageStats::default();+ let mut depth = 0usize;+ for p in prims {+ s.total += 1;+ match p {+ Prim::Fill { .. } => s.fills += 1,+ Prim::Stroke { .. } => s.strokes += 1,+ Prim::Text { outline, .. } => {+ if *outline {+ s.text_outline += 1;+ } else {+ s.text_paint += 1;+ }+ }+ Prim::Image { format, data, w, h, .. } => {+ let empty = data.is_empty() || *w == 0 || *h == 0;+ if empty {+ s.images_empty += 1;+ } else if *format == 1 {+ s.images_jpeg += 1;+ } else {+ s.images_ok += 1;+ s.decoded_img_bytes += data.len();+ if (*w as u64) * (*h as u64) > (s.max_img_w as u64) * (s.max_img_h as u64) {+ s.max_img_w = *w;+ s.max_img_h = *h;+ }+ }+ }+ Prim::ClipPush { .. } => {+ s.clip_push += 1;+ depth += 1;+ s.max_clip_depth = s.max_clip_depth.max(depth);+ }+ Prim::ClipPop => depth = depth.saturating_sub(1),+ Prim::GroupPush { .. } => s.groups += 1,+ Prim::SoftMaskPush { .. } => s.soft_masks += 1,+ _ => {}+ }+ }+ s+ }++ /// Result of processing one fixture PDF.+ struct FixtureReport {+ name: String,+ opened: bool,+ page_count: usize,+ panics: Vec<usize>, // 0-based page indices that panicked+ interp_errs: Vec<usize>, // pages where interpret_page returned Err+ slowest_ms: u128,+ slowest_page: usize,+ total_ms: u128,+ empty_image_pages: usize,+ }++ fn process(name: &str, path: &PathBuf) -> FixtureReport {+ let mut report = FixtureReport {+ name: name.to_string(),+ opened: false,+ page_count: 0,+ panics: Vec::new(),+ interp_errs: Vec::new(),+ slowest_ms: 0,+ slowest_page: 0,+ total_ms: 0,+ empty_image_pages: 0,+ };++ let bytes = match std::fs::read(path) {+ Ok(b) => b,+ Err(e) => {+ println!(" [{}] read error: {}", name, e);+ return report;+ }+ };++ // Mirror the real open path (registry::open_document_pw returns 0 on failure).+ let handle = open_document(&bytes);+ report.opened = handle != 0;+ if report.opened {+ close_document(handle);+ }+ println!(+ "\n=== {} === open={}",+ name,+ if report.opened { "OK" } else { "FAILED (handle 0)" }+ );++ // Load once for per-page interpretation, via the same recovery-capable+ // path the app uses (registry::open_document → load_document_lenient).+ let doc = match load_document_lenient(&bytes) {+ Some(d) => d,+ None => {+ println!(" load_document_lenient failed");+ return report;+ }+ };++ let pages = doc.get_pages();+ report.page_count = pages.len();+ println!(" pages: {}", report.page_count);++ for (idx, (page_num, page_id)) in pages.iter().enumerate() {+ let start = Instant::now();+ let outcome =+ std::panic::catch_unwind(AssertUnwindSafe(|| interpret_page(&doc, *page_id)));+ let ms = start.elapsed().as_millis();+ report.total_ms += ms;+ if ms > report.slowest_ms {+ report.slowest_ms = ms;+ report.slowest_page = idx;+ }+ match outcome {+ Ok(Ok(pd)) => {+ let st = tally(&pd.prims);+ if st.images_empty > 0 {+ report.empty_image_pages += 1;+ }+ println!(+ " p{} (#{}) {:.0}x{:.0} {}ms prims={} fill={} stroke={} \+ txt(paint={},outline={}) img(ok={},jpeg={},empty={}) \+ clip={}(d{}) grp={} smask={} maximg={}x{} imgMB={:.1}",+ idx, page_num, pd.width, pd.height, ms, st.total, st.fills, st.strokes,+ st.text_paint, st.text_outline, st.images_ok, st.images_jpeg,+ st.images_empty, st.clip_push, st.max_clip_depth, st.groups,+ st.soft_masks, st.max_img_w, st.max_img_h,+ st.decoded_img_bytes as f64 / (1024.0 * 1024.0),+ );+ }+ Ok(Err(e)) => {+ report.interp_errs.push(idx);+ println!(" p{} (#{}) {}ms INTERPRET ERROR: {}", idx, page_num, ms, e);+ }+ Err(_) => {+ report.panics.push(idx);+ println!(" p{} (#{}) {}ms *** PANIC ***", idx, page_num, ms);+ }+ }+ }++ println!(+ " summary: opened={} pages={} panics={} interp_errs={} empty_img_pages={} \+ total={}ms slowest=p{}({}ms)",+ report.opened, report.page_count, report.panics.len(), report.interp_errs.len(),+ report.empty_image_pages, report.total_ms, report.slowest_page, report.slowest_ms,+ );++ report+ }++ /// Drive every fixture and print a per-PDF / per-page report. This test never+ /// fails on rendering defects itself (it is a diagnostic harness); it only+ /// fails if the harness cannot run. Skips cleanly when fixtures are absent.+ #[test]+ fn issue321_report() {+ let dir = match fixtures_dir() {+ Some(d) => d,+ None => {+ println!(+ "issue321 fixtures not found (set ISSUE321_DIR or add <repo>/issue321_pdfs/); \+ skipping."+ );+ return;+ }+ };+ println!("issue321 fixtures dir: {}", dir.display());++ let mut reports = Vec::new();+ for name in FIXTURES {+ let path = dir.join(format!("{}.pdf", name));+ if !path.exists() {+ println!("\n=== {} === (missing file, skipped)", name);+ continue;+ }+ reports.push(process(name, &path));+ }++ // Compact overview table at the end for quick triage.+ println!("\n================ issue321 overview ================");+ println!(+ "{:<38} {:>4} {:>5} {:>6} {:>6} {:>8}",+ "fixture", "open", "pages", "panic", "err", "slow(ms)"+ );+ for r in &reports {+ println!(+ "{:<38} {:>4} {:>5} {:>6} {:>6} {:>8}",+ r.name,+ if r.opened { "OK" } else { "FAIL" },+ r.page_count,+ r.panics.len(),+ r.interp_errs.len(),+ r.slowest_ms,+ );+ }+ println!("==================================================");+ }+}
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex 7175a90372..87133a4459 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -80,3 +80,5 @@ mod jni_bindings; mod tests; #[cfg(test)] mod debug_ishi_test;+#[cfg(test)]+mod issue321_tests;
pdf/src/main/rust/src/registry.rs
diff --git a/pdf/src/main/rust/src/registry.rs b/pdf/src/main/rust/src/registry.rsindex 942ec3bd8e..c07eed6ab7 100644--- a/pdf/src/main/rust/src/registry.rs+++ b/pdf/src/main/rust/src/registry.rs@@ -42,9 +42,9 @@ pub(crate) fn open_document_pw(bytes: &[u8], password: &[u8]) -> i64 { if bytes.len() > MAX_PDF_BYTES { return 0; }- let mut doc = match Document::load_mem(bytes) {- Ok(d) => d,- Err(_) => return 0,+ let mut doc = match load_document_lenient(bytes) {+ Some(d) => d,+ None => return 0, }; if doc.trailer.get(b"Encrypt").is_ok() && decrypt_in_place(&mut doc, password) != DecryptStatus::Ok@@ -76,6 +76,214 @@ pub(crate) fn open_document(bytes: &[u8]) -> i64 { open_document_pw(bytes, &Vec::<u8>::new()) } +/// Load a document, falling back to cross-reference reconstruction when lopdf's+/// strict parser rejects an otherwise-recoverable file.+///+/// The common real-world failure (seen with viewers that tolerate it, e.g.+/// Chrome/Acrobat) is a `startxref` offset that points a byte or two off the+/// `xref` keyword, or a damaged/incremental xref chain. lopdf's `xref` parser+/// requires the keyword at the exact offset, so such files yield+/// `InvalidFileTrailer`. On any load error we rebuild a fresh classic xref by+/// scanning the byte stream for indirect objects and append it as an+/// incremental section, then reload. This never runs for files that already+/// parse, so it cannot regress the happy path.+pub(crate) fn load_document_lenient(bytes: &[u8]) -> Option<Document> {+ if let Ok(d) = Document::load_mem(bytes) {+ return Some(d);+ }+ let rebuilt = rebuild_with_scanned_xref(bytes)?;+ Document::load_mem(&rebuilt).ok()+}++/// True for PDF whitespace / delimiter bytes (used for token-boundary checks).+fn is_pdf_ws(b: u8) -> bool {+ matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0')+}++/// Scan `bytes` for `N G obj` indirect-object headers, returning a map of+/// object id -> (generation, byte offset of the first digit of `N`). When an id+/// appears more than once (incremental updates) the highest offset wins, which+/// matches "latest definition" semantics.+fn scan_indirect_objects(bytes: &[u8]) -> std::collections::BTreeMap<u32, (u16, usize)> {+ let mut map: std::collections::BTreeMap<u32, (u16, usize)> = std::collections::BTreeMap::new();+ let n = bytes.len();+ let mut i = 0usize;+ while i + 3 <= n {+ if &bytes[i..i + 3] == b"obj"+ && (i + 3 == n || is_pdf_ws(bytes[i + 3]) || bytes[i + 3] == b'<' || bytes[i + 3] == b'[')+ {+ // Backtrack: <ws> <gen digits> <ws> <num digits>, ending just before `obj`.+ let mut p = i;+ while p > 0 && is_pdf_ws(bytes[p - 1]) {+ p -= 1;+ }+ let gen_end = p;+ while p > 0 && bytes[p - 1].is_ascii_digit() {+ p -= 1;+ }+ let gen_start = p;+ if gen_start == gen_end {+ i += 1;+ continue; // no generation number -> not a header (e.g. `endobj`)+ }+ while p > 0 && is_pdf_ws(bytes[p - 1]) {+ p -= 1;+ }+ let num_end = p;+ while p > 0 && bytes[p - 1].is_ascii_digit() {+ p -= 1;+ }+ let num_start = p;+ if num_start == num_end {+ i += 1;+ continue; // no object number+ }+ // Require the header to sit at a token boundary (start of file, or+ // preceded by whitespace / delimiter) to avoid matching digits that+ // are part of some larger token inside binary data.+ let boundary = num_start == 0 || is_pdf_ws(bytes[num_start - 1]) || bytes[num_start - 1] == b'>';+ let num = std::str::from_utf8(&bytes[num_start..num_end]).ok().and_then(|s| s.parse::<u32>().ok());+ let gen = std::str::from_utf8(&bytes[gen_start..gen_end]).ok().and_then(|s| s.parse::<u16>().ok());+ if boundary {+ if let (Some(num), Some(gen)) = (num, gen) {+ let entry = map.entry(num).or_insert((gen, num_start));+ if num_start >= entry.1 {+ *entry = (gen, num_start);+ }+ }+ }+ i += 3;+ } else {+ i += 1;+ }+ }+ map+}++/// Extract an indirect reference (`N G R`) that follows `key` inside a raw+/// trailer-dictionary byte slice.+fn ref_after_key(dict: &[u8], key: &[u8]) -> Option<(u32, u16)> {+ let pos = dict.windows(key.len()).position(|w| w == key)?;+ let mut i = pos + key.len();+ let n = dict.len();+ let skip_ws = |i: &mut usize| while *i < n && is_pdf_ws(dict[*i]) { *i += 1; };+ let read_uint = |i: &mut usize| -> Option<u64> {+ let s = *i;+ while *i < n && dict[*i].is_ascii_digit() { *i += 1; }+ if *i == s { return None; }+ std::str::from_utf8(&dict[s..*i]).ok()?.parse().ok()+ };+ skip_ws(&mut i);+ let num = read_uint(&mut i)? as u32;+ skip_ws(&mut i);+ let gen = read_uint(&mut i)? as u16;+ skip_ws(&mut i);+ if i < n && dict[i] == b'R' {+ Some((num, gen))+ } else {+ None+ }+}++/// Capture the last `trailer << ... >>` dictionary bytes (balanced `<< >>`).+fn last_trailer_dict(bytes: &[u8]) -> Option<Vec<u8>> {+ let kw = b"trailer";+ // Find the last occurrence of the `trailer` keyword.+ let mut search_from = 0usize;+ let mut last = None;+ while let Some(rel) = bytes[search_from..].windows(kw.len()).position(|w| w == kw) {+ let abs = search_from + rel;+ last = Some(abs);+ search_from = abs + kw.len();+ }+ let start_kw = last?;+ let mut i = start_kw + kw.len();+ let n = bytes.len();+ while i < n && is_pdf_ws(bytes[i]) {+ i += 1;+ }+ if i + 1 >= n || bytes[i] != b'<' || bytes[i + 1] != b'<' {+ return None;+ }+ let dict_start = i;+ let mut depth = 0i32;+ while i + 1 < n {+ if bytes[i] == b'<' && bytes[i + 1] == b'<' {+ depth += 1;+ i += 2;+ } else if bytes[i] == b'>' && bytes[i + 1] == b'>' {+ depth -= 1;+ i += 2;+ if depth == 0 {+ return Some(bytes[dict_start..i].to_vec());+ }+ } else {+ i += 1;+ }+ }+ None+}++/// Locate the object id whose body declares `/Type /Catalog` (the document root),+/// used to synthesize a trailer when none is recoverable.+fn find_catalog_id(objs: &std::collections::BTreeMap<u32, (u16, usize)>, bytes: &[u8]) -> Option<(u32, u16)> {+ for (id, (gen, off)) in objs {+ let end = (*off + 4096).min(bytes.len());+ let window = &bytes[*off..end];+ if window.windows(8).any(|w| w == b"/Catalog") {+ return Some((*id, *gen));+ }+ }+ None+}++/// Rebuild a parseable PDF by scanning for indirect objects and appending a+/// fresh classic cross-reference table + trailer pointing at the scanned+/// offsets. Returns the new byte buffer, or `None` if no usable root is found.+fn rebuild_with_scanned_xref(bytes: &[u8]) -> Option<Vec<u8>> {+ let objs = scan_indirect_objects(bytes);+ if objs.is_empty() {+ return None;+ }+ let max_id = *objs.keys().max()?;++ // Recover /Root (and optional /Info) from the existing trailer if present,+ // else from the catalog object. A freshly synthesized trailer avoids reusing+ // /Prev or /XRefStm links back to the broken xref chain.+ let trailer_dict = last_trailer_dict(bytes);+ let root = trailer_dict+ .as_deref()+ .and_then(|d| ref_after_key(d, b"/Root"))+ .or_else(|| find_catalog_id(&objs, bytes))?;+ let info = trailer_dict.as_deref().and_then(|d| ref_after_key(d, b"/Info"));++ let mut out = bytes.to_vec();+ if !out.ends_with(b"\n") {+ out.push(b'\n');+ }+ let xref_pos = out.len();+ out.extend_from_slice(b"xref\n");+ out.extend_from_slice(format!("0 {}\n", max_id + 1).as_bytes());+ for id in 0..=max_id {+ if id != 0 {+ if let Some((gen, off)) = objs.get(&id) {+ out.extend_from_slice(format!("{:010} {:05} n \n", off, gen).as_bytes());+ continue;+ }+ }+ out.extend_from_slice(b"0000000000 65535 f \n");+ }+ out.extend_from_slice(b"trailer\n<<");+ out.extend_from_slice(format!("/Size {}", max_id + 1).as_bytes());+ out.extend_from_slice(format!("/Root {} {} R", root.0, root.1).as_bytes());+ if let Some((inum, igen)) = info {+ out.extend_from_slice(format!("/Info {} {} R", inum, igen).as_bytes());+ }+ out.extend_from_slice(b">>\n");+ out.extend_from_slice(format!("startxref\n{}\n%%EOF\n", xref_pos).as_bytes());+ Some(out)+}+ pub(crate) fn page_count(handle: i64) -> i32 { let mut reg = registry() .lock()