From b3e5296d072e2247da6fd5435483a7cad1c614c4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:17:57 +0000 Subject: [PATCH] PDF functions and mesh shadings: charge retained values, refuse short tables, bound lattice rows and raster work Depth-limit fallbacks were not charged to the function node budget; cached copies of a function deep-copied its coefficient and program vectors while only its nodes were charged; sampled functions made up missing samples as zeros; calculator programs had no size limit; a lattice row was filled before any limit applied; and overlapping mesh triangles each scanned their whole bounding box. The node is charged before the depth check; coefficients, bounds, encode arrays and calculator operators are charged (eight to a node) so cached copies carry their cost; a sampled function shorter than its table is unsupported; calculator programs hold at most 4,096 operators; lattice rows past the triangle limit are refused and vertices stop at it; and triangle bounding boxes share a budget of 64 passes over the raster. --- crates/pdf/src/color.rs | 50 +++++++++++++++++++++++++-------- crates/pdf/src/shading.rs | 13 ++++++++- crates/pdf/src/tests.rs | 29 +++++++++++++++++++ crates/pdf/src/tests/shading.rs | 29 +++++++++++++++++++ 4 files changed, 108 insertions(+), 13 deletions(-) diff --git a/crates/pdf/src/color.rs b/crates/pdf/src/color.rs index 6943476bc..275f81363 100644 --- a/crates/pdf/src/color.rs +++ b/crates/pdf/src/color.rs @@ -243,6 +243,15 @@ fn ps_push(st: &mut Vec, v: f64) { } } +/// The most operators and operands a calculator program may hold (nested procedures included). +/// It has no loops, so this bounds what one evaluation runs; real programs hold a few dozen. +const MAX_CALC_OPS: usize = 4096; + +/// The operators and operands in `code`, nested procedures included. +fn ps_len(code: &[PsOp]) -> usize { + code.iter().map(|op| if let PsOp::Proc(p) = op { 1 + ps_len(p) } else { 1 }).sum() +} + fn ps_run(code: &[PsOp], st: &mut Vec, depth: usize) { if depth > 32 { return; @@ -431,6 +440,12 @@ impl Budget { Budget { nodes: MAX_NODES, samples: MAX_SAMPLES, overrun: false } } + /// Charge `n` retained values (coefficients, bounds, program operators) as nodes, eight to a + /// node, so a cached copy of a function is charged for what it holds, not just its node. + fn take_values(&mut self, n: usize) -> bool { + self.take_nodes(n.div_ceil(8)) + } + /// Charge `n` nodes; `false` (and the read is abandoned) once the cap is passed. fn take_nodes(&mut self, n: usize) -> bool { match self.nodes.checked_sub(n) { @@ -484,7 +499,8 @@ impl Func { /// [`Func::read`] nested `depth` levels deep, charging `budget`: unsupported past [`MAX_DEPTH`] /// or once the budget is spent. fn read_at(file: &File, o: &Obj, depth: usize, budget: &mut Budget) -> Func { - if depth >= MAX_DEPTH || !budget.take_nodes(1) { + // Charged first: the fallback past the depth limit is a node a copy keeps too. + if !budget.take_nodes(1) || depth >= MAX_DEPTH { return Func::Unsupported; } let o = file.resolve(o); @@ -499,12 +515,14 @@ impl Func { let dom = file.get(d, "Domain").map(|x| file.nums(x)).unwrap_or_default(); let domain = [dom.first().copied().unwrap_or(0.0), dom.get(1).copied().unwrap_or(1.0)]; match file.get_num(d, "FunctionType").unwrap_or(-1.0) as i32 { - 2 => Func::Exp { - domain, - c0: file.get(d, "C0").map(|x| file.nums(x)).unwrap_or_else(|| vec![0.0]), - c1: file.get(d, "C1").map(|x| file.nums(x)).unwrap_or_else(|| vec![1.0]), - n: file.get_num(d, "N").unwrap_or(1.0), - }, + 2 => { + let c0 = file.get(d, "C0").map(|x| file.nums(x)).unwrap_or_else(|| vec![0.0]); + let c1 = file.get(d, "C1").map(|x| file.nums(x)).unwrap_or_else(|| vec![1.0]); + if !budget.take_values(c0.len() + c1.len()) { + return Func::Unsupported; + } + Func::Exp { domain, c0, c1, n: file.get_num(d, "N").unwrap_or(1.0) } + } 3 => { // A stitching function's pieces: no element cap (a repeating gradient lists one // piece once per repeat); the budget bounds the total work. @@ -513,12 +531,12 @@ impl Func { None => Some(vec![]), }; let Some(funcs) = funcs else { return Func::Unsupported }; - Func::Stitch { - domain, - funcs, - bounds: file.get(d, "Bounds").map(|x| file.nums(x)).unwrap_or_default(), - encode: file.get(d, "Encode").map(|x| file.nums(x)).unwrap_or_default(), + let bounds = file.get(d, "Bounds").map(|x| file.nums(x)).unwrap_or_default(); + let encode = file.get(d, "Encode").map(|x| file.nums(x)).unwrap_or_default(); + if !budget.take_values(bounds.len() + encode.len()) { + return Func::Unsupported; } + Func::Stitch { domain, funcs, bounds, encode } } 0 => { let Obj::Stream(sd, raw) = o else { return Func::Unsupported }; @@ -537,6 +555,10 @@ impl Func { if !budget.take_samples(count) { return Func::Unsupported; } + // The stream must hold the table: missing bytes are not made up as zeros. + if count.checked_mul(bps).is_none_or(|bits| bits.div_ceil(8) > data.len()) { + return Func::Unsupported; + } let enc = file.get(d, "Encode").map(|x| file.nums(x)).unwrap_or_default(); let encode = [enc.first().copied().unwrap_or(0.0), enc.get(1).copied().unwrap_or(size as f64 - 1.0)]; let decode = file.get(d, "Decode").map(|x| file.nums(x)).filter(|v| v.len() >= outputs * 2).unwrap_or_else(|| range.clone()); @@ -571,6 +593,10 @@ impl Func { Some(PsOp::Proc(p)) => p, _ => return Func::Unsupported, }; + let ops = ps_len(&code); + if ops > MAX_CALC_OPS || !budget.take_values(ops) { + return Func::Unsupported; + } Func::Calc { domain: dom, range: file.get(d, "Range").map(|x| file.nums(x)).unwrap_or_default(), code } } _ => Func::Unsupported, diff --git a/crates/pdf/src/shading.rs b/crates/pdf/src/shading.rs index df5e5f9c7..aa83adebf 100644 --- a/crates/pdf/src/shading.rs +++ b/crates/pdf/src/shading.rs @@ -18,6 +18,8 @@ const MAX_SIDE: f64 = 1024.0; const MAX_SCALE: f64 = 4.0; /// The most triangles one shading draws. const MAX_TRIANGLES: usize = 2_000_000; +/// How many times over the mesh raster may be covered by triangle bounding boxes in all. +const MAX_RASTER_PASSES: usize = 64; /// A mesh vertex: page-space position and its value (RGB, or `t` in `[0]` with a function). #[derive(Clone, Copy, Debug, PartialEq)] @@ -234,13 +236,17 @@ fn free_form(r: &mut Bits, l: &Layout, colors: &Colors, m: Affine) -> Vec<[V; 3] /// Type 5: a lattice of `per_row` vertices per row, two triangles per cell. fn lattice(r: &mut Bits, l: &Layout, colors: &Colors, m: Affine, per_row: usize) -> Vec<[V; 3]> { - if per_row < 2 { + if !(2..=MAX_TRIANGLES).contains(&per_row) { return vec![]; } let mut rows: Vec> = vec![]; let mut row = vec![]; while let (Some(p), Some(c)) = (l.point(r), l.comps(r)) { r.align(); + // Vertices kept, the unfinished row's included, stay within the triangle limit. + if (rows.len() * per_row).saturating_add(row.len()) >= MAX_TRIANGLES { + break; + } row.push(V { p: m * p, c: colors.value(&c) }); if row.len() == per_row { rows.push(std::mem::take(&mut row)); @@ -447,6 +453,9 @@ fn rasterize(tris: &[[V; 3]], colors: &Colors, page_box: [f64; 4]) -> Option Option>", "2 0 R ".repeat(1000)), None), + (2, format!("<< /FunctionType 2 /Domain [0 1] /C0 {c} /C1 {c} /N 1 >>"), None), + ]; + assert_eq!(read_function(objs), color::Func::Unsupported); +} + #[test] fn colour_space_chain_of_depth_3() { // Indexed → Separation → ICCBased → DeviceRGB: entry 0 is tint 1 (blue), entry 1 tint 0 (white). diff --git a/crates/pdf/src/tests/shading.rs b/crates/pdf/src/tests/shading.rs index 8e96193ab..4b5f9645d 100644 --- a/crates/pdf/src/tests/shading.rs +++ b/crates/pdf/src/tests/shading.rs @@ -262,3 +262,32 @@ fn corrupt_mesh_data_draws_what_parses() { let doc = parse(&bytes).unwrap(); assert!(doc.skipped.iter().any(|s| s.contains("layout")), "{:?}", doc.skipped); } + +#[test] +fn overlapping_mesh_triangles_stop_at_the_raster_budget() { + // 20,000 triangles each covering the whole page would test every sample 20,000 times; the + // raster budget stops after about 64 passes, and the shading is still drawn. + let mut m = Mesh::default(); + for _ in 0..20_000 { + m.flag(0).pt(0, 0).c(&[255, 0, 0]); + m.flag(0).pt(400, 0).c(&[255, 0, 0]); + m.flag(0).pt(0, 400).c(&[255, 0, 0]); + } + let sh = format!("<< /ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 16 /BitsPerComponent 8 /BitsPerFlag 8 {RGB_DECODE} >>"); + let bytes = page_pdf("/Sh sh", "/Shading << /Sh 10 0 R >>", vec![(10, sh, Some(m.0))]); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(parse(&bytes)).ok()); + let doc = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the mesh finishes").unwrap(); + assert!(render(&doc).get(50, 50)[0] > 0.99); +} + +#[test] +fn a_lattice_row_longer_than_the_triangle_limit_draws_nothing() { + let mut m = Mesh::default(); + for i in 0..8 { + m.pt(i * 10, 0).c(&[255, 0, 0]); + } + let sh = format!("<< /ShadingType 5 /ColorSpace /DeviceRGB /BitsPerCoordinate 16 /BitsPerComponent 8 /VerticesPerRow 3000000 {RGB_DECODE} >>"); + let doc = parse(&page_pdf("/Sh sh", "/Shading << /Sh 10 0 R >>", vec![(10, sh, Some(m.0))])).unwrap(); + assert!(doc.flatten().is_empty()); +}