Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
fix: open very large tagged PDFs without loading every object
Joshb0ca3deec795
diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rsindex 6938f82..e844876 100644--- a/crates/cos/src/document.rs+++ b/crates/cos/src/document.rs@@ -145,6 +145,24 @@ impl ObjectReader {pub(crate) fn try_get(&mut self, reference: ObjRef) -> Result<Arc<Object>, CosError> {let object = self.document.try_get(reference.num);+ self.evict_streams(reference.num);+ // Parsed objects stay cached (an indirect /Length or a dictionary read again costs a+ // lookup, not a parse) until the cache passes its object count or holds more than+ // STREAM_BYTES of data of its own. Streams read from the file are views into the+ // input bytes, which the document keeps anyway, so they don't count; decrypted+ // streams and strings do. Checked after failed loads too: resolving a /Length may+ // have cached large objects.+ if let Ok(mut cache) = self.document.cache.lock() {+ let data = &self.document.data;+ if cache.len() >= Self::OBJECTS || cache.values().fold(0usize, |n, o| n.saturating_add(owned_bytes(o, data, 0))) > Self::STREAM_BYTES {+ cache.clear();+ }+ }+ object+ }++ /// Keep the decoded object streams within bounds, retaining the one `num` is in.+ fn evict_streams(&mut self, num: u32) {// A missed eviction here only costs a re-parse, so never fail the read on a poisoned// lock. The editing-cache evictors propagate instead; they guard user edits.if let Ok(mut streams) = self.document.objstms.lock() {@@ -159,28 +177,48 @@ impl ObjectReader {if bytes > Self::STREAM_BYTES || streams.len() >= Self::OBJECTS {// Retain one oversized active stream so its next object does not require// decoding it again. That stream still obeys the document's decode cap.- let current = match self.document.xref_entry(reference.num) {+ let current = match self.document.xref_entry(num) {Some(XrefEntry::InStream { stream, .. }) => Some(stream),_ => None,};- streams.retain(|num, _| Some(*num) == current);+ streams.retain(|n, _| Some(*n) == current);}self.decoded_count = streams.len();}}- // Parsed objects stay cached (an indirect /Length or a dictionary read again costs a- // lookup, not a parse) until the cache passes its object count or holds more than- // STREAM_BYTES of data of its own. Streams read from the file are views into the- // input bytes, which the document keeps anyway, so they don't count; decrypted- // streams and strings do. Checked after failed loads too: resolving a /Length may- // have cached large objects.- if let Ok(mut cache) = self.document.cache.lock() {- let data = &self.document.data;- if cache.len() >= Self::OBJECTS || cache.values().fold(0usize, |n, o| n.saturating_add(owned_bytes(o, data, 0))) > Self::STREAM_BYTES {- cache.clear();+ }++ /// Whether object `num`'s source text contains `needle`, without parsing it: its slice of+ /// the decoded object stream, or the file from its offset to `endobj`. True when that can't+ /// be told cheaply (an edited object, an unreadable stream), so a scan then reads it.+ pub(crate) fn mentions(&mut self, num: u32, needle: &[u8]) -> bool {+ if self.document.overlay.contains_key(&num) {+ return true;+ }+ match self.document.entries.get(&num).cloned() {+ Some(XrefEntry::InStream { stream, index }) => {+ let Ok(stm) = self.document.objstm(stream) else { return true };+ self.evict_streams(num);+ // the object's text runs to the next object's offset (the offsets increase)+ let at = if stm.index.get(index as usize).is_some_and(|(n, _)| *n == num) {+ Some(index as usize)+ } else {+ stm.index.iter().position(|(n, _)| *n == num)+ };+ let Some(at) = at else { return true };+ let start = stm.index.get(at).map_or(0, |(_, o)| *o);+ let end = stm.index.get(at + 1).map(|(_, o)| *o).filter(|&o| o > start).unwrap_or(stm.data.len());+ stm.data.get(start..end).is_none_or(|text| find(text, needle, 0, text.len()).is_some())}+ Some(XrefEntry::InFile { offset, .. }) => {+ let data = &self.document.data;+ let start = usize::try_from(offset).unwrap_or(usize::MAX).min(data.len());+ let end = find(data, b"endobj", start, data.len()).unwrap_or(data.len());+ find(data, needle, start, end).is_some()+ }+ // free or absent: reads as null+ _ => false,}- object}}@@ -712,7 +750,7 @@ impl Document {/// that may never be used again. Keep their parse caches private and release them in/// batches. Returned objects own their data and remain valid after the next batch.pub fn scan_objects(&self) -> impl Iterator<Item = (ObjRef, Arc<Object>)> + use<> {- let numbers = self.object_numbers();+ let numbers = self.scan_order();let mut reader = self.object_reader();numbers.into_iter().map(move |num| {let reference = ObjRef::new(num, reader.document.generation(num));@@ -723,7 +761,38 @@ impl Document {/// Like [`Self::scan_objects`], preserving read errors for callers that must distinguish/// incomplete discovery from an actual null object. Caches remain private and bounded.pub fn scan_objects_checked(&self) -> impl Iterator<Item = (ObjRef, Result<Arc<Object>, CosError>)> + use<> {- self.scan_objects_subset(self.object_numbers())+ self.scan_objects_subset(self.scan_order())+ }++ /// Like [`Self::scan_objects_checked`], but only the objects whose source text contains+ /// `needle` are parsed and returned (edited objects always are). A search for objects with a+ /// given key need not parse the others: a tagged textbook's structure tree held 509 MB of+ /// `null` entries, which parsed took minutes and gigabytes. A key written with `#xx`+ /// escapes in the file is not seen.+ pub fn scan_objects_mentioning(&self, needle: &[u8]) -> impl Iterator<Item = (ObjRef, Result<Arc<Object>, CosError>)> + use<> {+ let needle = needle.to_vec();+ let mut reader = self.object_reader();+ self.scan_order().into_iter().filter_map(move |num| {+ if !reader.mentions(num, &needle) {+ return None;+ }+ let reference = ObjRef::new(num, reader.document.generation(num));+ Some((reference, reader.try_get(reference)))+ })+ }++ /// [`Self::object_numbers`] in the order a whole-file scan reads cheaply: the objects stored+ /// in the file first, by number, then each object stream's objects together, stream by+ /// stream. By number, objects of different streams interleave, and a stream larger than the+ /// scan's cache was decoded again for each of its objects (a 350 MB textbook's 509 MB object+ /// stream: 96 decodes, 44 s and gigabytes).+ pub fn scan_order(&self) -> Vec<u32> {+ let mut numbers = self.object_numbers();+ numbers.sort_by_key(|&num| match self.xref_entry(num) {+ Some(XrefEntry::InStream { stream, index }) => (1u8, stream, index),+ _ => (0, num, 0),+ });+ numbers}/// Inspect selected current objects with the same bounded cache as a whole-file scan.diff --git a/crates/cos/src/lib.rs b/crates/cos/src/lib.rsindex bb855cc..ce64c96 100644--- a/crates/cos/src/lib.rs+++ b/crates/cos/src/lib.rs@@ -53,3 +53,24 @@ pub enum CosError {#[error("this document was opened read-only with a decode limit and cannot be saved")]ReadOnlyLimit,}++#[cfg(test)]+mod decode_limit_tests {+ use super::CosError;++ #[test]+ fn a_decode_cap_is_told_from_damage() {+ assert!(CosError::Filter(pdfcraft_filters::FilterError::LimitExceeded(8).to_string()).is_decode_limit());+ assert!(!CosError::Filter("invalid deflate data".into()).is_decode_limit());+ assert!(!CosError::MissingObject(3).is_decode_limit());+ }+}++impl CosError {+ /// Whether stream data was refused only because it decodes to more than the reader's cap+ /// (a resource guard, as for a decompression bomb), not because it is damaged. The filter+ /// error's text is what [`CosError::Filter`] carries.+ pub fn is_decode_limit(&self) -> bool {+ matches!(self, CosError::Filter(m) if m.starts_with("decoded output exceeds the limit"))+ }+}diff --git a/crates/cos/tests/writer.rs b/crates/cos/tests/writer.rsindex 448cf35..6a3ff39 100644--- a/crates/cos/tests/writer.rs+++ b/crates/cos/tests/writer.rs@@ -238,3 +238,61 @@ fn page_tree_loops_in_object_streams_do_not_crash_readers() {assert!(String::from_utf8_lossy(&packed).contains("/ObjStm"));assert_eq!(hayro_pages(&packed), 1);}++/// Whole-file scans read each object stream's objects together (the objects stored in the file+/// first): by number, objects of different streams interleave, and a stream too big for the+/// scan's cache was decoded again for each of its objects (96 decodes of a 509 MB stream in a+/// 350 MB textbook: 44 s to list its signatures).+#[test]+fn scans_read_each_object_stream_together() {+ let mut doc = Document::open(Arc::new(fixture())).unwrap();+ let filler: Vec<_> = (0..600).map(|i| Object::Ref(doc.add(Object::Int(i)))).collect();+ doc.update_dict(doc.root().unwrap(), |catalog| catalog.set(b"Filler".to_vec(), Object::Array(filler))).unwrap();+ let packed = write_full(&doc, &SaveOptions::default()).unwrap();+ let back = Document::open(Arc::new(packed)).unwrap();+ let order = back.scan_order();+ let mut sorted = order.clone();+ sorted.sort_unstable();+ assert_eq!(sorted, back.object_numbers(), "every object, once");+ let keys: Vec<_> = order+ .iter()+ .map(|&n| match back.xref_entry(n) {+ Some(pdfcraft_cos::XrefEntry::InStream { stream, index }) => (1u8, stream, index),+ _ => (0, n, 0),+ })+ .collect();+ assert!(keys.windows(2).all(|w| w[0] < w[1]), "file objects by number, then stream by stream");+ assert!(keys.iter().any(|k| k.0 == 1), "the save packed objects into object streams");+ let scanned: Vec<u32> = back.scan_objects().map(|(r, _)| r.num).collect();+ assert_eq!(scanned, order);+}++/// A scan for a key parses only the objects whose text names it, in object streams and in the+/// file alike, and always the edited ones (a tagged textbook's 509 MB structure tree is never+/// parsed when looking for timestamps).+#[test]+fn a_scan_for_a_key_parses_only_objects_that_name_it() {+ let mut doc = Document::open(Arc::new(fixture())).unwrap();+ let mut marked = Dict::new();+ marked.set(b"ByteRange".to_vec(), Object::Array(vec![Object::Int(0)]));+ let kept = doc.add(Object::Dict(marked.clone()));+ let filler: Vec<_> = (0..300).map(|i| Object::Ref(doc.add(Object::Int(i)))).collect();+ // a full save writes what the catalog reaches+ doc.update_dict(doc.root().unwrap(), |catalog| {+ catalog.set(b"Marked".to_vec(), Object::Ref(kept));+ catalog.set(b"Filler".to_vec(), Object::Array(filler));+ })+ .unwrap();+ let packed = write_full(&doc, &SaveOptions::default()).unwrap();+ let mut back = Document::open(Arc::new(packed)).unwrap();+ // a full save renumbers: find the marked dictionary the long way+ let packed_one = back.scan_objects().find(|(_, o)| o.as_dict().is_some_and(|d| d.get(b"ByteRange").is_some())).unwrap().0;+ assert!(matches!(back.xref_entry(packed_one.num), Some(pdfcraft_cos::XrefEntry::InStream { .. })), "in an object stream");+ let found: Vec<u32> = back.scan_objects_mentioning(b"ByteRange").map(|(r, _)| r.num).collect();+ assert_eq!(found, vec![packed_one.num]);+ // an unsaved object is always read+ let edited = back.add(Object::Dict(marked));+ let found: Vec<u32> = back.scan_objects_mentioning(b"ByteRange").map(|(r, _)| r.num).collect();+ assert!(found.contains(&packed_one.num) && found.contains(&edited.num));+ assert!(back.scan_objects_mentioning(b"NoSuchKey").all(|(r, _)| r == edited), "only the edited one");+}diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rsindex e9fa260..37b20ee 100644--- a/crates/render/src/inspect.rs+++ b/crates/render/src/inspect.rs@@ -436,13 +436,25 @@ pub fn inspect(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocInfo, Oreturn None;}inspector.fill(&mut t);- (!doc.failed()).then_some(t)+ Some((t, doc.failed(), doc.limited()))})).ok().flatten();- if let Some(t) = lazy {- *tmp = t;- return Ok(());+ let huge = bytes.len() > LOAD_ALL_MAX;+ match lazy {+ Some((mut t, failed, limited)) if !failed || huge => {+ if limited {+ t.warnings.push("Some very large compressed data in this file was not read, so a few links or comments may be missing.".into());+ }+ if failed {+ t.warnings.push("Some of this file's structure could not be read (bookmarks, comments or fields may be missing).".into());+ }+ *tmp = t;+ return Ok(());+ }+ // the compatibility reader holds every object at once (many times the file's size)+ _ if huge => return Err("the file is too large for the compatibility reader".into()),+ _ => {}}let doc = Document::load_mem_with_options(&bytes, options).map_err(|e| e.to_string())?;Inspector::new(&doc).fill(tmp);@@ -454,6 +466,11 @@ pub fn inspect(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Result<DocInfo, OOk(info)}+/// Files larger than this never go to lopdf's load-everything reader (the fallback for files the+/// lazy reader can't read): it keeps every object in memory, many times the file's size, which+/// a phone can't give. Their lazy result is kept, with a warning, or the structure is skipped.+const LOAD_ALL_MAX: usize = 96 << 20;+// Commit auxiliary metadata only after inspection succeeds; renderer geometry is the fallback.fn inspect_structure(info: &mut DocInfo, fill: impl FnOnce(&mut DocInfo) -> Result<(), String>) {let structure = catch_unwind(AssertUnwindSafe(|| {@@ -1643,6 +1660,50 @@ mod tests {assert!(doc.get_object((3, 0)).is_err());}+ /// An object stream that decodes past the lazy reader's cap leaves its objects out without+ /// counting as damage, so inspection keeps the lazy result instead of loading every object+ /// (a 350 MB textbook with a 509 MB object stream took 7.6 GB that way).+ #[test]+ fn an_object_stream_over_the_cap_is_limited_not_failed() {+ // a well-formed file: catalog and page tree in the file, objects 3 and 5 in object stream 4+ let mut pdf = b"%PDF-1.7\n".to_vec();+ let mut records = vec![[0u8; 7]; 7];+ records[0] = [0, 0, 0, 0, 0, 255, 255];+ // the object stream (about 210 bytes) is larger than the cross-reference stream (49), so a+ // cap between the two opens the file but refuses the object stream+ let data = format!("3 0 5 2 5 ({})", "x".repeat(200));+ let objstm = format!("<< /Type /ObjStm /N 2 /First 8 /Length {} >>\nstream\n{data}\nendstream", data.len());+ let bodies: [(usize, &[u8]); 3] =+ [(1, b"<< /Type /Catalog /Pages 2 0 R >>"), (2, b"<< /Type /Pages /Kids [] /Count 0 >>"), (4, objstm.as_bytes())];+ for (id, body) in bodies {+ records[id][0] = 1;+ records[id][1..5].copy_from_slice(&(pdf.len() as u32).to_be_bytes());+ pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());+ pdf.extend_from_slice(body);+ pdf.extend_from_slice(b"\nendobj\n");+ }+ for (id, index) in [(3usize, 0u16), (5, 1)] {+ records[id][0] = 2;+ records[id][1..5].copy_from_slice(&4u32.to_be_bytes());+ records[id][5..7].copy_from_slice(&index.to_be_bytes());+ }+ let xref = pdf.len();+ records[6][0] = 1;+ records[6][1..5].copy_from_slice(&(xref as u32).to_be_bytes());+ let data: Vec<u8> = records.concat();+ pdf.extend_from_slice(format!("6 0 obj\n<< /Type /XRef /Size 7 /W [1 4 2] /Root 1 0 R /Length {} >>\nstream\n", data.len()).as_bytes());+ pdf.extend_from_slice(&data);+ pdf.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes());+ let pdf = Arc::new(pdf);+ let roomy = crate::structure::LazyStructure::new_with_limit(pdf.clone(), None, 1 << 20).unwrap();+ assert!(crate::structure::Structure::get_object(&roomy, (3, 0)).is_ok());+ assert!(!roomy.failed() && !roomy.limited());+ let tight = crate::structure::LazyStructure::new_with_limit(pdf, None, 100).unwrap();+ assert!(crate::structure::Structure::get_object(&tight, (3, 0)).is_err());+ assert!(tight.limited(), "the cap, not damage");+ assert!(!tight.failed());+ }+#[test]fn compressed_objects_and_indirect_stream_length_still_load() {let pdf = compressed_length_pdf(diff --git a/crates/render/src/structure.rs b/crates/render/src/structure.rsindex f6a0ad5..30dee71 100644--- a/crates/render/src/structure.rs+++ b/crates/render/src/structure.rs@@ -134,22 +134,34 @@ pub(crate) struct LazyStructure {// input object number (which can be sparse or hostile). Only queried objects fill slots.objects: Vec<Slot>,failed: AtomicBool,+ /// Objects skipped only because their (object) stream decodes past the cap.+ limited: AtomicBool,}impl LazyStructure {pub(crate) fn new(bytes: Arc<Vec<u8>>, password: Option<&str>) -> std::result::Result<Self, String> {- let source = Document::open_with_stream_limit(bytes, password, 256 << 20).map_err(|e| e.to_string())?;+ Self::new_with_limit(bytes, password, 256 << 20)+ }++ /// [`LazyStructure::new`] with object and cross-reference streams capped at `stream_limit` decoded bytes.+ pub(crate) fn new_with_limit(bytes: Arc<Vec<u8>>, password: Option<&str>, stream_limit: usize) -> std::result::Result<Self, String> {+ let source = Document::open_with_stream_limit(bytes, password, stream_limit).map_err(|e| e.to_string())?;if !source.repair_log().is_empty() {return Err("the structure requires compatibility repair".into());}let trailer = convert_dict(source.trailer(), 0).map_err(|e| e.to_string())?;let objects = source.object_numbers().into_iter().map(|n| (n, OnceLock::new())).collect();- Ok(Self { source, trailer, objects, failed: AtomicBool::new(false) })+ Ok(Self { source, trailer, objects, failed: AtomicBool::new(false), limited: AtomicBool::new(false) })}pub(crate) fn failed(&self) -> bool {self.failed.load(Ordering::Relaxed)}++ /// Whether some objects were left out because their data decodes past the cap.+ pub(crate) fn limited(&self) -> bool {+ self.limited.load(Ordering::Relaxed)+ }}impl Structure for LazyStructure {@@ -167,7 +179,17 @@ impl Structure for LazyStructure {}slot.1.get_or_init(|| {- let result = self.source.try_get(id.0).ok().and_then(|o| convert(&o, 0).ok()).map(Box::new);+ let result = match self.source.try_get(id.0) {+ Ok(o) => convert(&o, 0).ok().map(Box::new),+ // Too big to decode within the cap: left out, which is what the cap is for.+ // Not damage, so it doesn't send inspection to the load-everything reader+ // (on a 350 MB textbook with a 509 MB object stream that took 7.6 GB).+ Err(e) if e.is_decode_limit() => {+ self.limited.store(true, Ordering::Relaxed);+ return None;+ }+ Err(_) => None,+ };if result.is_none() {self.failed.store(true, Ordering::Relaxed);}diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rsindex 9627dbd..866994d 100644--- a/crates/sign/src/pdf.rs+++ b/crates/sign/src/pdf.rs@@ -135,8 +135,9 @@ impl DigestCache {#[cfg(test)]self.discovery_scans.fetch_add(1, std::sync::atomic::Ordering::Relaxed);let mut complete = true;- let candidates: Vec<_> = doc- .scan_objects_checked()+ // A timestamp has a /ByteRange: only objects whose text says so are parsed.+ let mut candidates: Vec<_> = doc+ .scan_objects_mentioning(b"ByteRange").filter_map(|(reference, object)| match object {Ok(object) => is_document_timestamp(&object).then_some(reference),Err(_) => {@@ -145,6 +146,8 @@ impl DigestCache {}}).collect();+ // the scan reads object streams together, not in number order+ candidates.sort_unstable_by_key(|r| r.num);if eligible&& complete&& candidates.len() <= DISCOVERY_CACHE_LIMITdiff --git a/crates/sign/src/pdf_discovery_tests.rs b/crates/sign/src/pdf_discovery_tests.rsindex 66bf7c8..856d75e 100644--- a/crates/sign/src/pdf_discovery_tests.rs+++ b/crates/sign/src/pdf_discovery_tests.rs@@ -173,7 +173,9 @@ fn reconstructed_and_unreadable_objects_are_not_cached_as_complete() {}// A single invalid keyword immediately before endobj is deliberately recovered as// Null by parse_indirect. Use a stream without endstream to exercise a real read error.- let unreadable = fixture(&[STAMP, "<< /Length 0 >>\nstream\nunterminated"]);+ // Its text names /ByteRange: the scan parses only objects that do (a timestamp needs one),+ // so an unreadable object that could be a timestamp must keep discovery incomplete.+ let unreadable = fixture(&[STAMP, "<< /Length 0 /ByteRange [0 1 2 1] >>\nstream\nunterminated"]);assert!(unreadable.repair_log().is_empty());assert!(unreadable.try_get(4).is_err());assert!(unreadable.scan_objects_checked().any(|(r, object)| r.num == 4 && object.is_err()));