fix(codecs): checked sizes in encoders, EXR name lookup, FITS float limit, VP8 plane copies, EXIF thumbnail bytes

This commit is contained in:
Dylan M. Taylor committed 2026-11-03 20:39:01 +00:00
1 parent d07684a379
commit b93e950acf
7 files changed
+47 -9

No files matched your search

+6 -1
View File
@@ -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<String> = channels.iter().map(|c| c.name.to_string()).collect();
let mut picked: Vec<&AnyChannel<FlatSamples>> = 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)"));
}
+2
View File
@@ -330,6 +330,8 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
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
+1 -1
View File
@@ -812,7 +812,7 @@ pub fn encode_indexed(
dpi: Option<(f32, f32)>,
stereo: Option<PngStereo>,
) -> Result<Vec<u8>, 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()) {
+7 -2
View File
@@ -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<Block> = 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);
+25 -1
View File
@@ -517,18 +517,42 @@ pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> {
fn exif_without_thumbnail(exif: &[u8]) -> Option<Vec<u8>> {
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`]).
+2 -2
View File
@@ -227,7 +227,7 @@ fn put_multibyte(out: &mut Vec<u8>, 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<Vec<u8>, 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();
+4 -2
View File
@@ -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<usize> = (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);