Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

LR-IMP-FORMATS: an RLE BMP that ends early opens; a GIF's bound counts only its LZW data (#2553)

insideTheFluxb55daa91da46
diff --git a/crates/codecs/src/other.rs b/crates/codecs/src/other.rs
index f99bd5f17..43942994f 100644
--- a/crates/codecs/src/other.rs
+++ b/crates/codecs/src/other.rs
@@ -23,7 +23,7 @@ pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
if w == 0 || h == 0 {
return Err(Error::Malformed(format, "zero dimension".into()));
}
- check_fillable(format, bytes.len(), w, h)?;
+ 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));
@@ -31,29 +31,71 @@ pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
Ok((w, h, 1))
}
-/// The decoder's allocation limit: the RGBA buffer of the largest image `opts` allows, so an
-/// oversized canvas is an error from the decoder instead of an allocation attempt.
+/// 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.
fn limits(opts: &DecodeOptions) -> image::Limits {
let mut l = image::Limits::default();
l.max_alloc = Some(opts.max_pixels.saturating_mul(4));
l
}
-/// The most pixels `len` bytes of pixel data can describe: BMP stores at least 1 bit per pixel and
-/// its RLE at most 255 pixels per 2-byte run (128 per byte covers both); a GIF LZW code takes at
-/// least 3 bits and expands to at most 4096 pixels (11,000 per byte). The decoders allocate the
-/// whole canvas before reading any pixel data, so a header declaring far more than the file can
-/// fill is refused first (issue #2553).
-fn fillable(format: Format, len: usize) -> u64 {
- let per_byte = if format == Format::Gif { 11_000 } else { 128 };
- (len as u64).saturating_mul(per_byte)
+/// 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. An RLE BMP has no such bound: an end-of-bitmap code leaves
+/// the rest of the picture blank, so it is left to `check_size`. 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.
+fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> {
+ let (len, per_byte) = match format {
+ Format::Bmp if bmp_is_rle(bytes) => return Ok(()),
+ Format::Gif => (gif_image_data_len(bytes).unwrap_or(bytes.len()), 2_731),
+ _ => (bytes.len(), 8),
+ };
+ if u64::from(w).saturating_mul(u64::from(h)) > (len as u64).saturating_mul(per_byte) {
+ return Err(Error::Malformed(format, format!("a {w} × {h} canvas is far larger than its {len} bytes of pixel data can hold")));
+ }
+ Ok(())
}
-fn check_fillable(format: Format, len: usize, w: u32, h: u32) -> Result<()> {
- if u64::from(w).saturating_mul(u64::from(h)) > fillable(format, len) {
- return Err(Error::Malformed(format, format!("a {w} × {h} canvas is far larger than its {len} bytes can hold")));
+/// 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))
+}
+
+/// The bytes of LZW data present in a GIF's first frame; its palettes, comments and other
+/// extensions describe no pixels. `None` when the blocks before the frame can't be walked.
+fn gif_image_data_len(bytes: &[u8]) -> Option<usize> {
+ 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 (10 bytes), local colour table, LZW minimum code size, data sub-blocks
+ 0x2C => {
+ let start = pos.saturating_add(10).saturating_add(table(*bytes.get(pos.saturating_add(9))?)).saturating_add(1);
+ return Some(sub_blocks(bytes, start).0);
+ }
+ _ => return None,
+ }
}
- Ok(())
+}
+
+/// 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> {
@@ -64,7 +106,7 @@ 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.len(), w, h)?;
+ 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)
@@ -73,7 +115,7 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
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.len(), w, h)?;
+ 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)
diff --git a/crates/codecs/tests/fuzz.rs b/crates/codecs/tests/fuzz.rs
index d52f80ee0..67a5b59c2 100644
--- a/crates/codecs/tests/fuzz.rs
+++ b/crates/codecs/tests/fuzz.rs
@@ -135,6 +135,53 @@ fn large_gif_and_bmp_sizes_come_from_the_header() {
}
}
+/// 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 6 MP picture: it opens, at its declared size.
+#[test]
+fn an_rle_bmp_that_ends_early_still_opens() {
+ let (w, h) = (3_000i32, 2_000i32);
+ 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);
+ 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 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]);
diff --git a/docs/whats-new.md b/docs/whats-new.md
index cba458a75..0f069ff14 100644
--- a/docs/whats-new.md
+++ b/docs/whats-new.md
@@ -5,8 +5,10 @@
### 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. Large GIF and BMP files
- are also measured from their header at import instead of being decoded.
+ 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 run-length-encoded BMP that ends early, leaving the rest of the
+ picture blank, still opens.
## 2026-10-21