From df73ed78f0828091a57e46474579ac7a7c8455c6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:14:35 +0000 Subject: [PATCH 1/5] fix(affinity): charge shared text traversal and retained text against a document budget --- crates/affinity/src/model.rs | 11 +++++++++++ crates/affinity/src/tests.rs | 20 ++++++++++++++++++++ crates/affinity/src/text.rs | 17 ++++++++++++++++- 3 files changed, 47 insertions(+), 1 deletion(-) 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 a8a1187da5..57a9a9b010 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -496,6 +496,26 @@ 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 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..d38f9ed1dd 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -19,8 +19,19 @@ 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; + } let chars = block_chars(s, glyphs, total, &mut placeholders); total = total.checked_add(chars.len())?; if total > MAX_CHARS { @@ -37,6 +48,10 @@ 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)); } } From 7336d201de7c342aee1870ed5680bfa668e0ecf1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 01:42:12 +0000 Subject: [PATCH 2/5] address review: charge paragraph-run and Glys scans, read alignment before runs --- crates/affinity/src/text.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index d38f9ed1dd..0b60903431 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -32,6 +32,25 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { r.warn("text beyond the document text budget (truncated)"); break; } + // The paragraph alignment is read before the runs, so a budget cut inside this block keeps it. + // Scanning the paragraph runs (null slots included) is charged before it is done. + 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)) { + 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` walks each segment's `Glys` slots, nulls included: charge them first. + if s.str(glyphs, b"Utf8").is_none() { + let slots = s.objs(glyphs, b"Mixd").iter().fold(0usize, |n, seg| n.saturating_add(s.array_len(*seg, b"Glys").unwrap_or(0))); + 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 { @@ -55,9 +74,6 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { 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)"); From c0d546983ded9a6e95ce72e57b5de6393200563e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 04:17:04 +0000 Subject: [PATCH 3/5] address review: apply block alignment after the character limit; charge Utf8 scan --- crates/affinity/src/text.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index 0b60903431..d832f2ba19 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -32,24 +32,27 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { r.warn("text beyond the document text budget (truncated)"); break; } - // The paragraph alignment is read before the runs, so a budget cut inside this block keeps it. + // 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)) { - align = s.objs(p, b"Runs").first().copied().and_then(|run| s.obj(run, b"Item")).map(|p| paragraph_align(r, p)); + 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` walks each segment's `Glys` slots, nulls included: charge them first. - if s.str(glyphs, b"Utf8").is_none() { - let slots = s.objs(glyphs, b"Mixd").iter().fold(0usize, |n, seg| n.saturating_add(s.array_len(*seg, b"Glys").unwrap_or(0))); - if !r.charge_text(slots) { - r.warn("text beyond the document text budget (truncated)"); - break; - } + // `block_chars` scans the `Utf8` string, or walks each segment's `Glys` slots (nulls included): charge the scan first. + let slots = match s.str(glyphs, b"Utf8") { + Some(text) => text.len(), + None => s.objs(glyphs, b"Mixd").iter().fold(0usize, |n, seg| n.saturating_add(s.array_len(*seg, b"Glys").unwrap_or(0))), + }; + 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())?; @@ -57,6 +60,9 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { 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()); From 34651cb4db82ac36ae6310663c263d86f269a584 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 22:48:45 +0000 Subject: [PATCH 4/5] address review: charge Mixd segment text before the block scan --- crates/affinity/src/text.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index d832f2ba19..1f203f0a0d 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -45,10 +45,13 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { 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): charge the scan first. + // `block_chars` scans the `Utf8` string, or walks each segment's `Glys` slots (nulls included) and `Utf8` text: charge the scan first. let slots = match s.str(glyphs, b"Utf8") { Some(text) => text.len(), - None => s.objs(glyphs, b"Mixd").iter().fold(0usize, |n, seg| n.saturating_add(s.array_len(*seg, b"Glys").unwrap_or(0))), + None => s + .objs(glyphs, b"Mixd") + .iter() + .fold(0usize, |n, seg| n.saturating_add(s.array_len(*seg, b"Glys").unwrap_or(0)).saturating_add(s.str(*seg, b"Utf8").map_or(0, str::len))), }; if !r.charge_text(slots) { r.warn("text beyond the document text budget (truncated)"); From 9e4e135971182ef332e53ba9da95f98686bd05f4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 02:35:27 +0000 Subject: [PATCH 5/5] address review: charge only the text block_chars scans against the text budget --- crates/affinity/src/tests.rs | 35 ++++++++++++++++++++++++++++ crates/affinity/src/text.rs | 45 ++++++++++++++++++++++++++++-------- 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index 57a9a9b010..2bba4a7a95 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -516,6 +516,41 @@ mod shapes { 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 1f203f0a0d..7403d99f6e 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -45,14 +45,8 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { 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: charge the scan first. - let slots = match s.str(glyphs, b"Utf8") { - Some(text) => text.len(), - None => s - .objs(glyphs, b"Mixd") - .iter() - .fold(0usize, |n, seg| n.saturating_add(s.array_len(*seg, b"Glys").unwrap_or(0)).saturating_add(s.str(*seg, b"Utf8").map_or(0, str::len))), - }; + // `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; @@ -105,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 => {