From 0ab81b6b7b3379d790e6ee4fcecdab371e3486cd Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:46:19 -0500 Subject: [PATCH 1/6] EPS import: an image too large to read skips its data An image over the pixel cap was left out without reading its data, so the program went on to read that data as PostScript and the file failed to open (Ghostscript's eps2write writes a page with a large inline image this way). The data is now skipped: the filters that find their own end (ASCIIHexDecode, ASCII85Decode, SubFileDecode) read the file up to it, without decoding what they pass. --- crates/eps/src/import/data/ops.rs | 30 +++++++++++++++++++++++++ crates/eps/src/import/tests_images.rs | 32 +++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index baca4d0ed8..7bff6a3c80 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -399,6 +399,30 @@ impl Interp<'_> { Ok(()) } + /// Skip the data an image left out (too large to read) would read from the program's own + /// file, so the program doesn't go on to read that data as PostScript. The filters that find + /// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`) + /// read the file up to it, the way the image reading all its data would leave it; the + /// filters over them, which would only decode what those pass, aren't run. When the first + /// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the + /// data where it was, as before. + fn skip_data(&mut self, src: &Source) { + let Source::File(f) = src else { return }; + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), + _ => return, + }; + let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count(); + let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec(); + *f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() }; + // A failure leaves the file as it was; the import goes on without the image either way. + if self.materialize(f).is_err() { + *f.borrow_mut() = Stream::Pending { chain, from }; + return; + } + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + } + /// The bytes a data procedure gives, called until it gives an empty string or `n` bytes. fn gather(&mut self, p: &Obj, n: usize) -> Res> { Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default()) @@ -518,6 +542,9 @@ impl Interp<'_> { let n = image.space.n(); if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS { self.out.warn(TOO_LARGE); + for src in image.sources.iter().chain(&stencil.sources) { + self.skip_data(src); + } return Ok(None); } if interleave != 3.0 { @@ -624,6 +651,9 @@ impl Interp<'_> { } if s.w.saturating_mul(s.h) > MAX_PIXELS { self.out.warn(TOO_LARGE); + for src in &s.sources { + self.skip_data(src); + } return Ok(None); } self.alloc(s.w * s.h * 4)?; diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 1600742300..8aad47fc77 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -516,3 +516,35 @@ fn tiff_predicted_rows_at_every_depth() { } assert!(wrong.is_empty(), "{wrong:#?}"); } + +/// An image too large to read is left out, and its data is skipped, as reading it would leave +/// the program: the art after it is read, not the data as PostScript. Here the data ends at its +/// `~>` (an inline image of a content stream run as a file, as PDF-reading prologs write it), at +/// a `SubFileDecode` end string, and at the end of compressed data that is read whole. +#[test] +fn the_data_of_an_image_too_large_to_read_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + for program in [ + format!( + "/ID {{ << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] \ + /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /LZWDecode filter >> \ + /DeviceRGB setcolorspace image }} def\n\ + currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\nJ1_V7fG\"r'\"b]2#:hXAd)~>\n{after}\nendstream\n" + ), + format!("10000 10000 8 [1 0 0 1 0 0] currentfile /ASCIIHexDecode filter false 3 colorimage\n0a1b 2c3d 4e5f>\n{after}"), + format!( + "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /FlateDecode filter image\n\ + x\u{9c}garbage\n%%EndData\n{after}" + ), + format!( + "10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{}\n{after}", + crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])) + ), + ] { + let r = read(&program); + assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + assert_eq!(o.len(), 1, "{program}: {:?}", r.warnings); + assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); + } +} From 725b3a469d17a465b590cc15b17c9aaf5db816fb Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:38:17 -0500 Subject: [PATCH 2/6] EPS import: images over the pixel cap are read at a lower resolution An image of more than 2^26 pixels was left out. It is now read at the least whole step that brings it within the cap, the middle sample of each block, over the same area. When its samples are more data than the reader holds, Flate or LZW last in its filters (without a predictor) is decoded keeping only the rows read. An image left out still has its data skipped, now also when a procedure reads it and when its first filter decompresses to more than the reader holds. --- crates/eps/src/import/data/filters.rs | 80 ++++++++- crates/eps/src/import/data/ops.rs | 238 ++++++++++++++++++++++---- crates/eps/src/import/tests_images.rs | 113 ++++++++++-- docs/file-format-parity.md | 5 +- 4 files changed, 378 insertions(+), 58 deletions(-) diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index e3268b240a..dbeabad1c4 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -78,14 +78,28 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { /// LZW data (`EarlyChange` 1) decoded, and how many bytes of `raw` it took. fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { + let mut out = vec![]; + let used = lzw_into(raw, &mut |bytes| { + out.extend_from_slice(bytes); + if out.len() > MAX_DATA { + return Err(PsError::Limit("decoded data is too large")); + } + Ok(()) + })?; + Ok((out, used)) +} + +/// LZW data (`EarlyChange` 1) decoded into `sink` as it goes, and how many bytes of `raw` it +/// took. +fn lzw_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res { let mut table: Vec> = (0..=255u8).map(|b| vec![b]).collect(); table.push(vec![]); table.push(vec![]); - let (mut out, mut prev): (Vec, Option>) = (vec![], None); + let mut prev: Option> = None; let (mut acc, mut bits, mut width, mut i) = (0u32, 0u32, 9u32, 0usize); loop { while bits < width { - let Some(&b) = raw.get(i) else { return Ok((out, i)) }; + let Some(&b) = raw.get(i) else { return Ok(i) }; i += 1; acc = (acc << 8) | u32::from(b); bits += 8; @@ -98,7 +112,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { width = 9; prev = None; } - 257 => return Ok((out, i)), + 257 => return Ok(i), _ => { let entry = match (table.get(code), &prev) { (Some(e), _) if !e.is_empty() => e.clone(), @@ -109,7 +123,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { } _ => return io("LZWDecode"), }; - out.extend_from_slice(&entry); + sink(&entry)?; if let Some(mut p) = prev.take() && table.len() < 4096 { @@ -123,14 +137,66 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { _ => 9, }; prev = Some(entry); - if out.len() > MAX_DATA { - return Err(PsError::Limit("decoded data is too large")); - } } } } } +/// zlib data inflated into `sink` as it goes (64 KiB at a time), and how many bytes of `raw` it +/// took. +fn flate_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res { + let mut z = flate2::Decompress::new(true); + let mut scratch = vec![0u8; 64 * 1024]; + loop { + let before = (z.total_in(), z.total_out()); + let input = raw.get(usize::try_from(z.total_in()).unwrap_or(usize::MAX)..).unwrap_or_default(); + let status = z.decompress(input, &mut scratch, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; + let made = usize::try_from(z.total_out() - before.1).unwrap_or(0); + sink(scratch.get(..made).unwrap_or_default())?; + match status { + flate2::Status::StreamEnd => break, + _ if (z.total_in(), z.total_out()) == before => break, + _ => {} + } + } + Ok(usize::try_from(z.total_in()).unwrap_or(raw.len())) +} + +/// Data compressed with filter `f` (`FlateDecode` or `LZWDecode` without a predictor) decoded +/// into `sink` as it goes, and how many bytes of `raw` it took; `None` for other filters. +pub(super) fn decode_into(f: &Filter, raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Option> { + match &*f.name { + _ if f.predictor.is_some() => None, + "FlateDecode" => Some(flate_into(raw, sink)), + "LZWDecode" => Some(lzw_into(raw, sink)), + _ => None, + } +} + +/// How many bytes of `raw` filter `f` would read, found without keeping what it decodes, for +/// data whose decoded form is too large to hold: compressed data (`FlateDecode`, `LZWDecode`, +/// `RunLengthDecode`) is decoded and dropped as it goes, a JPEG ends at its end-of-image +/// marker, as [`dct`] reads it. `None` for other filters, or data that can't be decoded. +pub(super) fn encoded_len(f: &Filter, raw: &[u8]) -> Option { + match &*f.name { + "FlateDecode" => flate_into(raw, &mut |_| Ok(())).ok(), + "LZWDecode" => lzw_into(raw, &mut |_| Ok(())).ok(), + "RunLengthDecode" => { + let mut i = 0usize; + while let Some(&n) = raw.get(i) { + i += match n { + 128 => return Some(i + 1), + 0..=127 => 2 + usize::from(n), + _ => 2, + }; + } + Some(raw.len()) + } + "DCTDecode" => Some(find(raw, &[0xFF, 0xD9]).map_or(raw.len(), |e| e + 2)), + _ => None, + } +} + /// A JPEG's pixels (gray, RGB or CMYK, 8 bits) with its channel count, and how many bytes of /// `raw` it took. A CMYK JPEG gives its samples as stored, for the image's Decode array to read /// (Adobe's CMYK JPEGs store them inverted, which a Decode array of `[1 0 1 0 1 0 1 0]` undoes). diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 7bff6a3c80..3c0842d045 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -1,4 +1,4 @@ -use super::filters::{Filter, Predictor, Stream, decode, fax_settings, io}; +use super::filters::{Filter, Predictor, Stream, decode, decode_into, encoded_len, fax_settings, io}; use super::pixels::{Pixels, Spec, by_rows, by_samples, masked, source}; use super::{ Affine, Color, DictRef, HashMap, ImageBlob, ImageObject, Inks, Interp, Key, Lexer, Node, NodeId, NodeKind, Obj, Op, OpacityMask, Paint, PsError, @@ -15,6 +15,8 @@ const MAX_PIXELS: usize = 1 << 26; /// Why an image is missing. const TOO_LARGE: &str = "images too large to read were left out"; +/// Why an image is at a lower resolution than the file's. +const REDUCED: &str = "images of more than 67 million pixels were read at a lower resolution"; /// Most distinct colours an image converts through a tint transform. const MAX_TINTS: usize = 1 << 16; @@ -406,7 +408,20 @@ impl Interp<'_> { /// filters over them, which would only decode what those pass, aren't run. When the first /// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the /// data where it was, as before. - fn skip_data(&mut self, src: &Source) { + fn skip_data(&mut self, src: &Source, n: usize) { + // A procedure (`{ currentfile buf readhexstring pop }`) reads the data itself: it is + // called, and what it gives dropped, until it has given the image's `n` bytes or ends. + if let Source::Proc(p) = src { + let mut given = 0usize; + while given < n { + let Ok(len) = self.call(p.clone()).and_then(|()| self.pop_str()).map(|s| s.len()) else { return }; + if len == 0 { + return; + } + given = given.saturating_add(len); + } + return; + } let Source::File(f) = src else { return }; let (chain, from) = match &*f.borrow() { Stream::Pending { chain, from } => (chain.clone(), from.clone()), @@ -415,14 +430,128 @@ impl Interp<'_> { let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count(); let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec(); *f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() }; - // A failure leaves the file as it was; the import goes on without the image either way. if self.materialize(f).is_err() { - *f.borrow_mut() = Stream::Pending { chain, from }; - return; + // Decompressed data too large to hold: the first filter only measures it instead, + // and the file is read past it. Data that can't be decoded at all leaves the file as + // it was; the import goes on without the image either way. + let Some(first) = chain.first() else { return }; + match &from { + Some(r) => { + let mut b = r.borrow_mut(); + if let Stream::Buf { data, pos, .. } = &mut *b + && let Some(used) = encoded_len(first, data.get(*pos..).unwrap_or_default()) + { + *pos = pos.saturating_add(used); + } else { + drop(b); + *f.borrow_mut() = Stream::Pending { chain, from }; + return; + } + } + None => match encoded_len(first, self.lex.data()) { + Some(used) => self.lex.advance(used), + None => { + *f.borrow_mut() = Stream::Pending { chain, from }; + return; + } + }, + } } *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; } + /// The rows image `s` reads at `step` (rows of `row` bytes), when its one source is the + /// program's data with Flate or LZW last among its filters (and no predictor): the filters + /// before it are decoded as usual, and it decodes into the rows read alone, dropping the + /// others as it goes. `None` (nothing read) for other data, or rows read that would still be + /// more than the reader holds. + fn read_rows(&mut self, s: &Spec, row: usize, step: usize) -> Res>> { + let ([Source::File(f)], oh) = (s.sources.as_slice(), s.h.div_ceil(step)) else { return Ok(None) }; + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), + _ => return Ok(None), + }; + let Some((last, head)) = chain.split_last() else { return Ok(None) }; + if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { + return Ok(None); + } + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + self.alloc(kept)?; + // The compressed data: what the filters before the last one decode, or the file itself. + let compressed = if head.is_empty() { + None + } else { + *f.borrow_mut() = Stream::Pending { chain: head.to_vec(), from: from.clone() }; + if let Err(e) = self.materialize(f) { + *f.borrow_mut() = Stream::Pending { chain, from }; + return Err(e); + } + match std::mem::replace(&mut *f.borrow_mut(), Stream::Buf { data: vec![], pos: 0, rgb: None }) { + Stream::Buf { data, pos, .. } => Some(data.get(pos..).unwrap_or_default().to_vec()), + _ => Some(vec![]), + } + }; + let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); + // Past the image's data and as much again the data is not an image's: it stops there. + let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let mut sink = |mut chunk: &[u8]| -> Res { + while !chunk.is_empty() { + let (r, off) = (seen / row.max(1), seen % row.max(1)); + let take = (row - off).min(chunk.len()); + if r < s.h && picked(r / step, step, s.h) == r { + rows.extend_from_slice(chunk.get(..take).unwrap_or_default()); + } + seen += take; + chunk = chunk.get(take..).unwrap_or_default(); + } + if seen > most { + return Err(PsError::Limit("decoded data is too large")); + } + Ok(()) + }; + let used = match &compressed { + Some(data) => decode_into(last, data, &mut sink), + None => match &from { + Some(r) => { + let b = r.borrow(); + let Stream::Buf { data, pos, .. } = &*b else { return io("filter") }; + let used = decode_into(last, data.get(*pos..).unwrap_or_default(), &mut sink); + drop(b); + if let (Some(Ok(n)), Stream::Buf { pos, .. }) = (&used, &mut *r.borrow_mut()) { + *pos = pos.saturating_add(*n); + } + used + } + None => { + let used = decode_into(last, self.lex.data(), &mut sink); + if let Some(Ok(n)) = &used { + self.lex.advance(*n); + } + used + } + }, + }; + drop(sink); + let Some(used) = used else { return Ok(None) }; + used?; + self.spend((seen / 4096) as u64)?; + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + rows.resize(kept, 0); + Ok(Some(rows)) + } + + /// Leave out image `s` (too large to read), skipping its data: `None`, the image it gives. + fn leave_out(&mut self, s: &Spec) -> Option { + self.out.warn(TOO_LARGE); + let n = if s.stencil.is_some() { 1 } else { s.space.n() }; + let per_source = if s.sources.len() > 1 { 1 } else { n }; + let bytes = (s.w.saturating_mul(per_source).saturating_mul(usize::from(s.bpc))).div_ceil(8).saturating_mul(s.h); + for src in &s.sources { + self.skip_data(src, bytes); + } + None + } + /// The bytes a data procedure gives, called until it gives an empty string or `n` bytes. fn gather(&mut self, p: &Obj, n: usize) -> Res> { Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default()) @@ -540,13 +669,6 @@ impl Interp<'_> { let mut stencil = self.image_dict(&mask, false)?; stencil.space = Space::Gray; let n = image.space.n(); - if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS { - self.out.warn(TOO_LARGE); - for src in image.sources.iter().chain(&stencil.sources) { - self.skip_data(src); - } - return Ok(None); - } if interleave != 3.0 { let src = image.sources.first().cloned().ok_or(PsError::Ps("undefined", "DataSource".into()))?; let (pixels, samples) = if interleave == 2.0 { @@ -567,7 +689,11 @@ impl Interp<'_> { stencil.sources = vec![Source::Str(pixels)]; image.sources = vec![Source::Str(samples)]; } - let Some(mut img) = self.decode_image(image)? else { return Ok(None) }; + let Some(mut img) = self.decode_image(image)? else { + // The mask's own data (`InterleaveType` 3) is skipped with the image's. + let _ = self.leave_out(&stencil); + return Ok(None); + }; let Some(m) = self.decode_image(stencil)? else { return Ok(Some(img)) }; let (w, h, mw, mh) = (img.w as usize, img.h as usize, m.w as usize, m.h as usize); for (i, px) in img.rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { @@ -649,19 +775,28 @@ impl Interp<'_> { if !matches!(s.bpc, 1 | 2 | 4 | 8 | 12 | 16) { return ps_err("rangecheck", "BitsPerComponent"); } - if s.w.saturating_mul(s.h) > MAX_PIXELS { - self.out.warn(TOO_LARGE); - for src in &s.sources { - self.skip_data(src); - } - return Ok(None); - } - self.alloc(s.w * s.h * 4)?; + // An image of more pixels than the cap is read at a lower resolution: every `step`th + // sample of every `step`th row (the middle one of each `step` × `step` block). + let step = reduction(s.w, s.h); + let (ow, oh) = (s.w.div_ceil(step), s.h.div_ceil(step)); let n = if s.stencil.is_some() { 1 } else { s.space.n() }; let bpc = usize::from(s.bpc); - for src in &s.sources { + // A reduced image compressed last with Flate or LZW keeps only the rows it reads, as they + // are decoded: its whole data can be more than the reader holds. + let streamed = match if step > 1 { self.read_rows(&s, (s.w * n * bpc).div_ceil(8), step) } else { Ok(None) } { + Ok(rows) => rows, + Err(PsError::Limit(_)) => return Ok(self.leave_out(&s)), + Err(e) => return Err(e), + }; + for src in s.sources.iter().filter(|_| streamed.is_none()) { if let Source::File(f) = src { - self.materialize(f)?; + match self.materialize(f) { + Ok(()) => {} + // Decoded data past the cap: a reduced image is left out (its data skipped) + // rather than failing the file, as an image too large to read at all is. + Err(PsError::Limit(_)) if step > 1 => return Ok(self.leave_out(&s)), + Err(e) => return Err(e), + } } } // A decoded JPEG gives 8-bit gray, RGB or CMYK samples whatever the color space says. @@ -686,11 +821,28 @@ impl Interp<'_> { if sources.len() > n { return ps_err("rangecheck", "DataSource"); } - let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?; - self.alloc(plane.saturating_mul(sources.len()))?; - let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; - for p in &mut planes { - p.resize(row * s.h, 0); + // With only the rows read kept, row `i` of the plane is the `i`th row read. + let rows_kept = streamed.is_some(); + let planes = match streamed { + Some(rows) => vec![rows], + None => { + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + if step > 1 { + return Ok(self.leave_out(&s)); + } + return Err(PsError::Limit("decoded data is too large")); + }; + self.alloc(plane.saturating_mul(sources.len()))?; + let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?; + for p in &mut planes { + p.resize(row * s.h, 0); + } + planes + } + }; + self.alloc(ow * oh * 4)?; + if step > 1 { + self.out.warn(REDUCED); } let max = ((1u32 << bpc.min(16)) - 1) as f64; let sample = |plane: &[u8], y: usize, i: usize| -> u32 { @@ -714,19 +866,19 @@ impl Interp<'_> { // with the default Decode array. let decode = if s.decode.len() >= 2 * n && jpeg.is_none_or(|c| c == 4) { s.decode.clone() } else { default_decode }; let paint = self.g.paint.color().map(|c| c.to_rgba8(1.0)); - let mut rgba = Vec::with_capacity(s.w * s.h * 4); + let mut rgba = Vec::with_capacity(ow * oh * 4); // CMYK samples keep their ink amounts, as the Decode array reads them. let mut inks = if matches!(space, Space::Cmyk) && s.stencil.is_none() { - self.alloc(s.w * s.h * 4)?; - Some(Vec::with_capacity(s.w * s.h * 4)) + self.alloc(ow * oh * 4)?; + Some(Vec::with_capacity(ow * oh * 4)) } else { None }; let mut cache: HashMap, [u8; 3]> = HashMap::new(); let mut raw = vec![0u32; n]; let mut comps = vec![0f64; n]; - for y in 0..s.h { - for x in 0..s.w { + for y in (0..oh).map(|y| if rows_kept { y } else { picked(y, step, s.h) }) { + for x in (0..ow).map(|x| picked(x, step, s.w)) { for (c, slot) in raw.iter_mut().enumerate() { *slot = match planes.as_slice() { [one] => sample(one, y, x * n + c), @@ -764,7 +916,9 @@ impl Interp<'_> { rgba.extend([rgb[0], rgb[1], rgb[2], if masked { 0 } else { 255 }]); } } - Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix })) + // The reduced samples cover the image's area: image space scaled to them. + let matrix = Affine::scale_non_uniform(ow as f64 / s.w as f64, oh as f64 / s.h as f64) * s.matrix; + Ok(Some(Pixels { w: ow as u32, h: oh as u32, rgba, inks, matrix })) } /// One pixel's colour in `space` as display RGB. @@ -836,3 +990,19 @@ impl Interp<'_> { Some(OpacityMask::new(Node::new(self.out.doc.alloc_id(), NodeKind::Image(Box::new(im))), true)) } } + +/// The sample (or row) of `len` a reduced image reads as its `i`th at `step`: the middle one of +/// its block of `step`, the last one in a short last block. +fn picked(i: usize, step: usize, len: usize) -> usize { + (i * step + step / 2).min(len.saturating_sub(1)) +} + +/// The step [`Interp::decode_image`] reads a `w` × `h` image at: 1 (every sample) within +/// [`MAX_PIXELS`], else the least that brings the samples it reads within it. +fn reduction(w: usize, h: usize) -> usize { + let mut step = 1; + while w.div_ceil(step).saturating_mul(h.div_ceil(step)) > MAX_PIXELS { + step += 1; + } + step +} diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 8aad47fc77..0032d0a1a8 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -517,34 +517,117 @@ fn tiff_predicted_rows_at_every_depth() { assert!(wrong.is_empty(), "{wrong:#?}"); } -/// An image too large to read is left out, and its data is skipped, as reading it would leave -/// the program: the art after it is read, not the data as PostScript. Here the data ends at its -/// `~>` (an inline image of a content stream run as a file, as PDF-reading prologs write it), at -/// a `SubFileDecode` end string, and at the end of compressed data that is read whole. +/// An image over the reader's pixel cap is read at a lower resolution, or when its data is too +/// large to hold left out with its data skipped; either way the program goes on after the data, +/// as reading the whole image would leave it: the art after it is read, not the data as +/// PostScript. Here the data ends at its `~>` (an inline image of a content stream run as a file, +/// as PDF-reading prologs write it), at a `SubFileDecode` end string, and at the end of +/// compressed data that is read whole. #[test] fn the_data_of_an_image_too_large_to_read_is_skipped() { let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let packed = crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])); for program in [ format!( "/ID {{ << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] \ - /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /LZWDecode filter >> \ + /DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter >> \ /DeviceRGB setcolorspace image }} def\n\ - currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\nJ1_V7fG\"r'\"b]2#:hXAd)~>\n{after}\nendstream\n" + currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\n{packed}\n{after}\nendstream\n" ), format!("10000 10000 8 [1 0 0 1 0 0] currentfile /ASCIIHexDecode filter false 3 colorimage\n0a1b 2c3d 4e5f>\n{after}"), format!( - "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /FlateDecode filter image\n\ - x\u{9c}garbage\n%%EndData\n{after}" - ), - format!( - "10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{}\n{after}", - crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64])) + "10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter image\n\ + {packed}\n%%EndData\n{after}" ), + format!("10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{packed}\n{after}"), ] { let r = read(&program); - assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("too large to read") || w.contains("lower resolution")), "{program}: {:?}", r.warnings); let o = super::tests::objects(&r.document); - assert_eq!(o.len(), 1, "{program}: {:?}", r.warnings); - assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); + let last = o.last().expect("the art after the image"); + assert_eq!(super::tests::fill(last), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); + } +} + +/// An image of more pixels than the reader's cap (2^26) is read at a lower resolution, every +/// second sample of every second row here, over the same area, with a note; not left out. +#[test] +fn an_image_over_the_pixel_cap_is_read_at_a_lower_resolution() { + // 9000 × 8000 one-bit samples, every row the same: its left half ones, painted. + let row = format!("{}{}", "ff".repeat(563), "00".repeat(562)); + let r = read(&format!("0 0 1 setrgbcolor 90 80 scale 9000 8000 true [9000 0 0 -8000 0 8000] <{row}> imagemask")); + assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); + let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { + unreachable!() + }; + assert_eq!((im.width, im.height), (4500, 4000)); + // Its 4500 × 4000 pixels cover the 90 × 80 points the image does. + let corner = im.xf * kurbo::Point::new(4500.0, 4000.0); + let origin = im.xf * kurbo::Point::ZERO; + assert!(((corner - origin).x.abs() - 90.0).abs() < 1e-6 && ((corner - origin).y.abs() - 80.0).abs() < 1e-6, "{:?}", im.xf); + // Left half painted, right half clear. + assert_eq!(pixel(&r.document, 100, 2000)[3], 255); + assert_eq!(pixel(&r.document, 4400, 2000)[3], 0); +} + +/// An image over the pixel cap whose samples are more data than the reader holds (9500 × 9500 +/// RGB is 270 MB) is read at a lower resolution too when Flate or LZW compresses it last: only +/// the rows it reads are kept as they are decoded. +#[test] +fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { + let (w, h) = (9500usize, 9500usize); + let mut samples = Vec::with_capacity(w * h * 3); + for y in 0..h { + let px: [u8; 3] = if y < h / 2 { [255, 0, 0] } else { [0, 0, 255] }; + samples.extend(std::iter::repeat_n(px, w).flatten()); + } + let data = crate::ps::ascii85(&crate::ps::deflate(&samples)); + drop(samples); + let r = read(&format!( + "95 95 scale {w} {h} 8 [{w} 0 0 -{h} 0 {h}] currentfile /ASCII85Decode filter /FlateDecode filter false 3 colorimage\n{data}\n\ + 0 1 0 setrgbcolor 0 0 0.1 0.1 rectfill" + )); + assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); + let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { + unreachable!() + }; + assert_eq!((im.width, im.height), (4750, 4750)); + // The rows read from the top half are red, from the bottom half blue. + assert_eq!(pixel(&r.document, 10, 10), [255, 0, 0, 255]); + assert_eq!(pixel(&r.document, 10, 4740), [0, 0, 255, 255]); + // The art after the data is read. + assert_eq!(super::tests::objects(&r.document).len(), 2); +} + +/// An image too large to read even at a lower resolution (its samples are more data than the +/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure +/// is called until the data ends; when its first filter decompresses to more than the reader +/// holds (and can't be read a row at a time), the compressed data is measured without keeping it. +#[test] +fn the_data_of_an_image_too_large_to_hold_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + // Predicted rows aren't decoded a row at a time: such an image is left out. + let mut flate = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); + flate.extend(&zeros); + flate.extend(format!("\n{after}").as_bytes()); + for program in [ + format!( + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + flate, + ] { + let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); + let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + file.extend(&program); + file.extend(b"\nshowpage\n%%EOF\n"); + let r = import(&file).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings); + assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{text}"); } } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d3e2f03031..65b45f73b6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (EPS import: images over 67 million pixels are read at a lower resolution; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -153,7 +153,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | | PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160) | -| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | +| EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); an image of more than 2^26 pixels is read at a lower resolution (every second, third… sample of every second, third… row), not left out, with a note; when its data is more than the reader holds, Flate or LZW compressing it last (without a predictor) is decoded keeping only the rows read; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as ``, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`) | | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). CNC preset and VCarve QA remain open | @@ -191,6 +191,7 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | EPS import: an image of more than 2^26 pixels (the reader's cap) was left out, so a page that is one large scan or photo came in empty. It is now read at a lower resolution: the least whole step that brings it within the cap, the middle sample of each step × step block, over the image's whole area, with the note *images of more than 67 million pixels were read at a lower resolution*. When its samples are more data than the reader holds (256 MB), an image whose last filter is Flate or LZW without a predictor is decoded a row at a time, keeping only the rows read (an 11903 × 8423 RGB page, 300 MB, comes in at 5952 × 4212). An image left out still has its data skipped (#6003), now also when a procedure reads it (called until it has given the image's data or ends) and when its first filter decompresses to more than the reader holds (the compressed data is measured without keeping it). Tests `an_image_over_the_pixel_cap_is_read_at_a_lower_resolution`, `an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads`, `the_data_of_an_image_too_large_to_hold_is_skipped`; scores unchanged | | 2026-11-06 | minor | SVG import: filter and mask regions clip (SVG 1.1 §15.5, §14.4). An object whose imported blur, shadow or glow reaches past its filter's region comes in inside a clip group cut to the region (#5876), and a mask's art is cut to the mask's region, in user space or the object's bounding box (#5875). Objects that fit their regions, and our own exports, are unchanged; primitive subregions are still ignored. Tests `import_live::a_blur_is_cut_at_its_filter_region`, `import_live::a_mask_counts_only_inside_its_region` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-06 | minor | SVG import: a Gaussian blur keeps the colour space its filter asks for with `color-interpolation-filters` (initially `linearRGB`, SVG 1.1 §15.7.6): a linear-light blur becomes Gaussian Blur with the new `linear` parameter, which blurs the colours in linear light (black beside white meets at about 188/255 instead of 128), and SVG export writes it back on the `feGaussianBlur` (#5877). Blurs that ask for sRGB, and the blurs our own export writes, are as before. CSS export still writes `blur()`. Tests `pixel::tests::linear_light_blur_mixes_light_not_values` (crate `vectorcraft-effects`), `import_live::a_gaussian_blur_keeps_its_colour_space` (crate `vectorcraft-svg`); scores unchanged | | 2026-11-06 | minor | PDF export and PDF-compatible `.ai` saves write each object's URL (Attributes panel) as a link annotation with a URI action (web and mail URLs only) over the bounds of the object that shows, trimmed by its clipping groups (ISO 32000-1, 12.5.6.5 and 12.6.4.7); hidden objects, layers that don't print and prints have none, and PDF/X files leave them out with a warning (#5785). Own-fixture tests in `tests::links`; PDF import doesn't read links back as URLs yet; scores unchanged | From 6d55dbd93ecc3e0b18f9d44c4dadb2d4033debcd Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:02:51 -0500 Subject: [PATCH 3/6] EPS import: reduced image tests panic instead of unreachable --- crates/eps/src/import/tests_images.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 0032d0a1a8..9f6a76defc 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -558,7 +558,7 @@ fn an_image_over_the_pixel_cap_is_read_at_a_lower_resolution() { let r = read(&format!("0 0 1 setrgbcolor 90 80 scale 9000 8000 true [9000 0 0 -8000 0 8000] <{row}> imagemask")); assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { - unreachable!() + panic!("an image") }; assert_eq!((im.width, im.height), (4500, 4000)); // Its 4500 × 4000 pixels cover the 90 × 80 points the image does. @@ -589,7 +589,7 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { )); assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings); let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else { - unreachable!() + panic!("an image") }; assert_eq!((im.width, im.height), (4750, 4750)); // The rows read from the top half are red, from the bottom half blue. From 88ba1c384264d9cb3760074b08e1f2a15da605a9 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:12:11 -0500 Subject: [PATCH 4/6] EPS import: a left-out image's mask data is skipped, unfiltered or shared When an image too large to read is left out, the data of its mask (InterleaveType 3) read straight from the program file was not skipped, so the program read the samples as PostScript. Unfiltered data is now read past by its byte count. A shared filter whose first filter read its data before a later one failed is left empty, past that data, instead of being armed to decode again from there. An unreduced image whose samples are more data than the reader holds still stops the read, as #3568 has it; the code says so. --- crates/eps/src/import/data/ops.rs | 39 ++++++++++++++++++++++++--- crates/eps/src/import/tests_images.rs | 28 +++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index ccd8824c1a..01989f3b60 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -408,8 +408,10 @@ impl Interp<'_> { /// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`) /// read the file up to it, the way the image reading all its data would leave it; the /// filters over them, which would only decode what those pass, aren't run. When the first - /// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the - /// data where it was, as before. + /// filter decompresses, it is run alone; when it can't hold what it decompresses, it measures + /// its data instead. Unfiltered data is read past by its `n` bytes. A failure that read + /// nothing leaves the data where it was; one after a filter read its data leaves the file + /// past it, with nothing more to read. fn skip_data(&mut self, src: &Source, n: usize) { // A procedure (`{ currentfile buf readhexstring pop }`) reads the data itself: it is // called, and what it gives dropped, until it has given the image's `n` bytes or ends. @@ -425,14 +427,39 @@ impl Interp<'_> { return; } let Source::File(f) = src else { return }; - let (chain, from) = match &*f.borrow() { + let (chain, from) = match &mut *f.borrow_mut() { Stream::Pending { chain, from } => (chain.clone(), from.clone()), - _ => return, + // The data unfiltered: its `n` bytes are read past, as reading them would. + Stream::Current => { + let k = n.min(self.lex.data().len()); + self.lex.advance(k); + return; + } + Stream::Buf { data, pos, .. } => { + *pos = pos.saturating_add(n).min(data.len()); + return; + } }; let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count(); let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec(); *f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() }; + // How much of the file the filters are over is left. + let left = |me: &mut Self| match &from { + None => Some(me.lex.data().len()), + Some(r) => match &*r.borrow() { + Stream::Buf { data, pos, .. } => Some(data.len().saturating_sub(*pos)), + Stream::Current => Some(me.lex.data().len()), + Stream::Pending { .. } => None, + }, + }; + let before = left(self); if self.materialize(f).is_err() { + // A filter that read its data before a later one failed has the file past that data, + // where reading the image would leave it: the file is empty from there. + if left(self) != before { + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + return; + } // Decompressed data too large to hold: the first filter only measures it instead, // and the file is read past it. Data that can't be decoded at all leaves the file as // it was; the import goes on without the image either way. @@ -828,6 +855,10 @@ impl Interp<'_> { let planes = match streamed { Some(rows) => vec![rows], None => { + // More samples than the reader holds: a reduced image is left out (its data + // skipped), while one within the pixel cap whose samples are still too much data + // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane + // is refused). let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { if step > 1 { return Ok(self.leave_out(&s)); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 9f6a76defc..b4e47d7ba7 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -631,3 +631,31 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{text}"); } } + +/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is +/// skipped too: unfiltered from the program's own file by its byte count, and through a filter +/// shared with later reads, which then find the file past the data (here the second filter fails +/// on what the first decoded) rather than decoding the program after it. +#[test] +fn the_mask_data_of_an_image_left_out_is_skipped() { + let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; + let masked = |source: &str| { + format!( + "<< /ImageType 3 /InterleaveType 3 /DataDict << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 \ + /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] /DataSource (x) >> \ + /MaskDict << /ImageType 1 /Width 10 /Height 10 /BitsPerComponent 1 /Decode [0 1] /ImageMatrix [1 0 0 1 0 0] \ + /DataSource {source} >> >> /DeviceRGB setcolorspace image" + ) + }; + for program in [ + // 10 rows of 2 bytes, not PostScript. + format!("{}\n{}\n{after}", masked("currentfile"), "@".repeat(20)), + format!("/F currentfile /ASCIIHexDecode filter /ASCII85Decode filter def {}\n7676>\nF read {{ pop }} if {after}", masked("F")), + ] { + let r = read(&program); + assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings); + let o = super::tests::objects(&r.document); + assert_eq!(o.len(), 1, "{program}: {:?}", r.warnings); + assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}"); + } +} From b40ea27592a9f6408694d3fdb35e753373b0a7e2 Mon Sep 17 00:00:00 2001 From: centy <caongare@gmail.com> Date: Sun, 22 Nov 2026 09:04:25 -0500 Subject: [PATCH 5/6] Put a left-out image's filters back before skipping its data; test the measuring charge materialize now empties a file whose decode failed, so the reduced image that is left out restores its pending filters for skip_data. The new test runs an image over 300 MB of compressed zeros from a reusable stream in a loop until the operation budget ends. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/eps/src/import/data/ops.rs | 13 ++++++++++++- crates/eps/src/import/tests_images.rs | 16 ++++++++-------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index ce1c811d43..b59d0102ab 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -936,11 +936,22 @@ impl Interp<'_> { }; for src in s.sources.iter().filter(|_| streamed.is_none()) { if let Source::File(f) = src { + // A decode that fails leaves the file empty (`materialize`), but a reduced image + // that is left out still has its data to skip: its filters are put back for that. + let pending = match &*f.borrow() { + Stream::Pending { chain, from } => Some((chain.clone(), from.clone())), + _ => None, + }; match self.materialize(f) { Ok(()) => {} // Decoded data past the cap: a reduced image is left out (its data skipped) // rather than failing the file, as an image too large to read at all is. - Err(PsError::Limit(_)) if step > 1 => return Ok(self.leave_out(&s)), + Err(PsError::Limit(_)) if step > 1 => { + if let Some((chain, from)) = pending { + *f.borrow_mut() = Stream::Pending { chain, from }; + } + return Ok(self.leave_out(&s)); + } Err(e) => return Err(e), } } diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 26b3499495..a9385f8eff 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -668,16 +668,16 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { } /// Measuring the data of an image too large to hold decompresses it, and that is charged to the -/// operation budget: a small compressed stream that decodes to 300 MB, kept in a reusable stream -/// and measured again on every pass of a loop, runs out of the budget. +/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed +/// zeros is left out and measured again each time a loop runs the stream from its start, runs out +/// of the budget. #[test] fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() { - let data = crate::ps::ascii85(&crate::ps::deflate(&vec![0u8; 300 << 20])); - super::tests::runs_out_of_budget(&format!( - "/R currentfile /ASCII85Decode filter /ReusableStreamDecode filter def -{data} - {{ R 0 setfileposition 10000 10000 8 [1 0 0 1 0 0] R << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage }} loop" - )); + let mut program = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); + program.extend(crate::ps::deflate(&vec![0u8; 300 << 20])); + let hex: String = program.iter().map(|b| format!("{b:02x}")).collect(); + super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop")); } /// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is From ec674949dff061d3ab74ab08d8a4263e561c55f0 Mon Sep 17 00:00:00 2001 From: centy <caongare@gmail.com> Date: Sun, 22 Nov 2026 10:53:21 -0500 Subject: [PATCH 6/6] Decode an image's source in a helper that puts a left-out image's filters back decode_image was over clippy's cognitive-complexity limit with the restore inline. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- crates/eps/src/import/data/ops.rs | 46 ++++++++++++++++++------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index b59d0102ab..f5d45449f2 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -915,6 +915,27 @@ impl Interp<'_> { Ok(Spec { w, h, bpc, space, decode: vec![], matrix, sources, mask_color: None, stencil }) } + /// Decode the filters image source `f` waits to run. `false` when the decoded data is past + /// what the reader holds and the image is `reduced` (read at a lower resolution): a decode that + /// fails leaves the file empty (`materialize`), but such an image is left out with its data + /// still to skip, so its filters are put back for that. + fn decode_source(&mut self, f: &Rc<RefCell<Stream>>, reduced: bool) -> Res<bool> { + let pending = match &*f.borrow() { + Stream::Pending { chain, from } => Some((chain.clone(), from.clone())), + _ => None, + }; + match self.materialize(f) { + Ok(()) => Ok(true), + Err(PsError::Limit(_)) if reduced => { + if let Some((chain, from)) = pending { + *f.borrow_mut() = Stream::Pending { chain, from }; + } + Ok(false) + } + Err(e) => Err(e), + } + } + /// The image's pixels, straight RGBA, rows from the first one read, and a CMYK image's ink /// amounts. fn decode_image(&mut self, s: Spec) -> Res<Option<Pixels>> { @@ -935,25 +956,12 @@ impl Interp<'_> { Err(e) => return Err(e), }; for src in s.sources.iter().filter(|_| streamed.is_none()) { - if let Source::File(f) = src { - // A decode that fails leaves the file empty (`materialize`), but a reduced image - // that is left out still has its data to skip: its filters are put back for that. - let pending = match &*f.borrow() { - Stream::Pending { chain, from } => Some((chain.clone(), from.clone())), - _ => None, - }; - match self.materialize(f) { - Ok(()) => {} - // Decoded data past the cap: a reduced image is left out (its data skipped) - // rather than failing the file, as an image too large to read at all is. - Err(PsError::Limit(_)) if step > 1 => { - if let Some((chain, from)) = pending { - *f.borrow_mut() = Stream::Pending { chain, from }; - } - return Ok(self.leave_out(&s)); - } - Err(e) => return Err(e), - } + // Decoded data past the cap: a reduced image is left out (its data skipped) rather + // than failing the file, as an image too large to read at all is. + if let Source::File(f) = src + && !self.decode_source(f, step > 1)? + { + return Ok(self.leave_out(&s)); } } // A decoded JPEG gives 8-bit gray, RGB or CMYK samples whatever the color space says.