Skip to content

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

Merge main into fix/coderabbit-c5-forms-misc

Dylan M. Taylor93b25f67a6d4
diff --cc crates/annot/src/tests.rs
index 017e06671,6eb94b830..b39e41c60
--- a/crates/annot/src/tests.rs
+++ b/crates/annot/src/tests.rs
@@@ -1505,57 -1505,65 +1505,120 @@@ fn typed_signature_uses_nonzero_winding
assert!(!ap.contains("f*"), "must not use even-odd fill (`f*`): {ap}");
}
+/// Many page tree nodes sharing one `/Kids` array read it once, not once per node.
+#[test]
+fn page_walk_reads_a_shared_kids_array_once() {
+ let mut doc = fixture();
+ let root = ObjRef { num: 2, generation: 0 };
+ let (first, second) = (ObjRef { num: 3, generation: 0 }, ObjRef { num: 4, generation: 0 });
+ let shared = doc.add(Object::Array([Object::Ref(first), Object::Ref(second)].into_iter().cycle().take(2_000).collect()));
+ let nodes: Vec<Object> = (0..1_000)
+ .map(|_| {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Pages"));
+ d.set(b"Kids".to_vec(), Object::Ref(shared));
+ Object::Ref(doc.add(d))
+ })
+ .collect();
+ doc.update_dict(root, |d| d.set(b"Kids".to_vec(), Object::Array(nodes))).unwrap();
+ let mut walk = PageWalk::new(&doc, root);
+ let pages: Vec<ObjRef> = walk.by_ref().collect();
+ assert_eq!(pages, [first, second]);
+ assert!(walk.examined <= 10_000, "{} kids entries read", walk.examined);
+}
+
+/// Adding many links to a page extends its `/Annots` once, not once per link.
+#[test]
+fn many_links_extend_a_page_annotation_list_once() {
+ let mut doc = fixture();
+ let before = annots(&doc, page_refs(&doc).unwrap()[0]).len();
+ let n = 2_000;
+ let rects: Vec<[f64; 4]> = (0..n).map(|i| [10.0, i as f64 * 0.1, 50.0, i as f64 * 0.1 + 5.0]).collect();
+ ANNOTS_ENTRIES_COPIED.with(|c| c.set(0));
+ let added = links::add_many(&mut doc, &[(0, rects, "https://example.com".into())], &links::LinkStyle::default()).unwrap();
+ let copied = ANNOTS_ENTRIES_COPIED.with(std::cell::Cell::get);
+ assert_eq!(added, n);
+ assert_eq!(annots(&doc, page_refs(&doc).unwrap()[0]).len(), before + n);
+ assert!(copied <= 4 * n, "{copied} annotation entries copied for {n} links");
+}
+
+/// A batch with one bad entry adds nothing: no link objects are left behind unattached.
+#[test]
+fn a_link_batch_with_a_bad_entry_creates_no_objects() {
+ let mut doc = fixture();
+ let page = page_refs(&doc).unwrap()[0];
+ let before = (annots(&doc, page).len(), doc.scan_objects().count());
+ let good = [10.0, 10.0, 50.0, 20.0];
+ let style = links::LinkStyle::default();
+ for bad in [
+ vec![(0, vec![good], "https://example.com".to_string()), (0, vec![good, [f64::NAN, 0.0, 10.0, 10.0]], "https://example.com".into())],
+ vec![(0, vec![good], "https://example.com".to_string()), (0, vec![good], " ".into())],
+ vec![(0, vec![good], "https://example.com".to_string()), (99, vec![good], "https://example.com".into())],
+ ] {
+ assert!(links::add_many(&mut doc, &bad, &style).is_err());
+ assert_eq!((annots(&doc, page).len(), doc.scan_objects().count()), before);
+ }
+}
++
+ fn doc_of(objs: &[String]) -> Document {
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ Document::open(Arc::new(out)).expect("opens")
+ }
+
+ #[test]
+ fn link_listing_skips_repeated_refs_and_caps_web_address_text() {
+ // One link referenced 1000 times, and 300 small links sharing one 64 KiB address.
+ let annots = format!("{}{}", " 4 0 R".repeat(1000), "<< /Subtype /Link /Rect [0 0 1 1] /A 5 0 R >>".repeat(300));
+ let doc = doc_of(&[
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
+ "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A 5 0 R >>".into(),
+ "<< /S /URI /URI 6 0 R >>".into(),
+ format!("({})", "u".repeat(64 << 10)),
+ ]);
+ let all = links::list(&doc);
+ assert_eq!(all.iter().filter(|l| l.obj == Some(ObjRef::new(4, 0))).count(), 1);
+ assert_eq!(all.len(), 301, "every distinct link is still listed");
+ let kept: usize = all.iter().map(|l| if let links::LinkAction::Uri(u) = &l.action { u.len() } else { 0 }).sum();
+ assert!(kept <= links::MAX_URI_BYTES, "{kept} bytes of web addresses kept");
+ assert!(matches!(&all[0].action, links::LinkAction::Uri(u) if u.len() == 64 << 10));
+ }
+
+ #[test]
+ fn web_address_cap_counts_the_text_kept_after_conversion() {
+ // 200 links sharing a 64 KiB address of invalid UTF-8: 12.5 MiB of bytes, each byte kept as a
+ // three-byte replacement character.
+ let annots = "<< /Subtype /Link /Rect [0 0 1 1] /A 4 0 R >>".repeat(200);
+ let doc = doc_of(&[
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),
+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
+ "<< /S /URI /URI 5 0 R >>".into(),
+ format!("<{}>", "FF".repeat(64 << 10)),
+ ]);
+ let all = links::list(&doc);
+ assert_eq!(all.len(), 200);
+ let kept: usize = all.iter().map(|l| if let links::LinkAction::Uri(u) = &l.action { u.len() } else { 0 }).sum();
+ assert!(kept <= links::MAX_URI_BYTES, "{kept} bytes of web addresses kept");
+ assert!(kept > 0);
+ }
+
+ #[test]
+ fn cloud_outline_has_a_bump_budget() {
+ // 50 long edges would each ask for 10,000 bumps of radius 1.
+ let pts: Vec<(f64, f64)> = (0..50).map(|i| (f64::from(i) * std::f64::consts::TAU / 50.0).sin_cos()).map(|(s, c)| (1e7 * c, 1e7 * s)).collect();
+ let bumps = appearance::cloud_path(&pts, 1.0).lines().filter(|l| l.ends_with(" c")).count();
+ assert!((pts.len()..=appearance::MAX_CLOUD_BUMPS + 2 * pts.len()).contains(&bumps), "{bumps} bumps");
+ }
diff --cc crates/content/src/lib.rs
index ab42728c2,0459fbe89..bb478d18e
--- a/crates/content/src/lib.rs
+++ b/crates/content/src/lib.rs
@@@ -92,142 -89,100 +95,152 @@@ pub fn ops(data: &[u8]) -> Ops<'_>
/// Parse `data`, recording which of the piece boundaries `ends` (as in [`Pieces`]) a comment
/// crosses.
fn parse_pieces(data: &[u8], ends: &[usize]) -> Parsed {
- let mut out = Parsed { comment_edges: vec![(false, false); ends.len()], ..Parsed::default() };
- let mut boundary = 0;
- let mut lx = Lexer::new(data, 0);
- let mut operands: Vec<Object> = Vec::new();
- let mut start: Option<usize> = None;
- loop {
- let trivia = lx.pos;
- lx.skip_ws();
- // Only the whitespace the lexer skips here holds top-level comments: a `%` inside a
- // string, a name, an array or dictionary operand or inline image data is not one.
- if boundary < ends.len() {
- comment_edges(data, trivia..lx.pos, ends, &mut boundary, &mut out.comment_edges);
+ let mut reader = Ops::new(data, ends);
+ let ops = reader.by_ref().collect();
+ Parsed { ops, skipped: reader.skipped, ambiguous_images: reader.ambiguous_images, comment_edges: reader.comment_edges }
+}
+
+/// The iterator [`ops`] returns.
+pub struct Ops<'a> {
+ data: &'a [u8],
+ lx: Lexer<'a>,
+ operands: Vec<Object>,
+ start: Option<usize>,
+ skipped: usize,
+ ambiguous_images: usize,
+ ends: &'a [usize],
+ boundary: usize,
+ comment_edges: Vec<(bool, bool)>,
+}
+
+impl<'a> Ops<'a> {
+ fn new(data: &'a [u8], ends: &'a [usize]) -> Self {
+ Ops {
+ data,
+ lx: Lexer::new(data, 0),
+ operands: Vec::new(),
+ start: None,
+ skipped: 0,
+ ambiguous_images: 0,
+ ends,
+ boundary: 0,
+ comment_edges: vec![(false, false); ends.len()],
}
- let Some(&b) = data.get(lx.pos) else { break };
- let at = lx.pos;
- let operand_start = matches!(b, b'/' | b'(' | b'<' | b'[' | b'+' | b'-' | b'.') || b.is_ascii_digit();
- if operand_start {
- match lx.object() {
- Ok(o) => {
- start.get_or_insert(at);
- operands.push(o);
- }
- Err(_) if b == b'(' => {
- // An unterminated string runs to the end of the stream.
- out.skipped += data.len() - at;
- lx.pos = data.len();
- }
- Err(_) => {
- let read = lx.pos.saturating_sub(at);
- #[cfg(test)]
- tests::RESCANNED.with(|c| c.set(c.get() + read));
- let number = matches!(b, b'+' | b'-' | b'.') || b.is_ascii_digit();
- if number && read > MAX_RETRIED_TOKEN {
- // A long unreadable number is skipped whole: retrying from each of its
- // bytes would read the rest of it again every time.
- out.skipped += read;
- } else {
- // Skip the offending byte and carry on.
- lx.pos = at + 1;
- out.skipped += 1;
+ }
+
+ /// Bytes read so far that could not be read as operands or operators.
+ pub fn skipped(&self) -> usize {
+ self.skipped
+ }
+
+ /// Inline images read so far whose end is this parser's guess (as in
+ /// [`Parsed::ambiguous_images`]).
+ pub fn ambiguous_images(&self) -> usize {
+ self.ambiguous_images
+ }
+}
+
+impl Iterator for Ops<'_> {
+ type Item = Op;
+
+ fn next(&mut self) -> Option<Op> {
+ let Ops { data, lx, operands, start, skipped, ambiguous_images, ends, boundary, comment_edges: edges } = self;
+ let (data, ends): (&[u8], &[usize]) = (data, ends);
+ loop {
+ let trivia = lx.pos;
+ lx.skip_ws();
+ // Only the whitespace the lexer skips here holds top-level comments: a `%` inside a
+ // string, a name, an array or dictionary operand or inline image data is not one.
+ if *boundary < ends.len() {
+ comment_edges(data, trivia..lx.pos, ends, boundary, edges);
+ }
+ let Some(&b) = data.get(lx.pos) else {
+ // Operands left without an operator.
+ *skipped += operands.len();
+ operands.clear();
+ return None;
+ };
+ let at = lx.pos;
+ let operand_start = matches!(b, b'/' | b'(' | b'<' | b'[' | b'+' | b'-' | b'.') || b.is_ascii_digit();
+ if operand_start {
+ match lx.object() {
+ Ok(o) => {
+ start.get_or_insert(at);
+ operands.push(o);
+ }
+ Err(_) if b == b'(' => {
+ // An unterminated string runs to the end of the stream.
+ *skipped += data.len() - at;
+ lx.pos = data.len();
+ }
+ Err(_) => {
- // Skip the offending byte and carry on.
- lx.pos = at + 1;
- *skipped += 1;
++ let read = lx.pos.saturating_sub(at);
++ #[cfg(test)]
++ tests::RESCANNED.with(|c| c.set(c.get() + read));
++ let number = matches!(b, b'+' | b'-' | b'.') || b.is_ascii_digit();
++ if number && read > MAX_RETRIED_TOKEN {
++ // A long unreadable number is skipped whole: retrying from each of its
++ // bytes would read the rest of it again every time.
++ *skipped += read;
++ } else {
++ // Skip the offending byte and carry on.
++ lx.pos = at + 1;
++ *skipped += 1;
++ }
}
}
+ continue;
}
- continue;
- }
- if is_delim(b) {
- // A stray `)`, `>`, `]`, `{`, `}`.
- lx.pos += 1;
- out.skipped += 1;
- continue;
- }
- let kw = lx.token();
- if kw.is_empty() {
- lx.pos = at + 1;
- out.skipped += 1;
- continue;
- }
- match kw {
- b"true" => {
- start.get_or_insert(at);
- operands.push(Object::Bool(true));
- }
- b"false" => {
- start.get_or_insert(at);
- operands.push(Object::Bool(false));
+ if is_delim(b) {
+ // A stray `)`, `>`, `]`, `{`, `}`.
+ lx.pos += 1;
+ *skipped += 1;
+ continue;
}
- b"null" => {
- start.get_or_insert(at);
- operands.push(Object::Null);
+ let kw = lx.token();
+ if kw.is_empty() {
+ lx.pos = at + 1;
+ *skipped += 1;
+ continue;
}
- b"BI" => {
- let image = inline_image(data, at, lx.pos);
- out.ambiguous_images += usize::from(image.ambiguous);
- let end = image.end;
- lx.pos = end;
- match image.image {
- Some((dict, img)) => {
- out.ops.push(Op {
- op: b"BI".to_vec(),
- operands: Vec::new(),
- inline: Some((dict, img)),
- span: start.take().unwrap_or(at)..end,
- });
- }
- None => {
- out.skipped += end.saturating_sub(at);
- start = None;
+ match kw {
+ b"true" => {
+ start.get_or_insert(at);
+ operands.push(Object::Bool(true));
+ }
+ b"false" => {
+ start.get_or_insert(at);
+ operands.push(Object::Bool(false));
+ }
+ b"null" => {
+ start.get_or_insert(at);
+ operands.push(Object::Null);
+ }
+ b"BI" => {
+ let image = inline_image(data, at, lx.pos);
+ *ambiguous_images += usize::from(image.ambiguous);
+ let end = image.end;
+ lx.pos = end;
+ operands.clear();
+ match image.image {
+ Some((dict, img)) => {
+ return Some(Op {
+ op: b"BI".to_vec(),
+ operands: Vec::new(),
+ inline: Some((dict, img)),
+ span: start.take().unwrap_or(at)..end,
+ });
+ }
+ None => {
+ *skipped += end.saturating_sub(at);
+ *start = None;
+ }
}
}
- operands.clear();
- }
- _ => {
- let s = start.take().unwrap_or(at);
- out.ops.push(Op { op: kw.to_vec(), operands: std::mem::take(&mut operands), inline: None, span: s..lx.pos });
+ _ => {
+ let s = start.take().unwrap_or(at);
+ return Some(Op { op: kw.to_vec(), operands: std::mem::take(operands), inline: None, span: s..lx.pos });
+ }
}
}
}
diff --cc crates/forms/src/tests.rs
index 2b2042865,b2b8573eb..6a7c04492
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@@ -2982,19 -2982,42 +2982,59 @@@ fn page_walk_skips_repeated_and_cyclic_
assert_eq!(page_refs(&doc), [page]);
}
+/// A Calculate script naming thousands of fields is merged with the field's other reads in one
+/// pass, not by searching the names so far for each one.
+#[test]
+fn a_script_reading_many_fields_merges_its_reads_in_one_pass() {
+ use crate::calc_order::NAMES_COMPARED;
+ let mut doc = one_page();
+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &NewField::Text { multiline: false }, Some("total")).unwrap();
+ let n = 2_000;
+ let script: String = (0..n).map(|i| format!("getField(\"f{i}\").value + ")).collect::<String>() + "0";
+ set_field_script(&mut doc, "total", "calculate", Some(&format!("event.value = {script};"))).unwrap();
+ NAMES_COMPARED.with(|c| c.set(0));
+ let order = calculation_order(&doc, &fields(&doc));
+ assert_eq!(order.fields[0].reads.len(), n);
+ let compared = NAMES_COMPARED.with(std::cell::Cell::get);
+ assert!(compared <= 4 * n, "{compared} names compared for {n} reads");
+}
++
+ /// 300 fields and 300 document scripts that all name one 1 MiB JavaScript stream.
+ fn repeated_script_references() -> Document {
+ use pdfcraft_cos::Stream;
+ let dict = |entries: Vec<(&[u8], Object)>| -> Object { Object::Dict(entries.into_iter().map(|(k, v)| (k.to_vec(), v)).collect()) };
+ let mut doc = Document::new_empty();
+ let js = doc.add(Stream::flate(pdfcraft_cos::Dict::new(), &vec![b'x'; 1 << 20]));
+ let action = doc.add(dict(vec![(b"S", Object::Name(b"JavaScript".to_vec())), (b"JS", Object::Ref(js))]));
+ let fields: Vec<Object> = (0..300)
+ .map(|i| {
+ Object::Ref(doc.add(dict(vec![
+ (b"FT", Object::Name(b"Tx".to_vec())),
+ (b"T", Object::String(pdfcraft_cos::PdfString::literal(format!("f{i}")))),
+ (b"Rect", Object::Array([0, 0, 10, 10].map(Object::from).to_vec())),
+ (b"AA", dict(vec![(b"C", Object::Ref(action))])),
+ ])))
+ })
+ .collect();
+ let names: Vec<Object> =
+ (0..300).flat_map(|i| [Object::String(pdfcraft_cos::PdfString::literal(format!("s{i:03}"))), Object::Ref(action)]).collect();
+ let catalog = doc.add(dict(vec![
+ (b"Type", Object::Name(b"Catalog".to_vec())),
+ (b"AcroForm", dict(vec![(b"Fields", Object::Array(fields))])),
+ (b"Names", dict(vec![(b"JavaScript", dict(vec![(b"Names", Object::Array(names))]))])),
+ ]));
+ doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(catalog));
+ doc
+ }
+
+ #[test]
+ fn repeated_script_references_share_one_decode_budget() {
+ let doc = repeated_script_references();
+ let limit = MAX_SCRIPT_BYTES;
+ let named: usize = document_scripts_named(&doc).iter().map(|(_, js)| js.len()).sum();
+ assert!(named > 0 && named <= limit, "{named} bytes of document scripts");
+ let all = fields(&doc);
+ assert_eq!(all.len(), 300);
+ let calculate: usize = all.iter().filter_map(|f| f.actions.scripts.calculate.as_ref()).map(String::len).sum();
+ assert!(calculate > 0 && calculate <= limit, "{calculate} bytes of field scripts");
+ }
diff --cc crates/measure/src/tests.rs
index 259caeb5f,e9722cb62..8d69a05cf
--- a/crates/measure/src/tests.rs
+++ b/crates/measure/src/tests.rs
@@@ -403,27 -403,36 +403,61 @@@ fn a_scale_ratio_converts_its_page_side
assert!(Scale::ratio([0.0, 0.0], [1.0, 0.0], page, PageUnit::Mm, real, "mm", 2).is_err(), "{page} {real}");
}
}
+/// A content stream reads its `/XObject` resources once, not again (as a copy of a direct
+/// dictionary) for every `Do`.
+#[test]
+fn xobject_resources_are_read_once_per_stream() {
+ let d = fixture(&"/Missing Do\n".repeat(10_000), "", &[]);
+ snap::XOBJECT_DICT_READS.with(|c| c.set(0));
+ let paths = snap::geometry(&d, 0).unwrap();
+ assert!(paths.segments.is_empty());
+ let reads = snap::XOBJECT_DICT_READS.with(std::cell::Cell::get);
+ assert!(reads <= 1, "{reads} reads of the page's XObject resources");
+}
+/// Finding the scale under a point reads only well-formed viewport boxes, and only as many
+/// viewports as a page can be given, however many a file lists or however long their boxes.
+#[test]
+fn scale_lookup_reads_viewports_within_bounds() {
+ let vp = vec!["5 0 R"; 5_000].join(" ");
+ let long_box = vec!["0"; 2_000].join(" ");
+ let d = fixture("", &format!("/VP [{vp}]"), &["<< /Type /Viewport /BBox 6 0 R >>", &format!("[{long_box}]")]);
+ VIEWPORT_NUMBERS_READ.with(|c| c.set(0));
+ let scale = scale_at(&d, 0, [10.0, 10.0]).unwrap();
+ assert_eq!(scale.unit, "in");
+ let read = VIEWPORT_NUMBERS_READ.with(std::cell::Cell::get);
+ assert!(read <= 4 * 1024, "{read} viewport numbers read");
+}
++
+ #[test]
+ fn listing_skips_repeated_refs_and_caps_what_it_keeps() {
+ let mut d = fixture("", "", &[]);
+ let points: Vec<Point> = (0..MAX_POINTS).map(|i| [i as f64 * 0.1, 0.0]).collect();
+ add(&mut d, &new(Kind::Perimeter, points), &Meta::default()).unwrap();
+ let (r, mut annotation) = annot(&d, 0, 0).unwrap();
+ let page = pdfcraft_model::pages(&d)[0].obj;
+ let set_annots = |d: &mut Document, list: Vec<Object>| d.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Array(list))).unwrap();
+ // One annotation referenced 1000 times is one measurement.
+ set_annots(&mut d, vec![Object::Ref(r); 1000]);
+ assert_eq!(list(&d).measurements.len(), 1);
+ // Many small annotations sharing one 2048-point vertex array stop at the retained budget.
+ let vertices = d.add(annotation.get(b"Vertices").unwrap().clone());
+ annotation.set(b"Vertices".to_vec(), Object::Ref(vertices));
+ set_annots(&mut d, vec![Object::Dict(annotation); 1200]);
+ let listing = list(&d);
+ assert!(listing.truncated);
+ assert!(listing.measurements.iter().map(retained).sum::<usize>() <= MAX_LISTED_BYTES);
+ assert!(!listing.measurements.is_empty());
+ }
+ #[test]
+ fn a_stream_over_the_byte_budget_uses_it_up_once() {
+ // 50 references to one Flate stream that inflates past the 16 MiB budget decode once.
+ let big = pdfcraft_cos::Stream::flate(Dict::new(), &vec![b' '; 17 << 20]);
+ let hex: String = big.raw.iter().map(|b| format!("{b:02x}")).collect();
+ let bomb = String::from_utf8(pdfcraft_testkit::stream_obj("/Filter [/ASCIIHexDecode /FlateDecode]", hex)).unwrap();
+ let contents = format!("[4 0 R{}]", " 5 0 R".repeat(50));
+ let d = fixture_with(&contents, "0 0 m 10 0 l S", "", &[bomb.as_str()]);
+ let g = snap::geometry(&d, 0).unwrap();
+ assert_eq!(g.unreadable, 1);
+ assert!(g.truncated);
+ assert_eq!(g.segments.len(), 1, "the parts before it still snap");
+ }
diff --cc crates/preflight/src/tests.rs
index 874f6bbee,efd55f28e..52e6903e6
--- a/crates/preflight/src/tests.rs
+++ b/crates/preflight/src/tests.rs
@@@ -418,61 -418,14 +418,73 @@@ fn oversized_xmp_is_refused_while_decod
assert!(metadata(&doc).is_none(), "compressed metadata must be limited during decoding");
}
+/// Content is read one operator at a time and no further than it needs: once gray, RGB and CMYK
+/// are all set, the rest of the stream is not read.
+#[test]
+fn content_colour_reads_operators_one_at_a_time_and_stops_when_all_are_found() {
+ let mut data = b"0 g 0 0 0 rg 0 0 0 0 k\n".to_vec();
+ data.extend(b"n\n".repeat(100_000));
+ let mut used = DeviceColour::default();
+ let read = content_colour(&data, &mut used);
+ assert!(used.gray && used.rgb && used.cmyk);
+ assert_eq!(read, 3);
+}
+
+/// A forbidden action chained by `/Next` behind an allowed one, written directly inside its
+/// parent, is reported and removed like any other.
+#[test]
+fn forbidden_actions_chained_behind_allowed_ones_are_found_and_removed() {
+ let js = "<< /S /JavaScript /JS (app.alert(1)) >>";
+ let page = "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>";
+ let pages = "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>";
+ let link = |a: &str| format!("<< /Type /Annot /Subtype /Link /Rect [0 0 0 0] /P 3 0 R /F 4 /A {a} >>");
+ let open_action = format!("<< /Type /Catalog /Pages 2 0 R /OpenAction << /S /GoTo /D [3 0 R /Fit] /Next {js} >> >>");
+ let goto = format!("<< /Type /Action /S /GoTo /D [3 0 R /Fit] /Next [{js}] >>");
+ let cases = [
+ build(&[&open_action, pages, page, &link("<< /S /GoTo /D [3 0 R /Fit] >>")], ""),
+ build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, &link("5 0 R"), &goto], ""),
+ build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, &link(&format!("<< /S /GoTo /D [3 0 R /Fit] /Next {js} >>"))], ""),
+ // `/Next` refers to an array that holds the action directly.
+ build(&["<< /Type /Catalog /Pages 2 0 R >>", pages, page, &link("<< /S /GoTo /D [3 0 R /Fit] /Next 5 0 R >>"), &format!("[{js}]")], ""),
+ ];
+ for (i, mut doc) in cases.into_iter().enumerate() {
+ let found = messages(&verify(&doc, Level::A2b)).contains(&"A JavaScript action isn't allowed");
+ assert!(found, "case {i}: {:#?}", verify(&doc, Level::A2b));
+ let r = convert(&mut doc, Level::A2b).unwrap();
+ assert!(!r.remaining.iter().any(|x| x.clause == "6.5.1"), "case {i}: {:#?}", r.remaining);
+ let plain = pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() };
+ let bytes = pdfcraft_cos::write_full(&doc, &plain).unwrap();
+ assert!(!bytes.windows(11).any(|w| w == b"/JavaScript"), "case {i}: {}", String::from_utf8_lossy(&bytes));
+ }
+}
+
+/// Each annotation's page is found from one pass over the pages' `/Annots`, not by searching
+/// every page's list again for each annotation.
+#[test]
+fn annotation_pages_are_found_in_one_pass() {
+ let n = 2_000;
+ let annots: Vec<String> = (0..n).map(|i| format!("{} 0 R", i + 4)).collect();
+ let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", annots.join(" "));
+ let mut objs =
+ vec!["<< /Type /Catalog /Pages 2 0 R >>".to_string(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>".into(), page];
+ objs.extend((0..n).map(|_| "<< /Type /Annot /Subtype /Link /Rect [0 0 0 0] /P 3 0 R >>".to_string()));
+ let refs: Vec<&str> = objs.iter().map(String::as_str).collect();
+ let doc = build(&refs, "");
+ ANNOT_ENTRIES_READ.with(|c| c.set(0));
+ let issues = verify(&doc, Level::A2b);
+ assert!(issues.iter().any(|i| i.clause == "6.3.2" && i.page == Some(0)), "{issues:#?}");
+ let read = ANNOT_ENTRIES_READ.with(std::cell::Cell::get);
+ assert!(read <= 2 * n, "{read} entries read for {n} annotations");
+}
++
+ #[test]
+ fn an_output_intent_profile_header_is_read_within_a_size_cap() {
+ let intent = "/OutputIntents [<< /S /GTS_PDFA1 /DestOutputProfile 2 0 R >>]";
+ for (size, n) in [(128, Some(4)), (MAX_ICC_PROFILE + 1, None)] {
+ let mut doc = build(&[&format!("<< /Type /Catalog {intent} >>"), "null"], "");
+ let mut profile = vec![0; size];
+ profile[16..20].copy_from_slice(b"CMYK");
+ doc.set(pdfcraft_cos::ObjRef::new(2, 0), Object::Stream(pdfcraft_cos::Stream::flate(Dict::new(), &profile)));
+ assert_eq!(pdfa_intent_profile(&doc), Some(n), "a {size}-byte profile");
+ }
+ }