diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs index 3d74333111..529f118b24 100644 --- a/crates/affinity/src/model.rs +++ b/crates/affinity/src/model.rs @@ -294,6 +294,9 @@ const MAX_NAME_BYTES: usize = 64 << 20; const MAX_PAGES: usize = 1 << 18; /// Bytes of font names the text runs may retain across the document. const MAX_FONT_NAME_BYTES: usize = 16 << 20; +/// Text work units (block and run slots traversed, bytes of story text retained) across all +/// text nodes of a document; real documents use a tiny fraction. +const MAX_TEXT_WORK: usize = 64 << 20; /// Read a document: archive, `doc.dat` and the model. pub fn read(bytes: &[u8], limits: Limits) -> Result { @@ -316,6 +319,7 @@ pub(crate) struct Reader<'s, 'a, 'b> { name_bytes: usize, pages: usize, font_name_bytes: usize, + text_work: usize, active: HashSet, pub(crate) geometry_budget: crate::geometry::Budget, /// Decoded pixels still available ([`Limits::max_pixel_bytes`] less what the layers read so @@ -335,6 +339,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { name_bytes: 0, pages: 0, font_name_bytes: 0, + text_work: 0, active: HashSet::new(), geometry_budget: crate::geometry::Budget::default(), pixels_left: limits.max_pixel_bytes, @@ -652,6 +657,12 @@ impl Reader<'_, '_, '_> { self.font_name_bytes <= MAX_FONT_NAME_BYTES } + /// Counts text traversal work and retained text bytes against [`MAX_TEXT_WORK`]; false once it is spent. + pub(crate) fn charge_text(&mut self, n: usize) -> bool { + self.text_work = self.text_work.saturating_add(n); + self.text_work <= MAX_TEXT_WORK + } + /// Counts retained page rectangles against [`MAX_PAGES`]. fn charge_pages(&mut self, n: usize) -> Result<(), Error> { self.pages = self.pages.saturating_add(n); diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index 1afb5d29f8..61162454ba 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -496,6 +496,61 @@ mod shapes { assert!(t.frame.is_none()); } + #[test] + fn a_shared_story_placed_many_times_is_charged_against_the_text_budget() { + // One ~1 MiB story referenced 100 times would retain ~100 MiB of text without a budget. + let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("a".repeat((1 << 20) - 1)))]); + let run = F::Obj(tag(b"Item"), vec![]); + let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(1 << 20)), (tag(b"Item"), run)]]))]); + let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)]; + let text = F::Def( + 100, + vec![tag(b"TxtA")], + vec![ + (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])), + (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])), + ], + ); + let group = F::Def(101, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared((0..100).map(|_| F::Ref(100)).collect()))]); + let d = read(vec![text, group], 101); + assert!(d.warnings.iter().any(|w| w.contains("document text budget")), "{:?}", d.warnings); + } + + #[test] + fn text_past_the_character_limit_is_not_charged_so_a_later_text_node_survives() { + // 64 references to one segment of 1 MiB + 1 characters: only the first is scanned (the + // block is cut at the character limit), so only that scan is charged to the text budget. + let frame = || (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])); + let segment = F::Def(200, vec![tag(b"Segm")], vec![(tag(b"Utf8"), F::Str("a".repeat((1 << 20) + 1)))]); + let mut refs = vec![segment]; + refs.extend((0..63).map(|_| F::Ref(200))); + let big_block = vec![(tag(b"Glyp"), F::Obj(tag(b"Glyp"), vec![(tag(b"Mixd"), F::Shared(refs))]))]; + let big = + F::Def(100, vec![tag(b"TxtA")], vec![frame(), (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![big_block]))]))]); + let run = F::Obj(tag(b"Item"), vec![]); + let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]); + let small_block = vec![(tag(b"Glyp"), F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("ok".into()))])), (tag(b"GAtt"), attributes)]; + let small = F::Def( + 101, + vec![tag(b"TxtA")], + vec![frame(), (tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![small_block]))]))], + ); + let group = F::Def(102, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared(vec![F::Ref(100), F::Ref(101)]))]); + let d = read(vec![big, small, group], 102); + assert!(!d.warnings.iter().any(|w| w.contains("document text budget")), "{:?}", d.warnings); + fn collect(nodes: &[crate::model::Node], out: &mut Vec) { + for n in nodes { + if let Kind::Text(t) = &n.kind { + out.push(t.runs.iter().map(|r| r.text.as_str()).collect()); + } + collect(&n.children, out); + } + } + let mut texts = Vec::new(); + collect(&d.spreads[0].nodes, &mut texts); + assert!(texts.iter().any(|t| t == "ok"), "{texts:?}"); + } + #[test] fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() { let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100); diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index 96c11b4805..7403d99f6e 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -19,14 +19,47 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { let mut align = None; let mut total = 0usize; let mut placeholders = false; - for block in s.objs(story, b"Blok") { + // Shared structures are traversed once per occurrence: charge the raw slots (nulls and empty + // blocks included) before collecting them, against a document-wide budget. + if !r.charge_text(s.array_len(story, b"Blok").unwrap_or(0)) { + r.warn("text beyond the document text budget (left out)"); + return None; + } + 'blocks: for block in s.objs(story, b"Blok") { let glyphs = s.obj(block, b"Glyp")?; + let runs_n = s.obj(block, b"GAtt").and_then(|g| s.array_len(g, b"Runs")).unwrap_or(0); + if !r.charge_text(1 + runs_n + s.array_len(glyphs, b"Mixd").unwrap_or(0)) { + r.warn("text beyond the document text budget (truncated)"); + break; + } + // Applied to `align` only once this block passes the character limit below, so a discarded + // block does not set the alignment of the text kept from earlier blocks. + // Scanning the paragraph runs (null slots included) is charged before it is done. + let mut block_align = None; + if align.is_none() + && let Some(p) = s.obj(block, b"PAtt") + { + if r.charge_text(s.array_len(p, b"Runs").unwrap_or(0)) { + block_align = s.objs(p, b"Runs").first().copied().and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p)); + } else { + r.warn("text beyond the document text budget (paragraph alignment left out)"); + } + } + // `block_chars` scans the `Utf8` string, or walks each segment's `Glys` slots (nulls included) and `Utf8` text, and stops at the character limit: charge only that scan, first. + let slots = scan_cost(s, glyphs, room(total)); + if !r.charge_text(slots) { + r.warn("text beyond the document text budget (truncated)"); + break; + } let chars = block_chars(s, glyphs, total, &mut placeholders); total = total.checked_add(chars.len())?; if total > MAX_CHARS { r.warn("text longer than a million characters (truncated)"); break; } + if align.is_none() { + align = block_align; + } let mut start = 0usize; for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() { let end = usize::try_from(s.int(run, b"Indx")?).ok()?.min(chars.len()); @@ -37,12 +70,13 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { start = end; let Some(attrs) = s.obj(run, b"Item") else { continue }; if !text.is_empty() { + if !r.charge_text(text.len()) { + r.warn("text beyond the document text budget (truncated)"); + break 'blocks; + } runs.push(run_attrs(r, attrs, text, world)); } } - if align.is_none() { - align = s.obj(block, b"PAtt").and_then(|p| s.objs(p, b"Runs").first().copied()).and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p)); - } } if placeholders { r.warn("text fields such as page numbers (left out of the text)"); @@ -65,12 +99,43 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world }) } +/// One past the allowance is enough to trip the check in `read`; `block_chars` stops there. +fn room(total: usize) -> usize { + MAX_CHARS.saturating_sub(total).saturating_add(1) +} + +/// The bytes of `t` that holding `want` characters of it scans, and the characters taken. +fn prefix(t: &str, want: usize) -> (usize, usize) { + t.char_indices().enumerate().find(|(n, _)| *n == want).map_or((t.len(), t.chars().count()), |(n, (i, _))| (i, n)) +} + +/// What `block_chars` scans for a block, in the units `charge_text` takes: the `Utf8` bytes it +/// reads, or per segment its `Glys` slots (nulls included) and the `Utf8` bytes it reads, up to the +/// character allowance `room`; text past it is never scanned, so it is not charged. +fn scan_cost(s: &Stream, glyphs: ObjId, room: usize) -> usize { + if let Some(t) = s.str(glyphs, b"Utf8") { + return prefix(t, room).0; + } + let (mut len, mut cost) = (0usize, 0usize); + for seg in s.objs(glyphs, b"Mixd") { + if len >= room { + break; + } + let inline = s.objs(seg, b"Glys").len(); + len += inline.min(room - len); + cost = cost.saturating_add(s.array_len(seg, b"Glys").unwrap_or(0)); + let (bytes, chars) = prefix(s.str(seg, b"Utf8").unwrap_or_default(), room.saturating_sub(len)); + len += chars; + cost = cost.saturating_add(bytes); + } + cost +} + /// The characters of one text block. A block without a UTF-8 string is a list of segments: each /// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once /// `total` plus these characters would pass the cap. fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec { - // One past the allowance is enough to trip the check in `read`; both arms stop there. - let room = MAX_CHARS.saturating_sub(total).saturating_add(1); + let room = room(total); match s.str(glyphs, b"Utf8") { Some(t) => t.chars().take(room).collect(), None => {