From b2b318b2016fe42fc2f308b4ba2f09faeb9ed544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:39:04 +0300 Subject: [PATCH] U20: ec-image drop tests/fuzz.rs and its tracking-allocator dev-dependency (allocation counter for fuzz tests only; regressions and differential tests stay) --- Cargo.lock | 1 - crates/ec-image/Cargo.toml | 1 - crates/ec-image/tests/fuzz.rs | 774 ---------------------------------- 3 files changed, 776 deletions(-) delete mode 100644 crates/ec-image/tests/fuzz.rs diff --git a/Cargo.lock b/Cargo.lock index 14b61940..d52dc450 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -608,7 +608,6 @@ dependencies = [ "ec-inflate", "ec-testkit", "image 0.25.10 (registry+https://github.com/rust-lang/crates.io-index)", - "tracking-allocator", ] [[package]] diff --git a/crates/ec-image/Cargo.toml b/crates/ec-image/Cargo.toml index bdb291f5..91eca6b5 100644 --- a/crates/ec-image/Cargo.toml +++ b/crates/ec-image/Cargo.toml @@ -16,4 +16,3 @@ ec-testkit.workspace = true # bytes both ways and compares pixels. Running it is the point; nothing is # copied from it. image = "0.25.10" -tracking-allocator = "0.4.0" diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs deleted file mode 100644 index b8666eb0..00000000 --- a/crates/ec-image/tests/fuzz.rs +++ /dev/null @@ -1,774 +0,0 @@ -//! Malformed input never panics, never hangs and never allocates without -//! bound. -//! -//! Ten thousand mutations per format, from a fixed seed so a failure is -//! reproducible: bit flips, truncations, byte injections and pure noise behind -//! each format's signature. Every one of them must come back as `Ok` or as an -//! `Err` — a decoder reached by a file picker is reached by every broken file -//! on the disk. - -use std::alloc::System; -use std::cell::Cell; -use std::sync::Once; - -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; -use std::path::{Path, PathBuf}; - -/// Counting allocator: the "refused without doing unbounded work" tests -/// below bound that work by *bytes allocated*, not by wall time. A clock is -/// a machine-dependent proxy for exactly the thing those tests care about -- -/// it measures the host's memcpy bandwidth, not the decoder's behaviour -- -/// and it was measured failing that way: the same refused WebP decode takes -/// 0.75-0.89 s on this desktop host and 3.89 s on a server, a 5x spread with -/// byte-identical decoder work, which is what reddened a 2 s ceiling. -/// Lives in the test binary only; the shipped crate has no allocator games. -/// -/// The tally is per-thread, not global: `cargo test` runs these tests in -/// parallel, so a shared counter sums concurrent decodes together and -/// reports work none of them did. -struct CountingAlloc; - -std::thread_local! { - static ALLOC_BYTES: Cell = const { Cell::new(0) }; -} - -fn count_alloc(size: usize) { - let _ = ALLOC_BYTES.try_with(|b| b.set(b.get() + size as u64)); -} - -impl AllocationTracker for CountingAlloc { - fn allocated(&self, _addr: usize, object_size: usize, _wrapped: usize, _g: AllocationGroupId) { - count_alloc(object_size); - } - fn deallocated( - &self, - _addr: usize, - _object_size: usize, - _wrapped: usize, - _source: AllocationGroupId, - _current: AllocationGroupId, - ) { - } -} - -#[global_allocator] -static ALLOC: Allocator = Allocator::system(); - -/// Installs the tracker once. Realloc reaches the tracker as an allocation of -/// the new size, which is the accounting this file has always used. -fn install_counter() { - static ONCE: Once = Once::new(); - ONCE.call_once(|| { - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); - AllocationRegistry::enable_tracking(); - }); -} - -/// Runs `f` on this thread and returns its value together with every byte -/// that thread allocated while it ran. That count is the decoder's own -/// work, independent of how fast the host is at moving those bytes around. -fn counting_allocations(f: impl FnOnce() -> T) -> (T, u64) { - install_counter(); - ALLOC_BYTES.with(|b| b.set(0)); - let out = f(); - (out, ALLOC_BYTES.with(Cell::get)) -} - -/// Serializes the tests that allocate up to the decoder's whole budget. -/// -/// Those tests each decode a near-limit canvas, so run together they need -/// several GiB at once and the per-scope memory cap (`scripts/memguard-runner.sh`) -/// SIGKILLs the test binary. One at a time they fit. The lock covers only -/// those tests; the cheap ones stay parallel. A poisoned lock (a failed -/// assertion in another heavy test) is recovered, so one failure does not -/// cascade into spurious failures in the rest. -/// -/// The counting allocator needs no lock for its numbers: its tally is -/// per-thread, so serializing does not change what any test measures. -static HEAVY: std::sync::Mutex<()> = std::sync::Mutex::new(()); - -fn heavy() -> std::sync::MutexGuard<'static, ()> { - HEAVY.lock().unwrap_or_else(|e| e.into_inner()) -} - -/// Limits for the tests that run up to the total budget: 1 GiB total and 512 MiB per buffer. -/// -/// The default total (4 GiB) would need about 4 GiB resident before the refusal, which is past -/// the 3500M memory cap on the lane servers. These limits keep the same behaviour (a total -/// budget, a per-buffer cap) at a size the cap can hold. -/// -/// Also used by the mutation sweeps, which test robustness rather than the default limit values. -/// -/// The tests' canvases are 4000x2000 RGBA (32,000,000 bytes), which does not divide the 1 GiB -/// total evenly. A canvas that did (say 4096x2048, 2^25 bytes) lets the last clone that fits -/// land exactly on the budget, and the test's own small allocations then push the measured -/// total a few kilobytes past it. -fn budget_limits() -> ec_image::Limits { - ec_image::Limits { - max_total_alloc: 1 << 30, - max_alloc: 1 << 29, - ..ec_image::Limits::default() - } -} - -const ROUNDS: usize = 10_000; - -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/stills") -} - -/// xorshift64*, so every run mutates the same way. -struct Rng(u64); - -impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - - fn below(&mut self, bound: usize) -> usize { - (self.next() % bound.max(1) as u64) as usize - } -} - -/// One mutated copy of `seed`: a few bit flips, a truncation, or an injection. -/// -/// `head` bounds where the flips land. Aiming them at the first few dozen -/// bytes is what actually reaches the geometry and colour-type paths: spread -/// over a whole file they nearly all land in the compressed data and stop at -/// the first integrity check. -fn mutate(rng: &mut Rng, seed: &[u8], head: Option) -> Vec { - let mut data = seed.to_vec(); - let region = head.unwrap_or(data.len()).min(data.len()); - match rng.below(4) { - 0 => { - for _ in 0..1 + rng.below(8) { - let at = rng.below(region); - data[at] ^= 1 << rng.below(8); - } - } - 1 => data.truncate(rng.below(data.len())), - 2 => { - for _ in 0..1 + rng.below(16) { - let at = rng.below(region); - data[at] = (rng.next() & 0xff) as u8; - } - } - _ => { - // Keep the signature, replace the body with noise: this is the - // shape that exercises header fields hardest. - let keep = 12.min(data.len()); - data.truncate(keep); - for _ in 0..rng.below(400) { - data.push((rng.next() & 0xff) as u8); - } - } - } - data -} - -/// Recompute every chunk CRC of a mutated PNG. -/// -/// Without this the checksum catches every mutation at the door and the -/// decoder proper is never fuzzed at all — the sweep would prove only that -/// CRC-32 works. -fn repair_png_crcs(data: &mut [u8]) { - let mut at = 8usize; - while at + 12 <= data.len() { - let len = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize; - if len > data.len() || at + 12 + len > data.len() { - return; - } - let crc = crc32(&data[at + 4..at + 8 + len]); - data[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes()); - at += 12 + len; - } -} - -fn sweep(name: &str, seed_file: &str) { - // Mutated headers can claim canvases up to the budget, so a sweep is heavy too. - let _heavy = heavy(); - let seed = std::fs::read(fixtures().join(seed_file)).unwrap(); - let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64); - let mut decoded = 0usize; - for round in 0..ROUNDS { - // Half the rounds aim at the header, half at the whole file. - let head = if round % 2 == 0 { Some(48) } else { None }; - let mut data = mutate(&mut rng, &seed, head); - if seed_file.ends_with(".png") { - repair_png_crcs(&mut data); - } - // The call is the assertion: a panic here fails the test with the - // round number, and the round number plus the fixed seed reproduces it. - if let Ok(image) = ec_image::decode_with_limits(&data, budget_limits()) { - decoded += 1; - let pixels = image.to_rgba8(); - assert_eq!( - pixels.len(), - (image.width as usize) * (image.height as usize) * 4, - "{name} round {round}: buffer does not match the dimensions" - ); - } - // Header-only parsing must survive the same input. - let _ = ec_image::info(&data); - } - eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded"); -} - -/// Single-seed sweeps: (old test name, format label, seed fixture). Each was a #[test] -/// of its own; they run as one table so the mutation loop is written once. -const SWEEPS: &[(&str, &str, &str)] = &[ - ("png_survives_mutation", "png", "tiny.png"), - ("jpeg_survives_mutation", "jpeg", "tiny.jpg"), - ("webp_lossy_survives_mutation", "webp-lossy", "tiny-lossy.webp"), - ("webp_lossless_survives_mutation", "webp-lossless", "tiny-lossless.webp"), - ("gif_survives_mutation", "gif", "tiny.gif"), - // BMP sizes three separate things from header fields -- a palette, a row - // stride and, for the run-length compressions, a decoded row buffer -- so a - // mutation can put any two of them in disagreement. - ("bmp_survives_mutation", "bmp", "tiny.bmp"), - // The run-length path is the one that writes at a position the *file* chooses - // (delta codes move the cursor), so it gets its own seed. - ("a_run_length_bmp_survives_mutation", "bmp-rle", "rle8.bmp"), - // TIFF is a directory of offsets into itself: a mutation can point a strip, - // a palette or the directory's own continuation anywhere in the file. - ("tiff_survives_mutation", "tiff", "tiny.tiff"), - // The compressed, predicted path decodes into a row buffer whose length comes - // from tags the mutation is free to disagree about, so it gets its own seed. - ("a_compressed_tiff_survives_mutation", "tiff-lzw", "rgb8-lzw-pred.tiff"), -]; - -#[test] -fn single_seed_sweeps_survive_mutation() { - // Scoped threads, as the separate #[test]s ran in parallel. `heavy()` still serializes the sweeps. - let failures: Vec<&str> = std::thread::scope(|s| { - let handles: Vec<_> = SWEEPS - .iter() - .map(|&(test, name, seed)| (test, s.spawn(move || sweep(name, seed)))) - .collect(); - handles - .into_iter() - .filter_map(|(test, h)| h.join().is_err().then_some(test)) - .collect() - }); - assert!(failures.is_empty(), "failed cases: {failures:?}"); -} - -/// The animation path has its own frame loop, its own canvas and its own -/// disposal state machine, none of which `decode` reaches past frame one. -#[test] -fn a_gif_animation_survives_mutation() { - let seed = std::fs::read(fixtures().join("animated.gif")).unwrap(); - let _heavy = heavy(); - let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37); - let mut decoded = 0usize; - for round in 0..ROUNDS { - let head = if round % 2 == 0 { Some(48) } else { None }; - let data = mutate(&mut rng, &seed, head); - if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) { - decoded += 1; - for frame in &frames { - let image = &frame.image; - assert_eq!( - image.to_rgba8().len(), - (image.width as usize) * (image.height as usize) * 4, - "gif-animation round {round}: buffer does not match the dimensions" - ); - } - } - } - eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded"); -} - -/// The WebP animation path parses its own ANMF headers and composites onto a -/// canvas sized by a different chunk, so a mutation can make the two disagree. -#[test] -fn an_animated_webp_survives_mutation() { - let seed = std::fs::read(fixtures().join("anim-alpha.webp")).unwrap(); - let _heavy = heavy(); - let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed); - let mut decoded = 0usize; - for round in 0..ROUNDS { - let head = if round % 2 == 0 { Some(48) } else { None }; - let data = mutate(&mut rng, &seed, head); - if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) { - decoded += 1; - for frame in &frames { - let image = &frame.image; - assert_eq!( - image.to_rgba8().len(), - (image.width as usize) * (image.height as usize) * 4, - "webp-animation round {round}: buffer does not match the dimensions" - ); - } - } - } - eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded"); -} - -#[test] -fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { - let signatures: [&[u8]; 6] = [ - &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], - &[0xff, 0xd8, 0xff, 0xe0], - b"RIFF\x40\x00\x00\x00WEBPVP8 ", - b"GIF89a", - // A TIFF header whose directory offset is inside the header itself. - b"II\x2a\x00\x04\x00\x00\x00", - // "BM" alone is two bytes anything could start with, so the guess also - // asks the file header to agree with itself: this prefix declares a - // 40-byte info header and pixels at 54, which is what makes the bytes - // behind it reach the decoder at all. - b"BM\x00\x10\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00", - ]; - let _heavy = heavy(); - let mut rng = Rng(0x9e37_79b9_7f4a_7c15); - for signature in signatures { - for _ in 0..ROUNDS / 4 { - let mut data = signature.to_vec(); - for _ in 0..rng.below(200) { - data.push((rng.next() & 0xff) as u8); - } - let _ = ec_image::decode_with_limits(&data, budget_limits()); - let _ = ec_image::info(&data); - } - } -} - -#[test] -fn a_header_asking_for_more_pixels_than_the_limit_is_refused() { - // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse - // it before any buffer is sized from those numbers. - let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; - let mut ihdr = Vec::new(); - ihdr.extend_from_slice(&65535u32.to_be_bytes()); - ihdr.extend_from_slice(&65535u32.to_be_bytes()); - ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); - png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes()); - let start = png.len(); - png.extend_from_slice(b"IHDR"); - png.extend_from_slice(&ihdr); - let crc = crc32(&png[start..]); - png.extend_from_slice(&crc.to_be_bytes()); - let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit"); - assert!(format!("{err}").contains("limit"), "{err}"); -} - -/// LSB-first bit packer, matching how every decoder in this crate reads a -/// GIF LZW or VP8L bitstream: used to hand-craft the smallest possible valid -/// compressed payload for the budget tests below. -struct BitWriter { - buffer: u64, - bits: u8, - out: Vec, -} - -impl BitWriter { - fn new() -> Self { - BitWriter { - buffer: 0, - bits: 0, - out: Vec::new(), - } - } - - fn push(&mut self, value: u16, width: u8) { - self.buffer |= u64::from(value) << self.bits; - self.bits += width; - while self.bits >= 8 { - self.out.push((self.buffer & 0xff) as u8); - self.buffer >>= 8; - self.bits -= 8; - } - } - - fn finish(mut self) -> Vec { - if self.bits > 0 { - self.out.push((self.buffer & 0xff) as u8); - } - self.out - } -} - -/// A minimal GIF: no global colour table, one 0x2C image descriptor with a -/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end), -/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen; -/// the frame itself is always 1x1 so its own indices buffer is trivial — -/// what grows per frame is the *composited canvas* `composite` clones. -fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec { - let mut w = BitWriter::new(); - w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2) - w.push(0, 3); // colour index 0, literal - w.push(5, 3); // end code - let lzw = w.finish(); - - let mut data = Vec::new(); - data.extend_from_slice(b"GIF87a"); - data.extend_from_slice(&canvas_w.to_le_bytes()); - data.extend_from_slice(&canvas_h.to_le_bytes()); - data.push(0x00); // no global colour table - data.push(0); - data.push(0); - for _ in 0..frames { - data.push(0x2C); - data.extend_from_slice(&0u16.to_le_bytes()); // left - data.extend_from_slice(&0u16.to_le_bytes()); // top - data.extend_from_slice(&1u16.to_le_bytes()); // width - data.extend_from_slice(&1u16.to_le_bytes()); // height - data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours - data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT - data.push(2); // min code size - data.push(lzw.len() as u8); - data.extend_from_slice(&lzw); - data.push(0); // sub-block terminator - } - data.push(0x3B); // trailer - data -} - -#[test] -fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { - // A single 0x2C image descriptor declaring a 60000x60000 frame: the - // frame's own rectangle is a header field like the canvas is, and must - // be refused before it sizes the indices buffer below it. - let mut data = Vec::new(); - data.extend_from_slice(b"GIF87a"); - data.extend_from_slice(&4u16.to_le_bytes()); - data.extend_from_slice(&4u16.to_le_bytes()); - data.push(0x00); - data.push(0); - data.push(0); - data.push(0x2C); - data.extend_from_slice(&0u16.to_le_bytes()); - data.extend_from_slice(&0u16.to_le_bytes()); - data.extend_from_slice(&60000u16.to_le_bytes()); - data.extend_from_slice(&60000u16.to_le_bytes()); - data.push(0x00); - - // Bounded by bytes, not by a clock: this refusal happens before the - // frame sizes anything at all, so the whole decode is a few hundred - // bytes of header parsing (measured: 421 B in 2.6 us) whatever the host's - // speed. The old 100 ms clock was a machine-dependent proxy for that. - let (err, allocated) = counting_allocations(|| { - ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit") - }); - assert!(format!("{err}").contains("limit"), "{err}"); - assert!( - allocated <= 64 * 1024, - "a header-only refusal allocated {allocated} bytes; it must refuse before sizing the frame" - ); -} - -#[test] -fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { - let _heavy = heavy(); - // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but - // `composite` clones the *whole* canvas onto the result once per frame. - // A canvas near the single-buffer limit, repeated a few dozen times, - // must be caught by the decode-wide budget even though no single frame - // or single buffer ever looks large by itself. - let data = one_pixel_gif(4000, 2000, 64); - // A few real canvas clones run before the budget catches up (the budget - // is spent per frame, so it can't refuse before at least one clone), so - // this bounds "the decoder's own total budget, not a byte more", not "no - // allocation at all". Bytes, not a clock -- see the counting allocator - // above. - let limits = budget_limits(); - let budget = limits.max_total_alloc as u64; - let (err, allocated) = counting_allocations(|| { - ec_image::decode_animation_with_limits(&data, limits) - .expect_err("64 clones of a near-limit canvas is past the total budget") - }); - assert!(format!("{err}").contains("limit"), "{err}"); - assert!( - allocated <= budget, - "refused decode allocated {allocated} bytes, past the {budget}-byte total budget" - ); - - // Size-relative, and the half that pins the guard: 64x the frames in the - // file must not buy 64x the work. A budget spent per *input* frame, or - // after the clone instead of before it, refuses later or not at all as - // the frame count grows. - let bomb = one_pixel_gif(4000, 2000, 4096); - let (err, allocated) = counting_allocations(|| { - ec_image::decode_animation_with_limits(&bomb, limits) - .expect_err("4096 clones of a near-limit canvas is past the total budget") - }); - assert!(format!("{err}").contains("limit"), "{err}"); - assert!( - allocated <= budget, - "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" - ); -} - -#[test] -fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() { - let _heavy = heavy(); - // The other side of the same budget: a handful of frames over a large - // canvas is exactly what a real animation looks like, and must not be - // refused just because the guard above exists. - let data = one_pixel_gif(4000, 4000, 3); - let frames = ec_image::decode_animation_with_limits(&data, budget_limits()) - .expect("well within every limit"); - assert_eq!(frames.len(), 3); -} - -/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks, -/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a -/// bitstream header plus one pixel, no transforms, no colour cache). -fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec { - // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0, - // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the - // image data: no colour cache, no meta prefix, one simple prefix code - // per channel (colour index 0 for all four), then the single pixel. - let mut w = BitWriter::new(); - w.push(0, 14); // width - 1 - w.push(0, 14); // height - 1 - w.push(0, 1); // alpha_is_used - w.push(0, 3); // version - w.push(0, 1); // no transform - w.push(0, 1); // no colour cache - w.push(0, 1); // no meta prefix - for _ in 0..5 { - // green/red/blue/alpha/distance, in that order: a simple code, one - // symbol, value 0. - w.push(1, 1); // simple code - w.push(0, 1); // one symbol - w.push(0, 1); // symbol is not a literal byte read as 8 bits - w.push(0, 1); // symbol0 = 0 - } - let vp8l_bits = w.finish(); - let mut vp8l = vec![0x2f]; - vp8l.extend_from_slice(&vp8l_bits); - if vp8l.len() % 2 == 1 { - vp8l.push(0); - } - - fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec { - let mut c = Vec::new(); - c.extend_from_slice(tag); - c.extend_from_slice(&(body.len() as u32).to_le_bytes()); - c.extend_from_slice(body); - if body.len() % 2 == 1 { - c.push(0); - } - c - } - - let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation" - let off24 = |v: u32| v.to_le_bytes()[..3].to_vec(); - let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec(); - vp8x.extend_from_slice(&dim24(canvas_w)); - vp8x.extend_from_slice(&dim24(canvas_h)); - let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour - anim.extend_from_slice(&0u16.to_le_bytes()); // loop count - - let mut anmf_body = Vec::new(); - anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2) - anmf_body.extend_from_slice(&off24(0)); // y offset - anmf_body.extend_from_slice(&dim24(1)); // width - 1 - anmf_body.extend_from_slice(&dim24(1)); // height - 1 - anmf_body.extend_from_slice(&off24(1)); // duration - anmf_body.push(0x00); // reserved/blend/dispose - anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l)); - - let mut payload = Vec::new(); - payload.extend_from_slice(&chunk(b"VP8X", &vp8x)); - payload.extend_from_slice(&chunk(b"ANIM", &anim)); - for _ in 0..frames { - payload.extend_from_slice(&chunk(b"ANMF", &anmf_body)); - } - - let mut data = Vec::new(); - data.extend_from_slice(b"RIFF"); - data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes()); - data.extend_from_slice(b"WEBP"); - data.extend_from_slice(&payload); - data -} - -#[test] -fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { - let _heavy = heavy(); - // The WebP analogue of the GIF test above: `decode_frames` clones the - // whole composited canvas into the result once per ANMF chunk. - // - // The bound here is *bytes*, not a clock. What this protects against is - // a guard that stops refusing and lets the clone multiplier run -- 64 - // frames over this canvas is 64 GiB of compositing -- and a clock cannot - // express that: it measures the host's memcpy bandwidth, measured at - // 0.75-0.89 s on this desktop host against 3.89 s on a server for - // byte-identical decoder work, which is what reddened the old 2 s - // ceiling. - // - // The byte bound is an INDEPENDENT measurement, not the guard's own - // tally: `AllocBudget::spend` sums DECLARED byte counts at chosen call - // sites, while `counting_allocations` sums the ACTUAL `layout.size()` of - // every allocation (and every realloc's full new size, so an - // incrementally grown Vec contributes more than its final size), plus the - // refusal's own formatting inside the measured window. So "refused at the - // budget" does NOT by itself mean "allocated no more than the budget" -- - // and this test's red proof (one clone moved past the spend -> 5.12e9 - // bytes against the 4.29e9 budget) is exactly the check that the two - // stay close enough for the budget to be a meaningful ceiling. - let limits = budget_limits(); - let budget = limits.max_total_alloc as u64; - let data = one_pixel_animated_webp(4000, 2000, 64); - let (err, allocated) = counting_allocations(|| { - ec_image::decode_animation_with_limits(&data, limits) - .expect_err("64 clones of a near-limit canvas is past the total budget") - }); - assert!(format!("{err}").contains("limit"), "{err}"); - assert!( - allocated <= budget, - "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget" - ); - - // Size-relative, and the half that pins the guard: 64x the frames in - // the file must not buy 64x the work. A budget spent per *input* frame, - // or after the clone instead of before it, refuses later or not at all - // as the frame count grows -- and no clock can tell those apart, since - // the work is the same order either way. - let bomb = one_pixel_animated_webp(4000, 2000, 4096); - assert!( - bomb.len() > data.len() * 16, - "the second input is meant to be far larger: {} vs {} bytes", - bomb.len(), - data.len() - ); - let (err, allocated) = counting_allocations(|| { - ec_image::decode_animation_with_limits(&bomb, limits) - .expect_err("4096 clones of a near-limit canvas is past the total budget") - }); - assert!(format!("{err}").contains("limit"), "{err}"); - assert!( - allocated <= budget, - "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" - ); -} - -/// Build an LZW-compressed data stream that keeps expanding after the -/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal -/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with -/// entries of increasing length, then a run of plain references to the -/// longest entry keeps emitting ~4 KB of output per 12-bit code with no -/// further dictionary growth to bound it. This is the classic GIF LZW bomb: -/// a stream well under 200 KB that decodes, uncapped, to hundreds of -/// megabytes. -fn lzw_bomb() -> Vec { - let min_code_size = 2u8; - let clear_code = 1u16 << min_code_size; // 4 - let end_code = clear_code + 1; // 5 - let mut next_code = clear_code + 2; // 6 - let mut code_size = min_code_size + 1; // 3 - - let mut w = BitWriter::new(); - w.push(clear_code, code_size); - w.push(0, code_size); // first code after clear: a literal, no dictionary entry - - // Phase 1: cScSc every time -- fills the dictionary, entries growing - // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly, - // so the decoder reads this stream at the same code width we wrote it). - while next_code < 4096 { - w.push(next_code, code_size); - if next_code >= (1u16 << code_size) - 1 && code_size < 12 { - code_size += 1; - } - next_code += 1; - } - - // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the - // longest entry's code keeps producing ~4 KB per code with nothing left - // to cap it. - let longest = next_code - 1; - for _ in 0..100_000 { - w.push(longest, code_size); - } - - w.push(end_code, code_size); - w.finish() -} - -/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if -/// decoded past that point, expands to hundreds of megabytes: guards the -/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds -/// `expected` bytes, rather than only checking after the loop. -#[test] -fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() { - let _heavy = heavy(); - let lzw = lzw_bomb(); - eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len()); - - let mut data = Vec::new(); - data.extend_from_slice(b"GIF87a"); - data.extend_from_slice(&4u16.to_le_bytes()); - data.extend_from_slice(&4u16.to_le_bytes()); - data.push(0x00); // no global colour table - data.push(0); - data.push(0); - data.push(0x2C); - data.extend_from_slice(&0u16.to_le_bytes()); // left - data.extend_from_slice(&0u16.to_le_bytes()); // top - data.extend_from_slice(&4u16.to_le_bytes()); // width - data.extend_from_slice(&4u16.to_le_bytes()); // height - data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3) - data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]); - data.push(2); // min code size - for chunk in lzw.chunks(255) { - data.push(chunk.len() as u8); - data.extend_from_slice(chunk); - } - data.push(0); // sub-block terminator - data.push(0x3B); // trailer - - // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour - // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is - // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes - // split as the budget tests above, and here the signal is much larger - // than any host's speed difference. - let (_out, allocated) = - counting_allocations(|| ec_image::decode_with_limits(&data, budget_limits())); - assert!( - allocated <= 1 << 20, - "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame" - ); -} - -/// The plain entry point must apply `Limits::default()`, and the limits must bind. -/// -/// A canvas just over the default `max_alloc` cannot be built: `max_pixels` caps the canvas at -/// exactly `max_alloc` bytes, so the total budget is the first limit a GIF canvas can cross. -#[test] -fn decode_animation_applies_the_default_limits() { - let data = one_pixel_gif(2, 2, 2); - let plain = ec_image::decode_animation(&data).expect("two frames within the default limits"); - let explicit = ec_image::decode_animation_with_limits(&data, ec_image::Limits::default()) - .expect("the same two frames"); - assert_eq!(plain, explicit); - - let tiny = ec_image::Limits { - max_total_alloc: 1, - ..ec_image::Limits::default() - }; - assert!( - ec_image::decode_animation_with_limits(&data, tiny).is_err(), - "a one-byte total budget must refuse the same file" - ); -} - -fn crc32(data: &[u8]) -> u32 { - let mut c = 0xffff_ffffu32; - for &b in data { - c ^= u32::from(b); - for _ in 0..8 { - c = if c & 1 != 0 { - 0xedb8_8320 ^ (c >> 1) - } else { - c >> 1 - }; - } - } - c ^ 0xffff_ffff -}