Merge #6501: fix(render): an image whose PNG predictor was declared but never applied draws its samples (hayro-syntax patch 40)

# Conflicts:
#	parity/acrobat-features.toml
#	vendor/README.md
This commit is contained in:
bflatastic committed 2026-11-09 08:05:23 +07:00
commit 5c42721193
12 files changed
+491 -44

No files matched your search

+32
View File
@@ -753,6 +753,38 @@ mod image_tests {
assert_eq!(budget.work_left(), u64::MAX);
}
/// PDFBOX-3932: an image and soft mask declared `/Predictor 15` that their writer never
/// applied, so their rows carry no PNG filter-type byte. Exported, they were "shorter than
/// their size says"; they are read as the samples they are, and tagged rows as before.
#[test]
fn an_image_whose_rows_carry_no_png_tags_decodes_to_its_samples() {
let doc = Document::new_empty();
let samples: Vec<u8> = (0..36u8).map(|i| 200 - i).collect();
let image = |height: Option<i64>, raw: Vec<u8>| {
let mut parms = Dict::new();
parms.set(b"Predictor".to_vec(), Object::Int(15));
parms.set(b"Colors".to_vec(), Object::Int(3));
parms.set(b"Columns".to_vec(), Object::Int(3));
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(3));
if let Some(h) = height {
dict.set(b"Height".to_vec(), Object::Int(h));
}
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
Stream::from_raw(dict, raw)
};
let untagged = pdfcraft_filters::encode_flate(&samples);
let mut budget = ImageBudget::with_work(u64::MAX);
assert_eq!(budget.decode(&doc, &image(Some(4), untagged.clone()), 1 << 20).unwrap(), samples);
// Without a height to tell, the predictor is undone, as before.
assert_ne!(budget.decode(&doc, &image(None, untagged.clone()), 1 << 20).ok(), Some(samples.clone()));
assert_ne!(budget.decode(&doc, &image(Some(5), untagged), 1 << 20).ok(), Some(samples.clone()));
let p = pdfcraft_filters::Params { predictor: 15, colors: 3, columns: 3, ..pdfcraft_filters::Params::default() };
let tagged = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, &p, &samples).unwrap();
assert_eq!(budget.decode(&doc, &image(Some(4), tagged), 1 << 20).unwrap(), samples);
}
/// The images of a file share its globals, so an image refused doesn't read them: this one's
/// can't be read, which is how to tell.
#[test]
+8 -1
View File
@@ -479,7 +479,14 @@ impl Document {
let data = if *work == 0 { Cow::Borrowed(&[][..]) } else { undo(before, work)? };
return pdfcraft_filters::decode_jbig2_within(&data, globals.as_deref().map(Vec::as_slice), columns, height, max, work).map_err(filter);
}
let Some(p) = self.fax_params(s) else { return s.decoded_spending(max, work) };
let Some(p) = self.fax_params(s) else {
// The last filter gives the image's rows: rows without the tags of the PNG predictor
// they declare are read as they are (`pdfcraft_filters::decode_image_tolerant_within`).
return match height {
Some(rows) => s.decoded_image_rows_spending(max, rows, work),
None => s.decoded_spending(max, work),
};
};
// As many rows as the image has: a /Rows below /Height would cut the picture short, and
// rows past /Height aren't drawn.
let p = pdfcraft_filters::CcittParams { rows: 0, ..p };
+8
View File
@@ -390,6 +390,14 @@ impl Stream {
pdfcraft_filters::decode_tolerant_within(&chain, &self.raw, max.min(MAX_DECODED), work).map_err(filter)
}
/// [`Stream::decoded_spending`] for the samples of an image `rows` high (its `/Height`):
/// [`pdfcraft_filters::decode_image_tolerant_within`].
pub(crate) fn decoded_image_rows_spending(&self, max: usize, rows: u32, work: &mut u64) -> Result<Vec<u8>, CosError> {
let filter = |e: pdfcraft_filters::FilterError| CosError::Filter(e.to_string());
let chain = self.readable_filters().map_err(filter)?;
pdfcraft_filters::decode_image_tolerant_within(&chain, &self.raw, max.min(MAX_DECODED), rows, work).map_err(filter)
}
/// The stream decoded through its filters by `decode`, or copied when it has none, within
/// `max` and [`MAX_DECODED`].
fn decode_chain(
+148 -20
View File
@@ -189,7 +189,7 @@ pub(crate) fn pay(work: &mut u64, steps: u64) -> Result<(), FilterError> {
/// [`FilterError::Unsupported`] (callers keep such data encoded), as does a chain longer than
/// [`MAX_CHAIN`]. `max_output` bounds every intermediate buffer.
pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<Vec<u8>, FilterError> {
run(chain, data, max_output, None, true, false).map(|(v, _, _)| v).map_err(|(e, _)| e)
run(chain, data, max_output, None, true, false, None).map(|(v, _, _)| v).map_err(|(e, _)| e)
}
/// Like [`decode`] for a caller charging an allowance: `max_output` bounds the bytes all stages
@@ -197,19 +197,19 @@ pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Res
/// bytes, on success and on failure. A stage's output counts even when a later stage or its
/// predictor shrinks it.
pub fn decode_counted(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, usize), (FilterError, usize)> {
run(chain, data, max_output, Some(max_output), true, false).map(|(v, _, spent)| (v, spent))
run(chain, data, max_output, Some(max_output), true, false, None).map(|(v, _, spent)| (v, spent))
}
/// Like [`decode`], but on corrupt data returns what was decoded before the error and
/// reports `partial = true` (the behaviour viewers expect). The remaining filters of the
/// chain still run on the partial data. Limit and unsupported errors are still errors.
pub fn decode_tolerant(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool), FilterError> {
run(chain, data, max_output, None, false, false).map(|(v, partial, _)| (v, partial)).map_err(|(e, _)| e)
run(chain, data, max_output, None, false, false, None).map(|(v, partial, _)| (v, partial)).map_err(|(e, _)| e)
}
/// [`decode_tolerant`] bounded and counted as [`decode_counted`] is.
pub fn decode_tolerant_counted(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)> {
run(chain, data, max_output, Some(max_output), false, false)
run(chain, data, max_output, Some(max_output), false, false, None)
}
/// [`decode_tolerant`], spending from `work`, what decoding may still cost across a run of images:
@@ -222,23 +222,46 @@ pub fn decode_tolerant_counted(chain: &[(Filter, Params)], data: &[u8], max_outp
///
/// Unlike [`decode_tolerant`], no filters at all gives `data` itself, within `max_output`.
pub fn decode_tolerant_within(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &mut u64) -> Result<Vec<u8>, FilterError> {
spending(chain, data, max_output, work, false)
spending(chain, data, max_output, work, false, None)
}
/// [`decode_tolerant_within`] for the samples of an image `rows` high (its `/Height`), which the
/// last stage gives. When that stage is Flate with a PNG predictor and gives exactly `rows` rows
/// without the filter-type byte each predicted row starts with (ISO 32000-2 §7.4.4.4), its writer
/// declared the predictor without applying it: the output is taken as the samples, as other
/// readers take it, and reported as the damage it is, like any other corruption tolerated here.
/// Any other output has its predictor undone as [`decode_tolerant_within`] does.
pub fn decode_image_tolerant_within(
chain: &[(Filter, Params)],
data: &[u8],
max_output: usize,
rows: u32,
work: &mut u64,
) -> Result<Vec<u8>, FilterError> {
spending(chain, data, max_output, work, false, usize::try_from(rows).ok())
}
/// [`decode`], spending from `work` as [`decode_tolerant_within`] does: corrupt data is an error,
/// having paid for what was decoded before it.
pub fn decode_within(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &mut u64) -> Result<Vec<u8>, FilterError> {
spending(chain, data, max_output, work, true)
spending(chain, data, max_output, work, true, None)
}
fn spending(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &mut u64, strict: bool) -> Result<Vec<u8>, FilterError> {
fn spending(
chain: &[(Filter, Params)],
data: &[u8],
max_output: usize,
work: &mut u64,
strict: bool,
rows: Option<usize>,
) -> Result<Vec<u8>, FilterError> {
decodable(chain)?;
pay(work, data.len() as u64)?;
if chain.is_empty() {
return if data.len() > max_output { Err(FilterError::LimitExceeded(max_output)) } else { Ok(data.to_vec()) };
}
let left = usize::try_from(*work).unwrap_or(usize::MAX);
match run(chain, data, max_output, Some(left), strict, true) {
match run(chain, data, max_output, Some(left), strict, true, rows) {
Ok((out, _, decoded)) => pay(work, decoded as u64).map(|()| out),
// The stage stopped at the lower of the two, which took as much to find out.
Err((FilterError::LimitExceeded(_), decoded)) if left.saturating_sub(decoded) > max_output => {
@@ -284,10 +307,11 @@ fn decodable(chain: &[(Filter, Params)]) -> Result<(), FilterError> {
}
/// The decoded data, whether it is partial and the bytes all stages decoded, or the error and
/// the bytes decoded before it. `max` bounds each stage, and `total` all of them together.
/// the bytes decoded before it. `max` bounds each stage, and `total` all of them together. With
/// `priced`, the count is steps: each Flate stage also pays [`FLATE_READ_WORK`] for each byte it
/// reads, before it runs, so a stage `total` can't pay for doesn't run
/// ([`FilterError::Spent`]).
/// ([`FilterError::Spent`]). `rows` is the height of the image whose samples the last stage
/// produces, if it does ([`decode_image_tolerant_within`]).
fn run(
chain: &[(Filter, Params)],
data: &[u8],
@@ -295,13 +319,14 @@ fn run(
total: Option<usize>,
strict: bool,
priced: bool,
rows: Option<usize>,
) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)> {
decodable(chain).map_err(|e| (e, 0))?;
let mut cur: Cow<[u8]> = Cow::Borrowed(data);
let mut partial = false;
let mut spent = 0usize;
let price = usize::try_from(FLATE_READ_WORK).unwrap_or(usize::MAX);
for (filter, params) in chain {
for (i, (filter, params)) in chain.iter().enumerate() {
let read = if priced && matches!(filter, Filter::Flate) { price.saturating_mul(cur.len()) } else { 0 };
let room = total.map_or(usize::MAX, |total| total.saturating_sub(spent));
if read > room {
@@ -313,8 +338,9 @@ fn run(
let limit = total.map_or(max, |total| max.min(total.saturating_sub(spent)));
// A second reading of the same bytes (Flate's raw retry) is paid for as the first was, and
// makes no more than is left once it has been.
let rows = rows.filter(|_| i + 1 == chain.len());
let again = room.checked_sub(read.saturating_mul(2)).map(|left| max.min(left));
let (step, work, again) = decode_one(filter, params, &cur, limit, again);
let (step, work, again) = decode_one(filter, params, &cur, limit, again, rows);
if again {
spent = spent.saturating_add(read);
}
@@ -333,16 +359,18 @@ fn run(
}
/// One stage's result, the bytes its decoder produced (before any predictor), and whether it
/// read its input twice, which it does only within `again` ([`flate::decode`]).
fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize, again: Option<usize>) -> (Step, usize, bool) {
/// read its input twice, which it does only within `again` ([`flate::decode`]); `rows` as for
/// [`run`].
fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize, again: Option<usize>, rows: Option<usize>) -> (Step, usize, bool) {
let once = |(step, n): (Step, usize)| (step, n, false);
match filter {
Filter::Flate => {
let (step, twice) = flate::decode(data, max, again);
let (step, n) = with_predictor(step, params, "FlateDecode");
let (step, n) = with_predictor(step, params, "FlateDecode", rows);
(step, n, twice)
}
Filter::Lzw => once(with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode")),
// LZW rows are predicted whatever their length, as the renderer reads them.
Filter::Lzw => once(with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode", None)),
Filter::AsciiHex => once(counted(asciihex::decode(data, max))),
Filter::Ascii85 => once(counted(ascii85::decode(data, max))),
Filter::RunLength => once(counted(runlength::decode(data, max))),
@@ -361,13 +389,14 @@ fn counted(step: Step) -> (Step, usize) {
/// Applies the predictor to a decoder's result, including to partial output on failure. The
/// count is the decoder's output: a PNG predictor drops a tag byte per row, but the decoder
/// produced it.
fn with_predictor(step: Step, params: &Params, name: &'static str) -> (Step, usize) {
/// produced it. `rows` (an image's height, for its last stage) applies only to data that decoded
/// whole: data cut short by damage has its predictor undone as it always had.
fn with_predictor(step: Step, params: &Params, name: &'static str, rows: Option<usize>) -> (Step, usize) {
let (step, n) = counted(step);
let step = match step {
Ok(v) => predictor::decode(params, v, name),
Ok(v) => predictor::decode(params, v, name, rows),
Err(Failure { error, partial, discarded }) => {
let partial = match predictor::decode(params, partial, name) {
let partial = match predictor::decode(params, partial, name, None) {
Ok(v) => v,
Err(f) => f.partial,
};
@@ -791,4 +820,103 @@ mod tests {
assert!(refused(&decode_tolerant_within(&[], b"data", 4, &mut work).unwrap_err()));
assert_eq!(work, 0);
}
/// Four rows of three RGB pixels, every sample above 4 (none reads as a PNG filter type).
fn rgb_rows() -> (Params, Vec<u8>) {
let p = Params { predictor: 15, colors: 3, columns: 3, ..Params::default() };
(p, (0..36u8).map(|i| 200 - i).collect())
}
#[test]
fn an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples_and_reported() {
let (p, samples) = rgb_rows();
let chain = [(Filter::Flate, p.clone())];
let data = encode_flate(&samples);
let mut work = u64::MAX;
assert_eq!(decode_image_tolerant_within(&chain, &data, 1 << 20, 4, &mut work).unwrap(), samples);
// The repair is reported as the damage it is: tolerant decoding says so, and strict refuses.
let (out, partial, _) = run(&chain, &data, 1 << 20, None, false, false, Some(4)).map_err(|(e, _)| e).unwrap();
assert_eq!((out, partial), (samples.clone(), true));
let strict = run(&chain, &data, 1 << 20, None, true, false, Some(4)).map(|_| ()).map_err(|(e, _)| e.to_string());
assert!(strict.as_ref().is_err_and(|e| e.contains("carry no filter-type bytes")), "{strict:?}");
// The same data that isn't known to be an image's rows still goes through the predictor.
let mut work = u64::MAX;
assert_ne!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap(), samples);
// LZW is read as before, as the renderer reads it.
let lzw = [(Filter::Lzw, p)];
let data = encode(&Filter::Lzw, &Params::default(), &samples).unwrap();
let mut plain = u64::MAX;
assert_eq!(
decode_image_tolerant_within(&lzw, &data, 1 << 20, 4, &mut work).ok(),
decode_tolerant_within(&lzw, &data, 1 << 20, &mut plain).ok()
);
}
#[test]
fn an_image_whose_rows_carry_png_tags_has_its_predictor_undone() {
let (p, samples) = rgb_rows();
let chain = [(Filter::Flate, p.clone())];
let data = encode(&Filter::Flate, &p, &samples).unwrap();
let (mut a, mut b) = (u64::MAX, u64::MAX);
assert_eq!(decode_image_tolerant_within(&chain, &data, 1 << 20, 4, &mut a).unwrap(), samples);
assert_eq!(decode_tolerant_within(&chain, &data, 1 << 20, &mut b).unwrap(), samples);
assert_eq!(a, b, "the same work");
let (_, partial, _) = run(&chain, &data, 1 << 20, None, false, false, Some(4)).map_err(|(e, _)| e).unwrap();
assert!(!partial);
}
#[test]
fn image_data_of_neither_length_decodes_as_it_did() {
let (p, _) = rgb_rows();
let chain = [(Filter::Flate, p.clone())];
for len in [0, 1, 9, 27, 35, 37, 39, 40, 41, 72] {
let data = encode_flate(&(0..len).map(|i| (i * 7 % 5) as u8).collect::<Vec<_>>());
let (mut a, mut b) = (u64::MAX, u64::MAX);
let image = decode_image_tolerant_within(&chain, &data, 1 << 20, 4, &mut a).map_err(|e| e.to_string());
let plain = decode_tolerant_within(&chain, &data, 1 << 20, &mut b).map_err(|e| e.to_string());
assert_eq!(image, plain, "{len} bytes");
}
// Rows of the untagged length for another height, or no height.
let samples = encode_flate(&[9; 36]);
for rows in [0, 3, 5, u32::MAX] {
let (mut a, mut b) = (u64::MAX, u64::MAX);
assert_eq!(
decode_image_tolerant_within(&chain, &samples, 1 << 20, rows, &mut a).ok(),
decode_tolerant_within(&chain, &samples, 1 << 20, &mut b).ok(),
"{rows} rows"
);
}
// Only the last stage produces the rows: an earlier one is predicted as before.
let hex: Vec<u8> = [9u8; 36].iter().flat_map(|b| format!("{b:02x}").into_bytes()).collect();
let earlier = [(Filter::Flate, p.clone()), (Filter::AsciiHex, Params::default())];
let data = encode_flate(&hex[..36]);
let (mut a, mut b) = (u64::MAX, u64::MAX);
assert_eq!(
decode_image_tolerant_within(&earlier, &data, 1 << 20, 4, &mut a).ok(),
decode_tolerant_within(&earlier, &data, 1 << 20, &mut b).ok()
);
// TIFF predictor 2 and no predictor are left alone.
for predictor in [1, 2] {
let chain = [(Filter::Flate, Params { predictor, ..p.clone() })];
let (mut a, mut b) = (u64::MAX, u64::MAX);
assert_eq!(
decode_image_tolerant_within(&chain, &samples, 1 << 20, 4, &mut a).ok(),
decode_tolerant_within(&chain, &samples, 1 << 20, &mut b).ok()
);
}
}
#[test]
fn image_rows_of_no_bytes_or_past_memory_do_not_panic() {
for (colors, bits_per_component, columns) in [(0, 8, 3), (3, 8, 0), (3, 8, -1), (255, 16, i64::MAX), (1, 1, i64::MAX), (3, 3, 3)] {
let chain = [(Filter::Flate, Params { predictor: 15, colors, bits_per_component, columns, early_change: 1 })];
for len in [0, 1, 36] {
let data = encode_flate(&vec![7; len]);
for rows in [0, 1, 4, u32::MAX] {
let mut work = u64::MAX;
let _ = decode_image_tolerant_within(&chain, &data, 1 << 20, rows, &mut work);
}
}
}
}
}
+29 -5
View File
@@ -6,6 +6,9 @@
//! byte (0 None, 1 Sub, 2 Up, 3 Average, 4 Paeth), whatever the predictor value is.
//!
//! A final partial row is decoded as far as its data goes.
//!
//! The samples of an image whose rows carry no filter-type byte, although a PNG predictor is
//! declared, are taken as they are and reported as damage ([`decode`]).
use crate::{Failure, FilterError, Params, Step};
@@ -37,18 +40,39 @@ fn layout(p: &Params) -> Result<Layout, String> {
Ok(Layout { bpc, colors, bpp: (colors * bpc).div_ceil(8), row: bits.div_ceil(8), samples })
}
/// Undoes the predictor named by `p.predictor` (1 = identity).
pub(crate) fn decode(p: &Params, data: Vec<u8>, name: &'static str) -> Step {
/// Undoes the predictor named by `p.predictor` (1 = identity). `rows` is the height of the image
/// `data` is the samples of, if it is: with a PNG predictor, data of exactly `rows` rows without
/// their filter-type bytes ([`untagged`]) is given back as it is, as a [`Failure`] whose partial
/// output is all of it, so that tolerant decoding takes the samples and reports the repair, and
/// strict decoding refuses them.
pub(crate) fn decode(p: &Params, data: Vec<u8>, name: &'static str, rows: Option<usize>) -> Step {
match p.predictor {
1 => Ok(data),
2 | 10..=15 => {
let l = layout(p).map_err(|e| Failure::corrupt(name, e, Vec::new()))?;
if p.predictor == 2 { Ok(tiff_decode(&l, data)) } else { png_decode(&l, &data, name) }
if p.predictor == 2 {
return Ok(tiff_decode(&l, data));
}
if let Some(rows) = rows.filter(|&rows| untagged(&l, data.len(), rows)) {
let detail =
format!("PNG predictor {} declared, but its {rows} rows carry no filter-type bytes: read as unpredicted samples", p.predictor);
return Err(Failure::corrupt(name, detail, data));
}
png_decode(&l, &data, name)
}
other => Err(Failure::corrupt(name, format!("invalid Predictor {other}"), Vec::new())),
}
}
/// Whether `len` bytes are exactly `rows` rows of `l` without the filter-type byte that starts each
/// PNG-predicted row (ISO 32000-2 §7.4.4.4), where predicted data would be `rows` × (row + 1): a
/// writer that declared the predictor and didn't apply it. Read with the predictor, every row's
/// first sample was taken for a filter type and the image came out a row short and shifted.
/// PDFium, MuPDF and Poppler read such data as the samples it is.
fn untagged(l: &Layout, len: usize, rows: usize) -> bool {
rows > 0 && l.row > 0 && rows.checked_mul(l.row) == Some(len)
}
/// Applies the predictor named by `p.predictor` (1 = identity; 15 = per-row optimum).
pub(crate) fn encode(p: &Params, data: &[u8]) -> Result<Vec<u8>, FilterError> {
match p.predictor {
@@ -213,7 +237,7 @@ mod tests {
}
fn dec(params: &Params, data: &[u8]) -> Result<Vec<u8>, FilterError> {
decode(params, data.to_vec(), "FlateDecode").map_err(|f| f.error)
decode(params, data.to_vec(), "FlateDecode", None).map_err(|f| f.error)
}
#[test]
@@ -262,7 +286,7 @@ mod tests {
#[test]
fn png_invalid_tag() {
let r = decode(&p(10, 1, 8, 2), vec![0, 1, 2, 5, 1, 1], "FlateDecode");
let r = decode(&p(10, 1, 8, 2), vec![0, 1, 2, 5, 1, 1], "FlateDecode", None);
let f = r.err().unwrap();
assert!(matches!(f.error, FilterError::Corrupt { .. }));
assert_eq!(f.partial, [1, 2]);
+2 -1
View File
@@ -9083,7 +9083,8 @@ mod default_colour_spaces;
// (vendored hayro-syntax patch 28, hayro-interpret patch 55).
mod devicen_inks;
// #5430: PNG-predicted Flate images are undone byte by byte (vendored hayro-syntax patch 35).
// #5430: PNG-predicted Flate images are undone byte by byte (vendored hayro-syntax patch 35), and
// PDFBOX-3932: rows that carry no filter-type byte are read as samples (patch 40).
mod png_predicted_images;
// TIFF-predicted Flate images at 8 and 16 bits are undone byte by byte (vendored hayro-syntax
@@ -1,7 +1,8 @@
//! #5430: Flate images with PNG predictors (ISO 32000-2 §7.4.4.4) are undone a byte row at a
//! time (vendored hayro-syntax patch 35). The bit-level decoder they went through before dropped
//! the last byte of each filtered row that ends part-way through a pixel, so every later row
//! started a byte early and the picture came out sheared.
//! started a byte early and the picture came out sheared. An image whose rows carry no filter-type
//! byte at all, although it declares a PNG predictor, is read as its samples (patch 40).
use super::rgb_at;
use crate::{PageRenderer, RenderConfig, RenderRequest, RequestKind};
@@ -67,3 +68,73 @@ fn a_four_bit_rgb_image_of_odd_width_with_up_predicted_rows_is_not_sheared() {
}
}
}
/// PDFBOX-3932: a writer declared `/Predictor 15` for an image and its soft mask without applying
/// it, so their rows carry no PNG filter-type byte (vendored hayro-syntax patch 40). Read with the
/// predictor, each row's first sample was taken for a filter type and the image came out a row
/// short and sheared; PDFium, MuPDF and Poppler draw the samples as they are.
#[test]
fn an_image_and_soft_mask_whose_rows_carry_no_png_tags_draw_their_samples() {
// Four rows of three 8-bit RGB pixels, every sample above 4 (no byte reads as a filter type
// that would happen to undo cleanly), and an opaque mask of three grey samples a row.
let rgb: Vec<u8> = ROWS.iter().flat_map(|px| (0..3).flat_map(move |_| px.map(|s| s * 16 + 8))).collect();
let mask = [255u8; 12];
let pdf = image_pdf(&[("/ColorSpace /DeviceRGB /SMask 6 0 R", "/Colors 3", &rgb), ("/ColorSpace /DeviceGray", "/Colors 1", &mask)]);
let page = render(pdf);
for (row, px) in ROWS.iter().enumerate() {
let expected = px.map(|s| s * 16 + 8);
for column in 0..3 {
let (x, y) = (column * 50 + 25, row * 50 + 25);
assert_eq!(rgb_at(&page.rgba, WIDTH, x, y), expected, "image row {row}, column {column}");
}
}
}
/// Data one byte short of rows without tags is neither layout: it is decoded with the predictor
/// as before, and does not panic.
#[test]
fn an_image_one_byte_short_of_untagged_rows_still_goes_through_the_predictor() {
let rgb = [0u8; 35];
let page = render(image_pdf(&[("/ColorSpace /DeviceRGB", "/Colors 3", &rgb)]));
assert_eq!((page.width, page.height), (WIDTH as u32, HEIGHT as u32));
}
/// Image objects 5, 6, … of a 3 × 4 8-bit image each, Flate-compressed with `/Predictor 15`
/// declared and their `data` stored as given; the page draws object 5 over all of itself.
fn image_pdf(images: &[(&str, &str, &[u8])]) -> Vec<u8> {
let content = "q 150 0 0 200 0 0 cm /Im0 Do Q";
let mut pdf = format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 150 200] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >> endobj\n\
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n",
content.len()
)
.into_bytes();
for (i, (keys, colors, data)) in images.iter().enumerate() {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(data).unwrap();
let data = encoder.finish().unwrap();
pdf.extend_from_slice(
format!(
"{} 0 obj << /Type /XObject /Subtype /Image /Width 3 /Height 4 {keys} /BitsPerComponent 8 \
/Filter /FlateDecode /DecodeParms << /Predictor 15 {colors} /BitsPerComponent 8 /Columns 3 >> /Length {} >> stream\n",
5 + i,
data.len()
)
.as_bytes(),
);
pdf.extend_from_slice(&data);
pdf.extend_from_slice(b"\nendstream endobj\n");
}
pdf.extend_from_slice(b"trailer << /Root 1 0 R >>\n%%EOF");
pdf
}
fn render(pdf: Vec<u8>) -> crate::RenderedPage {
let mut renderer = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
let page = renderer.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
assert!(page.error.is_none(), "{:?}", page.error);
assert_eq!((page.width, page.height), (WIDTH as u32, HEIGHT as u32));
page
}
+2 -2
View File
@@ -118,8 +118,8 @@ milestone = "M1"
status = "shipped"
commands = []
tools = []
evidence = ["crates/filters/src/lib.rs::chain_three_filters_with_predictor", "crates/filters/src/lzw.rs::spec_example", "crates/filters/src/predictor.rs::png_hand_vectors", "crates/filters/src/lib.rs::raw_flate_fallback_preserves_output_limits", "crates/cos/src/object.rs::raw_flate_fallback_streams_preserve_the_caller_limit", "crates/render/src/raster/tests/tiff_predicted_images.rs::an_eight_bit_rgb_image_with_tiff_predicted_rows_draws_its_colours", "crates/render/src/raster/tests/tiff_predicted_images.rs::a_sixteen_bit_grey_image_with_tiff_predicted_rows_draws_its_levels"]
notes = "Raw-deflate fallback preserves output limits in strict and tolerant decoding, including misleading zlib headers. The renderer undoes PNG predictors, and TIFF predictor 2 at 8 and 16 bits per component, a byte row at a time. Image codecs remain outside this general-purpose filter implementation."
evidence = ["crates/filters/src/lib.rs::chain_three_filters_with_predictor", "crates/filters/src/lzw.rs::spec_example", "crates/filters/src/predictor.rs::png_hand_vectors", "crates/filters/src/lib.rs::raw_flate_fallback_preserves_output_limits", "crates/cos/src/object.rs::raw_flate_fallback_streams_preserve_the_caller_limit", "crates/render/src/raster/tests/tiff_predicted_images.rs::an_eight_bit_rgb_image_with_tiff_predicted_rows_draws_its_colours", "crates/render/src/raster/tests/tiff_predicted_images.rs::a_sixteen_bit_grey_image_with_tiff_predicted_rows_draws_its_levels", "crates/filters/src/lib.rs::an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples_and_reported", "crates/cos/src/budget.rs::an_image_whose_rows_carry_no_png_tags_decodes_to_its_samples"]
notes = "Raw-deflate fallback preserves output limits in strict and tolerant decoding, including misleading zlib headers. The renderer undoes PNG predictors, and TIFF predictor 2 at 8 and 16 bits per component, a byte row at a time. An image whose PNG predictor was declared but never applied (exactly /Height rows with no filter-type bytes) is read as its samples and reported as tolerated damage, in decoding and on screen. Image codecs remain outside this general-purpose filter implementation."
[[feature]]
id = "core.image-filters"
+1 -1
View File
@@ -43,7 +43,7 @@ Other resource categories retain their existing parent-chain lookup.
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroLine truncated
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, TaLine truncated
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure |
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical; (4) `flatten::stroke`: when kurbo 0.13.1's stroker returns an outline containing NaN, which `fill` would drop whole, the path is stroked again from a copy (`robust_for_stroking`, one element out per element in) in which each curve whose control points lie within the stroke tolerance of its chord is a line (the #4907 fix, a nearly straight cubic given a NaN join, kurbo issues #617 and #519; its row here was lost in a merge and is restored with this entry) and each cubic whose second control point is its end point, as `y` builds (ISO 32000-2 §8.5.2.1 Table 58), has that control point moved the tolerance towards its first (`open_zero_end_handle`; the curve moves by at most 4/9 of the tolerance): kurbo's cusp search on such a curve's offset can stop on the end point, where the derivative is zero, and normalising it gives NaN, so at 16, 32 and 63 pt a two-curve `y` path drew nothing and a file in the PDFBox tracker lost its 32 pt "XX" outline. Only an exact zero triggers it (none of 192,000 random strokes with a handle 1e-9 long, nor of 256,000 `v` strokes, came back with NaN; 1,073 of 192,000 random `y`/`v` strokes at 1–64 pt did before and none after). A finite outline takes the old path unchanged | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate; (4) `flatten::tests::a_tiny_degenerate_cubic_does_not_drop_the_stroke` and the render crate's `stroke_degenerate_cubic` fail without the near-line replacement, `flatten::tests::a_wide_stroke_of_a_curve_with_a_zero_end_tangent_is_drawn` (widths 1–64, every join and cap, `y` and the mirrored `v`) and the render crate's `stroke_zero_end_tangent` fail without the moved control point; `a_finite_outline_is_stroked_as_before` and `a_path_with_nan_is_still_dropped` pass either way |
+179 -11
View File
@@ -6,7 +6,7 @@ use alloc::vec::Vec;
pub(crate) mod flate {
use super::*;
use crate::filter::lzw_flate::{PredictorParams, apply_predictor};
use crate::filter::lzw_flate::{PredictorParams, apply_predictor, untagged_png_rows};
pub(crate) use fallback::FlateState;
@@ -17,9 +17,15 @@ pub(crate) mod flate {
}
use crate::object::Dict;
/// PdfCraft patch: `limit` is the most bytes inflated (see `filter::decode_limit`).
/// PdfCraft patch: `limit` is the most bytes inflated (see `filter::decode_limit`), and `rows`
/// the `/Height` of the image the data is the samples of, if it is (see [`untagged_png_rows`]).
#[cfg(feature = "unsafe")]
pub(crate) fn decode(data: &[u8], params: &Dict<'_>, limit: usize) -> Option<Vec<u8>> {
pub(crate) fn decode(
data: &[u8],
params: &Dict<'_>,
limit: usize,
rows: Option<usize>,
) -> Option<Vec<u8>> {
use flate2::read::{DeflateDecoder, ZlibDecoder};
use std::io::Read;
@@ -51,19 +57,39 @@ pub(crate) mod flate {
if decoded.len() >= limit {
warn!("flate stream stopped at its decode limit of {limit} bytes");
}
let params = PredictorParams::from_params(params);
apply_predictor(decoded, &params)
undo_predictor(decoded, &PredictorParams::from_params(params), rows)
}
#[cfg(not(feature = "unsafe"))]
pub(crate) fn decode(data: &[u8], params: &Dict<'_>, limit: usize) -> Option<Vec<u8>> {
pub(crate) fn decode(
data: &[u8],
params: &Dict<'_>,
limit: usize,
rows: Option<usize>,
) -> Option<Vec<u8>> {
let decoded = fallback::decode(data, limit)?;
// PdfCraft patch: output cut at the limit is reported, never dropped silently.
if decoded.len() >= limit {
warn!("flate stream stopped at its decode limit of {limit} bytes");
}
let params = PredictorParams::from_params(params);
apply_predictor(decoded, &params)
undo_predictor(decoded, &PredictorParams::from_params(params), rows)
}
/// PdfCraft patch: the predictor undone, unless the image's rows carry none
/// ([`untagged_png_rows`]): the data is then its samples as they are, which is reported.
fn undo_predictor(
decoded: Vec<u8>,
params: &PredictorParams,
rows: Option<usize>,
) -> Option<Vec<u8>> {
if untagged_png_rows(params, decoded.len(), rows) {
warn!(
"flate image rows carry no PNG predictor tags, read as stored ({} rows)",
rows.unwrap_or(0)
);
return Some(decoded);
}
apply_predictor(decoded, params)
}
/// Ported from <https://github.com/mozilla/pdf.js/blob/master/src/core/flate_stream.js>
@@ -975,6 +1001,21 @@ impl PredictorParams {
}
}
/// PdfCraft patch: whether `len` bytes of an image `rows` high (`None` for data that isn't an
/// image's samples) are its rows without the filter-type byte each row starts with under a PNG
/// predictor (ISO 32000-2 §7.4.4.4): exactly `rows` × the row's bytes, where the predicted data
/// would be `rows` × (the row's bytes + 1). Some writers declare `/Predictor 15` without applying
/// it; read with the predictor, every row's first byte was taken for a filter type, the image
/// shifted a byte a row and came out short, drawn in fragments. PDFium, MuPDF and Poppler read
/// such data as the samples it is. Any other length is decoded with the predictor, as before.
fn untagged_png_rows(params: &PredictorParams, len: usize, rows: Option<usize>) -> bool {
let row_len = params.row_length_in_bytes();
params.predictor >= 10
&& matches!(params.bits_per_component, 1 | 2 | 4 | 8 | 16)
&& row_len > 0
&& rows.filter(|&r| r > 0).and_then(|r| r.checked_mul(row_len)) == Some(len)
}
fn apply_predictor(data: Vec<u8>, params: &PredictorParams) -> Option<Vec<u8>> {
match params.predictor {
1 => Some(data),
@@ -1289,7 +1330,7 @@ mod tests {
0x78, 0x9c, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x7, 0x0, 0x5, 0x8c, 0x1, 0xf5,
];
let decoded = flate::decode(&input, &Dict::default(), usize::MAX).unwrap();
let decoded = flate::decode(&input, &Dict::default(), usize::MAX, None).unwrap();
assert_eq!(decoded, b"Hello");
}
@@ -1297,7 +1338,7 @@ mod tests {
fn decode_flate() {
let input = [0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x7, 0x0];
let decoded = flate::decode(&input, &Dict::default(), usize::MAX).unwrap();
let decoded = flate::decode(&input, &Dict::default(), usize::MAX, None).unwrap();
assert_eq!(decoded, b"Hello");
}
@@ -1437,7 +1478,134 @@ mod tests {
/// PdfCraft patch tests: PNG predictors are undone byte by byte (`unfilter_png`).
#[cfg(test)]
mod pdfcraft_png_predictor_tests {
use crate::filter::lzw_flate::{PredictorParams, apply_predictor};
use crate::filter::lzw_flate::{PredictorParams, apply_predictor, flate, untagged_png_rows};
use crate::object::{Dict, FromBytes};
/// `data` as one stored (uncompressed) deflate block, at most 65,535 bytes.
fn stored(data: &[u8]) -> Vec<u8> {
let len = u16::try_from(data.len()).unwrap();
let mut out = vec![1];
out.extend(len.to_le_bytes());
out.extend((!len).to_le_bytes());
out.extend(data);
out
}
/// `data` inflated and its PNG predictor undone, as the last filter of an image `rows` high.
fn inflate(parms: &[u8], data: &[u8], rows: Option<usize>) -> Option<Vec<u8>> {
let parms = Dict::from_bytes(parms).unwrap();
flate::decode(&stored(data), &parms, usize::MAX, rows)
}
const RGB3: &[u8] = b"<< /Predictor 15 /Colors 3 /BitsPerComponent 8 /Columns 3 >>";
#[test]
fn an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples() {
// Three RGB pixels a row, four rows: 36 bytes, where the predictor would need 40. Every
// row starts with a byte above 4, which the predictor took for a filter type, so the
// image came out three rows of shifted samples.
let samples: Vec<u8> = (0..36).map(|i| 200 - i as u8).collect();
assert_eq!(inflate(RGB3, &samples, Some(4)).unwrap(), samples);
let params = PredictorParams {
predictor: 15,
colors: 3,
bits_per_component: 8,
columns: 3,
early_change: false,
};
assert!(
untagged_png_rows(&params, 36, Some(4)),
"the repair is reported"
);
// Not an image's samples (no height known): the predictor is undone, as before.
assert_eq!(
inflate(RGB3, &samples, None).unwrap(),
apply_predictor(samples.clone(), &params).unwrap()
);
assert!(!untagged_png_rows(&params, 36, None));
}
#[test]
fn an_image_whose_rows_carry_png_tags_still_has_its_predictor_undone() {
// The same four rows, each filtered None, then Sub: 40 bytes.
let samples: Vec<u8> = (0..36).map(|i| 200 - i as u8).collect();
let mut tagged = Vec::new();
for row in samples.chunks(9) {
tagged.push(1);
let mut left = [0u8; 3];
for px in row.chunks(3) {
tagged.extend(px.iter().zip(left).map(|(s, l)| s.wrapping_sub(l)));
left.copy_from_slice(px);
}
}
assert_eq!(tagged.len(), 40);
assert_eq!(inflate(RGB3, &tagged, Some(4)).unwrap(), samples);
}
#[test]
fn data_of_neither_length_decodes_as_it_did() {
let params = PredictorParams {
predictor: 15,
colors: 3,
bits_per_component: 8,
columns: 3,
early_change: false,
};
// Short of the untagged length, past it, or between it and the tagged one.
for len in [0, 1, 9, 27, 35, 37, 39, 41, 72] {
let data: Vec<u8> = (0..len).map(|i| (i * 7) as u8 % 5).collect();
assert!(!untagged_png_rows(&params, len, Some(4)), "{len} bytes");
assert_eq!(
inflate(RGB3, &data, Some(4)),
apply_predictor(data.clone(), &params),
"{len} bytes"
);
}
// Rows of the untagged length for another height.
assert!(!untagged_png_rows(&params, 36, Some(3)));
assert!(!untagged_png_rows(&params, 36, Some(0)));
// No PNG predictor, or one with an invalid depth.
for (predictor, bits_per_component) in [(1, 8), (2, 8), (15, 3), (15, 0)] {
let params = PredictorParams {
predictor,
bits_per_component,
..params
};
assert!(!untagged_png_rows(&params, 36, Some(4)));
}
}
#[test]
fn rows_of_no_bytes_or_of_more_than_memory_holds_do_not_panic() {
for (colors, bits_per_component, columns) in [
(0, 8, 3),
(3, 8, 0),
(255, 16, usize::MAX),
(1, 1, usize::MAX),
(3, 8, usize::MAX / 24 + 1),
] {
let params = PredictorParams {
predictor: 15,
colors,
bits_per_component,
columns,
early_change: false,
};
for rows in [None, Some(0), Some(1), Some(4), Some(usize::MAX)] {
for len in [0, 1, 36, usize::MAX] {
let _ = untagged_png_rows(&params, len, rows);
}
}
}
let zero = b"<< /Predictor 15 /Colors 3 /BitsPerComponent 8 /Columns 0 >>";
let huge =
b"<< /Predictor 15 /Colors 255 /BitsPerComponent 16 /Columns 9223372036854775807 >>";
for parms in [&zero[..], &huge[..]] {
for rows in [None, Some(0), Some(4), Some(usize::MAX)] {
let _ = inflate(parms, &[7; 36], rows);
}
}
}
/// PNG unfiltering written out from the PNG specification (§9.2–9.4), one byte at a time.
fn reference(data: &[u8], row_len: usize, bpp: usize) -> Vec<u8> {
+5 -2
View File
@@ -87,13 +87,16 @@ impl Filter {
}
}
/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`).
/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and
/// `rows` the `/Height` of the image whose samples it produces, when it is an image's last
/// filter.
pub(crate) fn apply(
&self,
data: &[u8],
params: &Dict<'_>,
#[cfg_attr(not(feature = "images"), allow(unused))] image_params: &ImageDecodeParams,
limit: usize,
rows: Option<usize>,
) -> Result<FilterResult<'static>, DecodeFailure> {
let res = match self {
Self::AsciiHexDecode => ascii_hex::decode(data)
@@ -108,7 +111,7 @@ impl Filter {
Self::LzwDecode => lzw_flate::lzw::decode(data, params, limit)
.map(FilterResult::from_data)
.ok_or(DecodeFailure::StreamDecode),
Self::FlateDecode => lzw_flate::flate::decode(data, params, limit)
Self::FlateDecode => lzw_flate::flate::decode(data, params, limit, rows)
.map(FilterResult::from_data)
.ok_or(DecodeFailure::StreamDecode),
#[cfg(feature = "images")]
+5
View File
@@ -273,11 +273,16 @@ impl<'a> Stream<'a> {
}
// PdfCraft patch: see `filter::decode_limit`.
let limit = crate::filter::decode_limit(image_params, i + 1 == count).min(max);
// PdfCraft patch: the last filter of an image produces its rows.
let rows = (i + 1 == count && image_params.height > 0)
.then(|| usize::try_from(image_params.height).ok())
.flatten();
let new = filter.apply(
current.as_ref().map(|c| c.data.as_ref()).unwrap_or(&data),
params,
image_params,
limit,
rows,
)?;
current = Some(new);
}