Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge #4114 (fix/coderabbit-b-shared): shared DecodeBudget

aiongga52e39a5e235
diff --cc crates/audit/src/tests.rs
index 4c36d2821,3d0c80e0b..a76536532
--- a/crates/audit/src/tests.rs
+++ b/crates/audit/src/tests.rs
@@@ -593,15 -593,35 +593,48 @@@ fn reading_blocks_respect_stream_commen
}
}
+/// `/ActualText` is metadata the file's author controls: an empty or substitute replacement must
+/// not hide the glyphs a cover sits on.
+#[test]
+fn a_cover_over_text_with_empty_or_substitute_actual_text_is_found() {
+ for actual in ["()", "(nothing here)"] {
+ let content =
+ format!("/Span << /ActualText {actual} >> BDC\nBT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\nEMC\n0 g\n100 688 220 32 re f\n");
+ let findings = audit_redactions(&open(one_page(content.as_bytes(), ""))).expect("audit must run");
+ assert_eq!(findings.len(), 1, "{actual}: {findings:?}");
+ assert!(findings[0].covered_text.contains("SECRET"), "{actual}: covered_text was {:?}", findings[0].covered_text);
+ }
+}
++
+ #[test]
+ fn repeated_stream_references_share_one_decode_budget() {
+ use pdfcraft_cos::{Dict, Document, Object, Stream};
+ // One 1 MiB stream of spaces (a kilobyte on disk), named 300 times: by the page's /Contents,
+ // and by 300 draws of a form holding it.
+ let mut doc = Document::new_empty();
+ let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
+ let contents: Dict = [(b"Contents".to_vec(), Object::Array(vec![Object::Ref(spaces); 300]))].into_iter().collect();
+ assert!(crate::cover::filled_rects(&doc, &contents).is_err(), "repeated content streams");
+
+ let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
+ let form = doc.add(Stream::flate(form_dict, &vec![b' '; 1 << 20]));
+ let draws = doc.add(Stream::from_raw(Dict::new(), "/X Do ".repeat(300).into_bytes()));
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
+ let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
+ let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
+ assert!(crate::cover::filled_rects(&doc, &page).is_err(), "repeated form draws");
+ }
+
+ #[test]
+ fn form_entries_past_the_page_allowance_fail_the_audit() {
+ use pdfcraft_cos::{Dict, Document, Object, Stream};
+ // An empty form decodes to no bytes, so only the count of entries bounds drawing it again.
+ let mut doc = Document::new_empty();
+ let form_dict: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
+ let form = doc.add(Stream::from_raw(form_dict, Vec::new()));
+ let draws = doc.add(Stream::from_raw(Dict::new(), "/X Do ".repeat(pdfcraft_cos::MAX_PAGE_FORMS + 1).into_bytes()));
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
+ let resources: Dict = [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect();
+ let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
+ assert!(matches!(crate::cover::filled_rects(&doc, &page), Err(crate::AuditError::TooManyForms)));
+ }
diff --cc crates/edit/src/tests.rs
index 291f3e26e,1395fb1c3..69ee2687e
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@@ -6356,71 -6356,95 +6356,164 @@@ fn reading_keeps_dotted_leader_entries_
);
}
+#[test]
+fn added_text_is_wrapped_once_per_write() {
+ let mut doc = fixture();
+ let lines: Vec<String> = (0..40).map(|i| format!("line {i}")).collect();
+ let text = AddedText { rect: [72.0, 100.0, 300.0, 700.0], text: lines.join("\n"), size: 10.0, align: Align::Justify, ..AddedText::default() };
+ added::WRAP_CALLS.with(|c| c.set(0));
+ add_content(&mut doc, 0, &Content::Text(text)).unwrap();
+ let calls = added::WRAP_CALLS.with(std::cell::Cell::get);
+ assert!(calls <= 4, "the text was wrapped {calls} times for 40 lines");
+}
+
+/// A field tree whose every node lists its child twice is pruned in work linear in its nodes, not
+/// in its paths, and a node listing itself is visited once.
+#[test]
+fn flattening_prunes_a_field_tree_with_repeated_kids_once_per_node() {
+ let levels = 16;
+ let page = stream("", " ");
+ // 5: the flattened widget; 6…: the chain; then the hidden widget at its end, on the page.
+ let leaf = 6 + levels;
+ let fields = format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R {} 0 R] >> >>", leaf + 2);
+ let annots = format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R {leaf} 0 R] >>");
+ let mut objs: Vec<String> = vec![
+ fields,
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ annots,
+ page,
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (shown) /Rect [10 10 150 40] /F 4 /AP << /N {} 0 R >> >>", leaf + 1),
+ ];
+ for i in 0..levels {
+ let next = 7 + i;
+ objs.push(format!("<< /T (n{i}) /Kids [{next} 0 R {next} 0 R] >>"));
+ }
+ objs.push("<< /Type /Annot /Subtype /Widget /FT /Tx /T (hidden) /Rect [10 90 150 120] /F 2 >>".into());
+ objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream".into());
+ objs.push(format!("<< /T (loop) /Kids [{} 0 R] >>", leaf + 2));
+ let objs: Vec<&str> = objs.iter().map(String::as_str).collect();
+ let mut doc = build(&objs);
+ flatten::KEEP_CALLS.with(|c| c.set(0));
+ assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1);
+ let calls = flatten::KEEP_CALLS.with(std::cell::Cell::get);
+ assert!(calls <= 2 * (levels + 4), "{calls} field-tree visits");
+ let root = doc.root().unwrap();
+ let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap());
+ let left = doc.resolve(af.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().len();
+ assert_eq!(left, 2, "the chain to the hidden widget and the self-listing node stay");
+}
+
+/// A ToUnicode destination is repeated for every glyph that shows its code: a page whose text
+/// would run past the extraction budget is refused, not built in memory.
+#[test]
+fn page_text_past_the_budget_is_refused() {
+ let cmap = stream("", &format!("1 beginbfchar <41> <{}> endbfchar", "0041".repeat(256)));
+ let page = |shown: &str| {
+ let content = stream("", &format!("BT /F1 12 Tf 10 10 Td ({shown}) Tj ET"));
+ build(&[
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
+ &content,
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 6 0 R >>",
+ &cmap,
+ ])
+ };
+ let doc = page(&"A".repeat(100_000));
+ assert!(matches!(text_lines(&doc, 0), Err(EditError::Invalid(_))), "25 MB of text from a 100 kB page");
+ let doc = page("AA");
+ assert_eq!(text_lines(&doc, 0).unwrap()[0].text.len(), 512, "a page within the budget still reads");
+}
++
+ /// A one-page document from the page's /Contents and /Resources, built in code.
+ fn page_with(build: impl FnOnce(&mut Document) -> (Object, Dict)) -> Document {
+ let mut doc = Document::new_empty();
+ let pages = doc.add(Object::Null);
+ let (contents, resources) = build(&mut doc);
+ let page: Dict = [
+ (b"Type".to_vec(), Object::Name(b"Page".to_vec())),
+ (b"Parent".to_vec(), Object::Ref(pages)),
+ (b"MediaBox".to_vec(), Object::Array([0, 0, 200, 300].map(Object::from).to_vec())),
+ (b"Contents".to_vec(), contents),
+ (b"Resources".to_vec(), Object::Dict(resources)),
+ ]
+ .into_iter()
+ .collect();
+ let page = doc.add(page);
+ let tree: Dict = [
+ (b"Type".to_vec(), Object::Name(b"Pages".to_vec())),
+ (b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)])),
+ (b"Count".to_vec(), Object::Int(1)),
+ ]
+ .into_iter()
+ .collect();
+ doc.set(pages, Object::Dict(tree));
+ let catalog: Dict = [(b"Type".to_vec(), Object::Name(b"Catalog".to_vec())), (b"Pages".to_vec(), Object::Ref(pages))].into_iter().collect();
+ let catalog = doc.add(catalog);
+ doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(catalog));
+ doc
+ }
+
+ #[test]
+ fn repeated_content_references_share_one_decode_budget() {
+ // One 1 MiB stream (a kilobyte on disk) named 300 times by the page's /Contents.
+ let doc = page_with(|doc| {
+ let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
+ (Object::Array(vec![Object::Ref(spaces); 300]), Dict::new())
+ });
+ match text_lines(&doc, 0) {
+ Ok(lines) => panic!("read {} lines from more content than a page may decode", lines.len()),
+ Err(e) => assert!(matches!(e, EditError::Invalid(_)), "{e}"),
+ }
+ }
+
+ #[test]
+ fn reading_images_stops_at_the_page_record_limit() {
+ // 20 draws of a form drawing a form 20 times that draws an image 20 times: 8,000 images
+ // per level-two form, 160,000 in all, from a few hundred bytes.
+ let doc = page_with(|doc| {
+ let image: Dict = [
+ (b"Subtype".to_vec(), Object::Name(b"Image".to_vec())),
+ (b"Width".to_vec(), Object::Int(1)),
+ (b"Height".to_vec(), Object::Int(1)),
+ (b"ColorSpace".to_vec(), Object::Name(b"DeviceGray".to_vec())),
+ (b"BitsPerComponent".to_vec(), Object::Int(8)),
+ ]
+ .into_iter()
+ .collect();
+ let mut inner = doc.add(Stream::from_raw(image, vec![0]));
+ let draws = "/X Do ".repeat(20);
+ let resources = |inner: pdfcraft_cos::ObjRef| -> Dict {
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(inner))].into_iter().collect();
+ [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect()
+ };
+ for _ in 0..3 {
+ let mut d = resources(inner);
+ d = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec())), (b"Resources".to_vec(), Object::Dict(d))].into_iter().collect();
+ inner = doc.add(Stream::from_raw(d, draws.clone().into_bytes()));
+ }
+ let page = doc.add(Stream::from_raw(Dict::new(), draws.into_bytes()));
+ (Object::Ref(page), resources(inner))
+ });
+ if let Ok(images) = crate::reading_images(&doc, 0) {
+ assert!(images.len() <= crate::images::MAX_PAGE_IMAGES, "{} images", images.len());
+ }
+ }
+
+ #[test]
+ fn reading_spends_one_decode_budget_on_content_and_forms() {
+ // 130 MiB of content and a 130 MiB form (a kilobyte each on disk): each fits a page's budget,
+ // together they don't, so reading leaves the form out and says so.
+ let doc = page_with(|doc| {
+ let mut body = b"%".to_vec();
+ body.resize(130 << 20, b'x');
+ let form: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
+ let form = doc.add(Stream::flate(form, &body));
+ let mut content = b"/X Do\n%".to_vec();
+ content.resize(130 << 20, b'x');
+ let content = doc.add(Stream::flate(Dict::new(), &content));
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
+ (Object::Ref(content), [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect())
+ });
+ assert!(crate::text::reading_blocks_checked(&doc, 0).unwrap().truncated);
+ }
diff --cc crates/edit/src/text.rs
index 99e6a3e0f,1f35bcd47..8c025fae8
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@@ -1309,10 -1299,10 +1324,10 @@@ fn text_lines_in(doc: &Document, p: &pd
let mut carry = Carry::new();
// The streams are one stream in pieces (§7.8.2), split between any two tokens: parse them
// joined, so an operator whose operands end one piece still has them.
- let pieces = Pieces::join(&content_streams(doc, &p.dict).into_iter().map(|(_, d)| d).collect::<Vec<_>>());
+ let pieces = Pieces::join(&content_streams(doc, &p.dict)?.into_iter().map(|(_, d)| d).collect::<Vec<_>>());
let ops = pieces.parse().ops;
let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default();
- let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, Some(&properties))?;
+ let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?;
let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run ended
for mut s in shown {
// A single RTL glyph's ActualText (e.g. lam-alef) is an inline ligature, not a
diff --cc crates/organize/src/tests.rs
index 2dbe8a4d6,bc833257f..9ce128432
--- a/crates/organize/src/tests.rs
+++ b/crates/organize/src/tests.rs
@@@ -3133,116 -3133,42 +3133,156 @@@ fn page_walk_skips_repeated_and_cyclic_
assert_eq!(labels(&doc), ["Page 1", "Page 2", "Page 3"]);
}
+/// A one-page document whose page carries `annots` (object bodies 5…), with `extra` bodies after them.
+fn page_with_annots(annots: &[String], extra: &[String], catalog_extra: &str) -> Document {
+ let n = annots.len();
+ let refs: String = (0..n).map(|i| format!("{} 0 R ", i + 5)).collect();
+ let mut b: Vec<String> = vec![
+ format!("<< /Type /Catalog /Pages 2 0 R {catalog_extra} >>"),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
+ format!("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Annots [{refs}] >>"),
+ body("P1"),
+ ];
+ b.extend(annots.iter().cloned());
+ b.extend(extra.iter().cloned());
+ open(build(&b, "/Root 1 0 R"))
+}
+
+#[test]
+fn registering_many_imported_fields_is_linear() {
+ let n = 2_000;
+ let widgets: Vec<String> = (0..n).map(|i| format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (f{i}) /Rect [0 0 10 10] >>")).collect();
+ let src = page_with_annots(&widgets, &[], "");
+ take_work();
+ let out = extract_pages(&src, &[0]).unwrap();
+ let work = take_work();
+ assert!(work <= 4 * n, "{work} steps registering {n} fields");
+ let form = out.resolve(catalog(&out).get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();
+ assert_eq!(form.get(b"Fields").and_then(|f| f.as_array()).map(Vec::len), Some(n));
+}
+
+#[test]
+fn renaming_many_same_named_fields_resumes_the_suffix_search() {
+ let n = 2_000;
+ let widgets: Vec<String> = (0..n).map(|_| "<< /Type /Annot /Subtype /Widget /FT /Tx /T (x) /Rect [0 0 10 10] >>".to_string()).collect();
+ let src = page_with_annots(&widgets, &[], "");
+ take_work();
+ let renames = combine_field_conflicts(&[&src]).remove(0);
+ let work = take_work();
+ assert!(work <= 4 * n, "{work} suffix attempts for {n} fields");
+ // Still the first free variant, in order.
+ assert_eq!(renames.len(), n - 1);
+ assert_eq!(renames.first(), Some(&("x".to_string(), "x-1".to_string())));
+ assert_eq!(renames.last(), Some(&("x".to_string(), format!("x-{}", n - 1))));
+}
+
+#[test]
+fn annotation_actions_share_the_objects_they_copy() {
+ // Fifty links whose URI actions all point at one string object.
+ let n = 50;
+ let links: Vec<String> =
+ (0..n).map(|_| format!("<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI {} 0 R >> >>", n + 5)).collect();
+ let src = page_with_annots(&links, &["(https://example.com/shared)".into()], "");
+ let out = extract_pages(&src, &[0]).unwrap();
+ let copies = out
+ .object_numbers()
+ .into_iter()
+ .filter(|&o| out.get(ObjRef::new(o, out.generation(o))).as_string().is_some_and(|s| s.bytes == b"https://example.com/shared"))
+ .count();
+ assert_eq!(copies, 1, "the shared URI is copied once, not once per action");
+}
+
+#[test]
+fn name_trees_with_shared_kids_are_walked_once_per_node() {
+ // Each level lists the next one twice: 2^depth paths through `depth` nodes.
+ let depth = 10;
+ let first = 6; // after the catalog, pages, page, content and the link
+ let mut extra = Vec::new();
+ for tree in 0..2 {
+ let base = first + tree * (depth + 1);
+ for level in 0..depth {
+ let next = base + level + 1;
+ extra.push(format!("<< /Kids [{next} 0 R {next} 0 R] >>"));
+ }
+ extra.push(if tree == 0 {
+ "<< /Names [(a.txt) << /Type /Filespec /F (a.txt) >>] >>".into()
+ } else {
+ "<< /Names [(other) [3 0 R /Fit]] >>".into()
+ });
+ }
+ let link = "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /Dest (missing) >>".to_string();
+ let catalog_extra = format!("/Names << /EmbeddedFiles {first} 0 R /Dests {} 0 R >>", first + depth + 1);
+ let src = page_with_annots(&[link], &extra, &catalog_extra);
+ take_work();
+ let out = combine(&[("a", &src)]).unwrap();
+ let work = take_work();
+ assert!(work <= 8 * (depth + 1), "{work} name-tree nodes visited");
+ let names = out.resolve(catalog(&out).get(b"Names").unwrap()).as_dict().cloned().unwrap();
+ let tree = out.resolve(names.get(b"EmbeddedFiles").unwrap()).as_dict().cloned().unwrap();
+ assert_eq!(tree.get(b"Names").and_then(|n| n.as_array()).map(Vec::len), Some(2), "one attachment, listed once");
+}
+
+#[test]
+fn a_form_drawing_itself_repeatedly_is_analysed_once() {
+ let form = "/F Do /F Do /F Do /F Do";
+ let b: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /F 5 0 R /Unused 6 0 R >> >> >>".into(),
+ "<< /Length 5 >>\nstream\n/F Do\nendstream".into(),
+ format!(
+ "<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /XObject << /F 5 0 R >> >> /Length {} >>\nstream\n{form}\nendstream",
+ form.len()
+ ),
+ "<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Length 0 >>\nstream\n\nendstream".into(),
+ ];
+ let src = open(build(&b, "/Root 1 0 R"));
+ take_work();
+ let out = extract_pages(&src, &[0]).unwrap();
+ let work = take_work();
+ assert!(work <= 4, "{work} form analyses");
+ let page = out.get(pages(&out).unwrap()[0].obj).as_dict().cloned().unwrap();
+ let res = out.resolve(page.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
+ let x = out.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
+ assert!(x.contains(b"F") && !x.contains(b"Unused"), "pruning still keeps what is drawn and drops the rest");
+}
++
+ /// One page whose /Contents names the same 1 MiB stream 300 times (a few kilobytes on disk).
+ fn repeated_contents() -> Document {
+ use pdfcraft_cos::{Dict, Stream};
+ let mut doc = Document::new_empty();
+ let stream = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
+ let pages = doc.add(Object::Null);
+ let page: Dict = [
+ (b"Type".to_vec(), Object::Name(b"Page".to_vec())),
+ (b"Parent".to_vec(), Object::Ref(pages)),
+ (b"MediaBox".to_vec(), Object::Array([0, 0, 200, 300].map(Object::from).to_vec())),
+ (b"Contents".to_vec(), Object::Array(vec![Object::Ref(stream); 300])),
+ ]
+ .into_iter()
+ .collect();
+ let page = doc.add(page);
+ let tree: Dict = [
+ (b"Type".to_vec(), Object::Name(b"Pages".to_vec())),
+ (b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)])),
+ (b"Count".to_vec(), Object::Int(1)),
+ ]
+ .into_iter()
+ .collect();
+ doc.set(pages, Object::Dict(tree));
+ let catalog: Dict = [(b"Type".to_vec(), Object::Name(b"Catalog".to_vec())), (b"Pages".to_vec(), Object::Ref(pages))].into_iter().collect();
+ let catalog = doc.add(catalog);
+ doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(catalog));
+ doc
+ }
+
+ #[test]
+ fn repeated_content_references_share_one_decode_budget() {
+ let src = repeated_contents();
+ let mut dst = Document::new_empty();
+ if let Ok((form, _)) = page_as_form(&mut dst, &src, 0) {
+ let Object::Stream(s) = &*dst.get(form) else { panic!("not a stream") };
+ let len = s.decoded().unwrap().len();
+ assert!(len <= pdfcraft_cos::MAX_PAGE_DECODED + 300, "{len} bytes");
+ }
+ }