Skip to content
Merged
1 change: 1 addition & 0 deletions crates/codecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ pub fn read_header_unguarded(bytes: &[u8], format: Format) -> Result<Header> {
Format::WebP => webp::header(bytes)?,
Format::Psd => psd::header(bytes)?,
Format::Heif => heif::header(bytes)?,
Format::Gif | Format::Bmp => other::header(bytes, format)?,
// rare here (or, for JPEG XL, without a header reader yet): a small decode, as before
_ => {
let d = decode_unguarded(bytes, format, &DecodeOptions::fit(64, 64))?;
Expand Down
134 changes: 134 additions & 0 deletions crates/codecs/src/other.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,136 @@ use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use image::{DynamicImage, ImageDecoder};

/// Canvases up to this many pixels are still decoded by [`header`] (at most 16 MB), so a truncated
/// small file is refused at import as before.
const HEADER_DECODE_MAX_PIXELS: u64 = 4_000_000;

/// Stored size for the import probe (issue #2553). The probe used to decode these in full, and a
/// few-dozen-byte file declaring a gigapixel canvas allocated gigabytes. The size now comes from the
/// header and must be one the file's bytes can fill; only a canvas small enough to be cheap is
/// decoded (to catch truncation). Orientation is always 1: neither format carries EXIF here.
pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
let cursor = std::io::Cursor::new(bytes);
let (w, h) = match format {
Format::Gif => image::codecs::gif::GifDecoder::new(cursor).map_err(err)?.dimensions(),
Format::Bmp => image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?.dimensions(),
_ => return Err(Error::Unsupported(format, "not handled by this decoder")),
};
if w == 0 || h == 0 {
return Err(Error::Malformed(format, "zero dimension".into()));
}
check_fillable(format, bytes, w, h)?;
if u64::from(w).saturating_mul(u64::from(h)) <= HEADER_DECODE_MAX_PIXELS {
let d = decode(bytes, format, &DecodeOptions::fit(64, 64))?;
return Ok((d.source_width, d.source_height, d.orientation));
}
Ok((w, h, 1))
}

/// The decoder's allocation limit: the RGBA buffer of the largest image `opts` allows. It bounds the
/// decoders' own frame buffers only: `DynamicImage::from_decoder` allocates the canvas without
/// consulting it, so the canvas is bounded by `check_size` and [`check_fillable`] beforehand (a
/// mostly blank one by [`SPARSE_MAX_PIXELS`]).
fn limits(opts: &DecodeOptions) -> image::Limits {
let mut l = image::Limits::default();
l.max_alloc = Some(opts.max_pixels.saturating_mul(4));
l
}

/// The largest canvas allowed that the file's pixel data leaves mostly blank: a GIF screen larger
/// than its first frame, or an RLE BMP whose runs can't cover it. Its decode still allocates the
/// whole canvas (16 MB at this size), so it is held well below `max_pixels`.
const SPARSE_MAX_PIXELS: u64 = 4_000_000;

/// Refuses a canvas larger than the file's bytes can describe, before the decoder allocates it
/// (issue #2553). Uncompressed BMP rows are stored in full at 1 bit per pixel or more, so the file
/// holds at least one byte per 8 pixels. A GIF frame's pixels come from its LZW data alone; a code
/// expands to at most 4096 pixels and takes 12 bits once the table holds that many (fewer bits only
/// while its strings are shorter), so at most 2731 pixels per byte. That bounds the first frame's
/// own size; the screen around it may be larger, and is blank there.
///
/// An RLE BMP has no such bound, since an end-of-bitmap code or a delta leaves the rest blank. Its
/// runs cover at most 255 pixels per 2 bytes, so a canvas beyond 128 pixels per byte is mostly
/// blank. Mostly blank canvases are limited to [`SPARSE_MAX_PIXELS`].
fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> {
let area = |w: u32, h: u32| u64::from(w).saturating_mul(u64::from(h));
let unfillable = |what: &str, w: u32, h: u32, len: usize| {
Error::Malformed(format, format!("a {w} × {h} {what} is far larger than its {len} bytes of pixel data can hold"))
};
let canvas = area(w, h);
// the pixels the file's data can cover
let covered = match format {
Format::Gif => {
let (fw, fh, len) = gif_first_frame(bytes).unwrap_or((w, h, bytes.len()));
if area(fw, fh) > (len as u64).saturating_mul(2_731) {
return Err(unfillable("frame", fw, fh, len));
}
area(fw, fh)
}
Format::Bmp if bmp_is_rle(bytes) => (bytes.len() as u64).saturating_mul(128),
_ => {
if canvas > (bytes.len() as u64).saturating_mul(8) {
return Err(unfillable("canvas", w, h, bytes.len()));
}
canvas
}
};
if canvas > covered && canvas > SPARSE_MAX_PIXELS {
return Err(Error::Malformed(
format,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
format!(
"a {w} × {h} canvas is mostly blank (its pixel data covers at most {covered} pixels), and such pictures are limited to {SPARSE_MAX_PIXELS} pixels"
),
));
}
Ok(())
}

/// Whether a BMP's pixels are run-length encoded (RLE8 or RLE4, in a header of 40 bytes or more).
fn bmp_is_rle(bytes: &[u8]) -> bool {
let u32_at = |i: usize| bytes.get(i..i + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
u32_at(14).is_some_and(|size| size >= 40) && matches!(u32_at(30), Some(1 | 2))
}

/// A GIF's first frame: its width and height, and the bytes of LZW data present (its palettes,
/// comments and other extensions describe no pixels). `None` when the blocks before the frame
/// can't be walked.
fn gif_first_frame(bytes: &[u8]) -> Option<(u32, u32, usize)> {
let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 };
let mut pos = 13 + table(*bytes.get(10)?);
loop {
match *bytes.get(pos)? {
// extension: introducer, label, sub-blocks
0x21 => pos = sub_blocks(bytes, pos.saturating_add(2)).1,
// image descriptor (separator, left, top, width, height, flags), local colour table,
// LZW minimum code size, data sub-blocks
0x2C => {
let (fw, fh) = (u16_at(pos.saturating_add(5))?, u16_at(pos.saturating_add(7))?);
let start = pos.saturating_add(10).saturating_add(table(*bytes.get(pos.saturating_add(9))?)).saturating_add(1);
return Some((u32::from(fw), u32::from(fh), sub_blocks(bytes, start).0));
}
_ => return None,
}
}
}

/// The GIF sub-blocks starting at `pos`: the data bytes present, and the position after them.
fn sub_blocks(bytes: &[u8], mut pos: usize) -> (usize, usize) {
let mut data = 0usize;
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
if n == 0 {
return (data, start);
}
let end = start.saturating_add(usize::from(n));
data = data.saturating_add(end.min(bytes.len()).saturating_sub(start));
pos = end;
}
(data, pos)
}

pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result<Decoded> {
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let cursor = std::io::Cursor::new(bytes);
Expand All @@ -12,13 +142,17 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
let mut d = image::codecs::gif::GifDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
Format::Bmp => {
let mut d = image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
Expand Down
162 changes: 162 additions & 0 deletions crates/codecs/tests/it/fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,168 @@ fn thumbnail_rejects_huge_gif_before_allocating_source_pixels() {
assert!(matches!(result, Err(Error::TooLarge(42_127, 16_304))), "{result:?}");
}

/// A GIF of a few dozen bytes: a `w` × `h` logical screen and one empty frame of that size.
fn tiny_gif(w: u16, h: u16) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend([0, 0, 0, b',', 0, 0, 0, 0]);
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend([0, 2, 0, b';']);
b
}

/// A 54-byte uncompressed 24-bit BMP header declaring `w` × `h` and no pixel data.
fn tiny_bmp(w: i32, h: i32) -> Vec<u8> {
let mut b = b"BM".to_vec();
b.extend(54u32.to_le_bytes());
b.extend(0u32.to_le_bytes());
b.extend(54u32.to_le_bytes());
b.extend(40u32.to_le_bytes());
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend(1u16.to_le_bytes());
b.extend(24u16.to_le_bytes());
b.extend([0u8; 24]);
b
}

/// Issue #2553: the import probe had no header reader for GIF or BMP and decoded them in full, so
/// a tiny file declaring a canvas just under the 1-gigapixel limit allocated ~4.3 GB (an abort, not
/// an error, when it failed). Both the probe and a decode now refuse a canvas the file's bytes
/// can't fill, before the decoder allocates it.
#[test]
fn tiny_gif_and_bmp_declaring_a_gigapixel_canvas_are_refused_before_allocating() {
for (name, bytes) in [("gif", tiny_gif(32_767, 32_767)), ("bmp", tiny_bmp(32_000, 32_000))] {
assert!(bytes.len() < 64, "{name}: {} bytes", bytes.len());
let header = read_header(&bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{name}: {header:?}");
let decoded = decode(&bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{name}: {:?}", decoded.err());
}
}

/// Above 4 MP the probe reads GIF and BMP sizes from the header without decoding; the size agrees
/// with a full decode.
#[test]
fn large_gif_and_bmp_sizes_come_from_the_header() {
let (w, h) = (2_100u32, 2_000u32);
let rgb = vec![90u8; (w * h * 3) as usize];
let mut bmp = Vec::new();
image::codecs::bmp::BmpEncoder::new(&mut bmp).encode(&rgb, w, h, image::ExtendedColorType::Rgb8).unwrap();
let mut gif = Vec::new();
let frame = image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]));
image::codecs::gif::GifEncoder::new(&mut gif).encode_frame(image::Frame::new(frame)).unwrap();
for (name, bytes) in [("bmp", bmp), ("gif", gif)] {
let header = read_header(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!((header.width, header.height, header.orientation), (w, h, 1), "{name}");
let d = decode(&bytes, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (w, h), "{name}");
}
}

/// A 64-byte RLE8 BMP declaring `w` × `h` whose pixels are one end-of-bitmap code: all blank.
fn rle_bmp_ending_at_once(w: i32, h: i32) -> Vec<u8> {
let mut b = b"BM".to_vec();
b.extend(64u32.to_le_bytes()); // file size
b.extend(0u32.to_le_bytes());
b.extend(62u32.to_le_bytes()); // pixel data offset: 14 + 40 + 2 palette entries
b.extend(40u32.to_le_bytes());
b.extend(w.to_le_bytes());
b.extend(h.to_le_bytes());
b.extend(1u16.to_le_bytes());
b.extend(8u16.to_le_bytes());
b.extend(1u32.to_le_bytes()); // BI_RLE8
b.extend(2u32.to_le_bytes()); // pixel data size
b.extend([0u8; 8]);
b.extend(2u32.to_le_bytes()); // colours used
b.extend(0u32.to_le_bytes());
b.extend([0, 0, 0, 0, 255, 255, 255, 0]);
b.extend([0, 1]); // end of bitmap
assert_eq!(b.len(), 64);
b
}

/// An RLE8 BMP may end its pixels with an end-of-bitmap code that leaves the rest blank, so a file
/// of a few dozen bytes is a valid picture: up to 4 MP it opens, at its declared size.
#[test]
fn an_rle_bmp_that_ends_early_still_opens() {
let (w, h) = (2_000i32, 2_000i32);
let b = rle_bmp_ending_at_once(w, h);
let header = read_header(&b).unwrap();
assert_eq!((header.width, header.height), (w as u32, h as u32));
let d = decode(&b, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (w as u32, h as u32));
}

/// A mostly blank canvas still costs its full size to decode, so a tiny RLE BMP can't claim a
/// gigapixel one: canvases the file's runs can't cover are limited to 4 MP, refused before the
/// decoder allocates them.
#[test]
fn a_tiny_rle_bmp_declaring_a_gigapixel_canvas_is_refused_before_allocating() {
for (w, h) in [(2_001, 2_000), (32_000, 32_000)] {
let b = rle_bmp_ending_at_once(w, h);
let header = read_header(&b);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{w} × {h}: {header:?}");
let decoded = decode(&b, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{w} × {h}: {:?}", decoded.err());
}
}

/// A `sw` × `sh` GIF screen whose first frame is one pixel (black, from a 2-colour palette).
fn gif_with_one_pixel_frame(sw: u16, sh: u16) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
b.extend(sw.to_le_bytes());
b.extend(sh.to_le_bytes());
b.extend([0x80, 0, 0]); // global colour table of 2 entries
b.extend([0, 0, 0, 255, 255, 255]);
b.extend([b',', 0, 0, 0, 0, 1, 0, 1, 0, 0]); // a 1 × 1 frame at the origin
b.extend([2, 2, 0x44, 0x01, 0]); // LZW: clear, index 0, end
b.push(b';');
b
}

/// Density is judged on the first frame's own size, not the screen's: a valid GIF with a small first
/// frame on a larger screen opens, at the screen's size (up to 4 MP, as for other mostly blank
/// canvases).
#[test]
fn a_gif_with_a_small_first_frame_on_a_larger_screen_opens() {
let b = gif_with_one_pixel_frame(2_000, 2_000);
let header = read_header(&b).unwrap();
assert_eq!((header.width, header.height), (2_000, 2_000));
let d = decode(&b, DecodeOptions::fit(64, 64)).unwrap();
assert_eq!((d.source_width, d.source_height), (2_000, 2_000));
}

#[test]
fn a_gif_whose_one_pixel_frame_sits_on_a_gigapixel_screen_is_refused_before_allocating() {
let b = gif_with_one_pixel_frame(32_767, 32_767);
let header = read_header(&b);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{header:?}");
let decoded = decode(&b, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("mostly blank")), "{:?}", decoded.err());
}

/// A GIF's comments and other extensions describe no pixels, so padding a tiny GIF with 100 KB of
/// comment doesn't let it claim a gigapixel canvas: only the frame's LZW data counts.
#[test]
fn a_gif_padded_with_comments_still_cannot_claim_a_gigapixel_canvas() {
let mut bytes = tiny_gif(32_767, 32_767);
let mut comment = vec![0x21, 0xFE];
for _ in 0..400 {
comment.push(255);
comment.extend([b'x'; 255]);
}
comment.push(0);
bytes.splice(13..13, comment);
assert!(bytes.len() > 100_000);
let header = read_header(&bytes);
assert!(matches!(&header, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{header:?}");
let decoded = decode(&bytes, DecodeOptions::default());
assert!(matches!(&decoded, Err(Error::Malformed(_, m)) if m.contains("can hold")), "{:?}", decoded.err());
}

#[test]
fn thumbnail_respects_configured_source_pixel_limit() {
let image = Rgba8::from_fn(3, 2, |_, _| [40, 80, 120, 255]);
Expand Down
9 changes: 9 additions & 0 deletions docs/whats-new.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

## 2026-10-23

### A damaged GIF or BMP can no longer crash an import
- A GIF or BMP whose header claims an enormous picture (a file of a few dozen bytes can claim a billion pixels) is
now refused with an error when importing or opening it (issue #2553). Before, LightCraft set aside memory for the
whole picture, several gigabytes, and could close without warning, losing unsaved work. At import, a GIF or BMP
picture larger than 4 megapixels now has its size read from the header instead of being decoded; smaller ones are
still decoded, so a damaged file is caught then. A picture that is mostly blank (a run-length-encoded BMP that ends
early, or a GIF whose first frame is smaller than the picture) still opens up to 4 megapixels; a larger one is
refused, because opening it would still set aside memory for the whole picture.

### Tab leaves the name field in New Album, New Smart Album and the name prompts
- In New Album, New Smart Album, Save Metadata Preset and the other dialogs with one name field, the field has the
keyboard focus when the dialog opens, and Tab now moves on to the check box, Cancel and OK (Shift+Tab goes back).
Expand Down
Loading