From b93e950acf1336bdfb2037bd9766557351cf586c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 20:39:01 +0000 Subject: [PATCH] fix(codecs): checked sizes in encoders, EXR name lookup, FITS float limit, VP8 plane copies, EXIF thumbnail bytes --- crates/codecs/src/codecs/exr.rs | 7 ++++++- crates/codecs/src/codecs/fits.rs | 2 ++ crates/codecs/src/codecs/png.rs | 2 +- crates/codecs/src/codecs/vp8.rs | 9 +++++++-- crates/codecs/src/resolution.rs | 26 +++++++++++++++++++++++++- crates/codecs/src/web.rs | 4 ++-- crates/codecs/tests/it/resolution.rs | 6 ++++-- 7 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index ec0956a4ec..fbbd043bed 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -288,9 +288,14 @@ pub(crate) fn decode_channels(bytes: &[u8], index: usize, names: &[&str], limits let (w, h) = (layer.size.0, layer.size.1); let channels = &layer.channel_data.list; let npx = w * h; + // More names than channels can only repeat one: refuse before the per-name lookups multiply. + if names.len() > channels.len() { + return Err(err("more channel names than the part has channels")); + } + let have: Vec = channels.iter().map(|c| c.name.to_string()).collect(); let mut picked: Vec<&AnyChannel> = Vec::with_capacity(names.len()); for name in names { - let c = channels.iter().find(|c| c.name.to_string() == *name).ok_or_else(|| err(format!("the part has no channel {name}")))?; + let c = have.iter().position(|n| n == name).map(|i| &channels[i]).ok_or_else(|| err(format!("the part has no channel {name}")))?; if c.sample_data.len() != npx { return Err(err("channel sample count mismatch (subsampled channels are unsupported)")); } diff --git a/crates/codecs/src/codecs/fits.rs b/crates/codecs/src/codecs/fits.rs index 214d968944..de791de239 100644 --- a/crates/codecs/src/codecs/fits.rs +++ b/crates/codecs/src/codecs/fits.rs @@ -330,6 +330,8 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result match out16 { Some(out) => Image::from_u16(w, hgt, layout, &out)?, None => { + // Admission above assumed 16-bit samples; the float fallback is twice that. + limits.check(w, hgt, layout, SampleType::F32)?; let max = (0..n).filter_map(physical).fold(0.0f64, f64::max); let white = if max <= 2.0 { 1.0 diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 1d91604abf..5b71bf406e 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -812,7 +812,7 @@ pub fn encode_indexed( dpi: Option<(f32, f32)>, stereo: Option, ) -> Result, CodecError> { - if width == 0 || height == 0 || indices.len() != width as usize * height as usize { + if width == 0 || height == 0 || (width as usize).checked_mul(height as usize) != Some(indices.len()) { return Err(CodecError::InvalidImage("index data does not match the size".into())); } if palette.is_empty() || palette.len() > 256 || indices.iter().any(|&i| usize::from(i) >= palette.len()) { diff --git a/crates/codecs/src/codecs/vp8.rs b/crates/codecs/src/codecs/vp8.rs index a24fb727cc..7e5ef59bdd 100644 --- a/crates/codecs/src/codecs/vp8.rs +++ b/crates/codecs/src/codecs/vp8.rs @@ -448,7 +448,9 @@ impl<'a> Encoder<'a> { let whole_cost = best_sse + 3 * lambda; // B_PRED: sub-blocks in raster order, each predicted from the reconstruction so far. - let saved_y = self.rec_y.data.clone(); + // B_PRED writes only this macroblock's 16 rows: save those, not the whole plane. + let rows = |p: &Plane| -> [[u8; 16]; 16] { std::array::from_fn(|r| p.data[(y0 + r) * p.width + x0..][..16].try_into().unwrap_or([0; 16])) }; + let saved_y = rows(&self.rec_y); let mut b_modes = [B_DC_PRED; 16]; let mut b_blocks: Vec = Vec::with_capacity(16); let mut b_sse = 0u64; @@ -490,7 +492,10 @@ impl<'a> Encoder<'a> { (B_PRED, None, b_blocks) } else { // Whole-block mode: undo the B_PRED reconstruction, code 16 blocks + Y2. - self.rec_y.data = saved_y; + let w = self.rec_y.width; + for (r, row) in saved_y.iter().enumerate() { + self.rec_y.data[(y0 + r) * w + x0..][..16].copy_from_slice(row); + } let mut dcs = [0i32; 16]; let mut ac_blocks: Vec<[i32; 16]> = Vec::with_capacity(16); let mut deq_blocks: Vec<[i32; 16]> = Vec::with_capacity(16); diff --git a/crates/codecs/src/resolution.rs b/crates/codecs/src/resolution.rs index a787cacbc3..8798829cf4 100644 --- a/crates/codecs/src/resolution.rs +++ b/crates/codecs/src/resolution.rs @@ -517,18 +517,42 @@ pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> { fn exif_without_thumbnail(exif: &[u8]) -> Option> { let body = tiff_body(exif); let prefix = exif.len() - body.len(); - let (_, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?; + let (order, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?; let next = prefix.checked_add(first)?.checked_add(count.checked_mul(entry_bytes)?)?; let width = if big_tiff { 8 } else { 4 }; // In bounds: `ifd0_entries` checked that the whole pointer is present. if exif.get(next..next.checked_add(width)?)?.iter().all(|b| *b == 0) { return None; } + // Classic TIFF: also blank the thumbnail JPEG itself (IFD1's JPEGInterchangeFormat/Length), + // which stays recoverable in the block once nothing points at it. + let thumb = (!big_tiff).then(|| thumbnail_range(order, body, next - prefix)).flatten(); let mut out = exif.to_vec(); out.get_mut(next..next + width)?.fill(0); + if let Some((off, len)) = thumb + && let Some(jpeg) = prefix.checked_add(off).and_then(|a| out.get_mut(a..a.checked_add(len)?)) + { + jpeg.fill(0); + } Some(out) } +/// IFD1's thumbnail JPEG as (offset, length) in `body`, from the next-IFD pointer at `ptr`. +fn thumbnail_range(order: Order, body: &[u8], ptr: usize) -> Option<(usize, usize)> { + let ifd1 = usize::try_from(order.u32(body, ptr)?).ok()?; + let (mut off, mut len) = (None, None); + for i in 0..usize::from(order.u16(body, ifd1)?) { + let e = ifd1.checked_add(2)?.checked_add(i.checked_mul(12)?)?; + let value = if order.u16(body, e + 2)? == 3 { usize::from(order.u16(body, e + 8)?) } else { usize::try_from(order.u32(body, e + 8)?).ok()? }; + match order.u16(body, e)? { + 0x0201 => off = Some(value), + 0x0202 => len = Some(value), + _ => {} + } + } + Some((off?, len?)) +} + /// The EXIF to write next to upright pixels at resolution `ppi`: Orientation 1 (see /// [`upright_exif`]), no thumbnail of the source image (see [`exif_without_thumbnail`]) and, /// when `ppi` is known, the resolution (see [`exif_with_resolution`]). diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rs index dfd0cd9b90..301e67a9b2 100644 --- a/crates/codecs/src/web.rs +++ b/crates/codecs/src/web.rs @@ -227,7 +227,7 @@ fn put_multibyte(out: &mut Vec, v: u32) { /// WBMP type 0 (1 bit per pixel, rows padded to bytes, 1 = white). `white[i]` per pixel. pub fn encode_wbmp(width: u32, height: u32, white: &[bool]) -> Result, CodecError> { let (w, h) = (width as usize, height as usize); - if width == 0 || height == 0 || white.len() != w * h { + if width == 0 || height == 0 || w.checked_mul(h) != Some(white.len()) { return Err(CodecError::InvalidImage("WBMP size must match the pixel data".into())); } let mut out = vec![0u8, 0u8]; @@ -304,7 +304,7 @@ pub fn encode_jpeg_rgb8( let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else { return Err(CodecError::encode(Format::Jpeg, "JPEG dimensions are limited to 65535")); }; - if rgb.len() != width as usize * height as usize * 3 { + if (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(3)) != Some(rgb.len()) { return Err(CodecError::InvalidImage("RGB data does not match the size".into())); } let mut out = Vec::new(); diff --git a/crates/codecs/tests/it/resolution.rs b/crates/codecs/tests/it/resolution.rs index 28c8203c96..a2bd7e8502 100644 --- a/crates/codecs/tests/it/resolution.rs +++ b/crates/codecs/tests/it/resolution.rs @@ -511,10 +511,12 @@ fn exports_drop_the_source_exif_thumbnail() { assert!(out.windows(6).any(|w| w == b"NIKON\0"), "the rest of the EXIF is kept"); near(exif_resolution(&out), ppi.map_or(300.0, |p| p.0)); } - // Only the pointer changes. + // Only the pointer and the thumbnail's own bytes (the JPEG at the end) change. let out = export_exif(&exif, None); + let thumb_len = b"\xFF\xD8stale thumbnail\xFF\xD9".len(); let differing: Vec = (0..exif.len()).filter(|&i| exif[i] != out[i]).collect(); - assert!(differing.iter().all(|&i| (8 + 2 + 4 * 12..8 + 2 + 4 * 12 + 4).contains(&i)), "{differing:?}"); + assert!(differing.iter().all(|&i| (8 + 2 + 4 * 12..8 + 2 + 4 * 12 + 4).contains(&i) || i >= exif.len() - thumb_len), "{differing:?}"); + assert!(!out.windows(5).any(|w| w == b"stale"), "the thumbnail bytes are blanked, not just unlinked"); // With a JPEG-style prefix too. let prefixed = [b"Exif\0\0".as_slice(), &exif].concat(); assert_eq!(next_ifd(e, &export_exif(&prefixed, None)[6..]), 0);