forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiBa69dfabTahinli7 hours ago4073 commits

fuzz.rs774 lines, 31.2 KiBHistoryRawDownload
1//! Malformed input never panics, never hangs and never allocates without
2//! bound.
3//!
4//! Ten thousand mutations per format, from a fixed seed so a failure is
5//! reproducible: bit flips, truncations, byte injections and pure noise behind
6//! each format's signature. Every one of them must come back as `Ok` or as an
7//! `Err` — a decoder reached by a file picker is reached by every broken file
8//! on the disk.
9
10use std::alloc::System;
11use std::cell::Cell;
12use std::sync::Once;
13
14use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator};
15use std::path::{Path, PathBuf};
16
17/// Counting allocator: the "refused without doing unbounded work" tests
18/// below bound that work by *bytes allocated*, not by wall time. A clock is
19/// a machine-dependent proxy for exactly the thing those tests care about --
20/// it measures the host's memcpy bandwidth, not the decoder's behaviour --
21/// and it was measured failing that way: the same refused WebP decode takes
22/// 0.75-0.89 s on this desktop host and 3.89 s on a server, a 5x spread with
23/// byte-identical decoder work, which is what reddened a 2 s ceiling.
24/// Lives in the test binary only; the shipped crate has no allocator games.
25///
26/// The tally is per-thread, not global: `cargo test` runs these tests in
27/// parallel, so a shared counter sums concurrent decodes together and
28/// reports work none of them did.
29struct CountingAlloc;
30
31std::thread_local! {
32 static ALLOC_BYTES: Cell<u64> = const { Cell::new(0) };
33}
34
35fn count_alloc(size: usize) {
36 let _ = ALLOC_BYTES.try_with(|b| b.set(b.get() + size as u64));
37}
38
39impl AllocationTracker for CountingAlloc {
40 fn allocated(&self, _addr: usize, object_size: usize, _wrapped: usize, _g: AllocationGroupId) {
41 count_alloc(object_size);
42 }
43 fn deallocated(
44 &self,
45 _addr: usize,
46 _object_size: usize,
47 _wrapped: usize,
48 _source: AllocationGroupId,
49 _current: AllocationGroupId,
50 ) {
51 }
52}
53
54#[global_allocator]
55static ALLOC: Allocator<System> = Allocator::system();
56
57/// Installs the tracker once. Realloc reaches the tracker as an allocation of
58/// the new size, which is the accounting this file has always used.
59fn install_counter() {
60 static ONCE: Once = Once::new();
61 ONCE.call_once(|| {
62 let _ = AllocationRegistry::set_global_tracker(CountingAlloc);
63 AllocationRegistry::enable_tracking();
64 });
65}
66
67/// Runs `f` on this thread and returns its value together with every byte
68/// that thread allocated while it ran. That count is the decoder's own
69/// work, independent of how fast the host is at moving those bytes around.
70fn counting_allocations<T>(f: impl FnOnce() -> T) -> (T, u64) {
71 install_counter();
72 ALLOC_BYTES.with(|b| b.set(0));
73 let out = f();
74 (out, ALLOC_BYTES.with(Cell::get))
75}
76
77/// Serializes the tests that allocate up to the decoder's whole budget.
78///
79/// Those tests each decode a near-limit canvas, so run together they need
80/// several GiB at once and the per-scope memory cap (`scripts/memguard-runner.sh`)
81/// SIGKILLs the test binary. One at a time they fit. The lock covers only
82/// those tests; the cheap ones stay parallel. A poisoned lock (a failed
83/// assertion in another heavy test) is recovered, so one failure does not
84/// cascade into spurious failures in the rest.
85///
86/// The counting allocator needs no lock for its numbers: its tally is
87/// per-thread, so serializing does not change what any test measures.
88static HEAVY: std::sync::Mutex<()> = std::sync::Mutex::new(());
89
90fn heavy() -> std::sync::MutexGuard<'static, ()> {
91 HEAVY.lock().unwrap_or_else(|e| e.into_inner())
92}
93
94/// Limits for the tests that run up to the total budget: 1 GiB total and 512 MiB per buffer.
95///
96/// The default total (4 GiB) would need about 4 GiB resident before the refusal, which is past
97/// the 3500M memory cap on the lane servers. These limits keep the same behaviour (a total
98/// budget, a per-buffer cap) at a size the cap can hold.
99///
100/// Also used by the mutation sweeps, which test robustness rather than the default limit values.
101///
102/// The tests' canvases are 4000x2000 RGBA (32,000,000 bytes), which does not divide the 1 GiB
103/// total evenly. A canvas that did (say 4096x2048, 2^25 bytes) lets the last clone that fits
104/// land exactly on the budget, and the test's own small allocations then push the measured
105/// total a few kilobytes past it.
106fn budget_limits() -> ec_image::Limits {
107 ec_image::Limits {
108 max_total_alloc: 1 << 30,
109 max_alloc: 1 << 29,
110 ..ec_image::Limits::default()
111 }
112}
113
114const ROUNDS: usize = 10_000;
115
116fn fixtures() -> PathBuf {
117 Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/stills")
118}
119
120/// xorshift64*, so every run mutates the same way.
121struct Rng(u64);
122
123impl Rng {
124 fn next(&mut self) -> u64 {
125 self.0 ^= self.0 << 13;
126 self.0 ^= self.0 >> 7;
127 self.0 ^= self.0 << 17;
128 self.0
129 }
130
131 fn below(&mut self, bound: usize) -> usize {
132 (self.next() % bound.max(1) as u64) as usize
133 }
134}
135
136/// One mutated copy of `seed`: a few bit flips, a truncation, or an injection.
137///
138/// `head` bounds where the flips land. Aiming them at the first few dozen
139/// bytes is what actually reaches the geometry and colour-type paths: spread
140/// over a whole file they nearly all land in the compressed data and stop at
141/// the first integrity check.
142fn mutate(rng: &mut Rng, seed: &[u8], head: Option<usize>) -> Vec<u8> {
143 let mut data = seed.to_vec();
144 let region = head.unwrap_or(data.len()).min(data.len());
145 match rng.below(4) {
146 0 => {
147 for _ in 0..1 + rng.below(8) {
148 let at = rng.below(region);
149 data[at] ^= 1 << rng.below(8);
150 }
151 }
152 1 => data.truncate(rng.below(data.len())),
153 2 => {
154 for _ in 0..1 + rng.below(16) {
155 let at = rng.below(region);
156 data[at] = (rng.next() & 0xff) as u8;
157 }
158 }
159 _ => {
160 // Keep the signature, replace the body with noise: this is the
161 // shape that exercises header fields hardest.
162 let keep = 12.min(data.len());
163 data.truncate(keep);
164 for _ in 0..rng.below(400) {
165 data.push((rng.next() & 0xff) as u8);
166 }
167 }
168 }
169 data
170}
171
172/// Recompute every chunk CRC of a mutated PNG.
173///
174/// Without this the checksum catches every mutation at the door and the
175/// decoder proper is never fuzzed at all — the sweep would prove only that
176/// CRC-32 works.
177fn repair_png_crcs(data: &mut [u8]) {
178 let mut at = 8usize;
179 while at + 12 <= data.len() {
180 let len = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize;
181 if len > data.len() || at + 12 + len > data.len() {
182 return;
183 }
184 let crc = crc32(&data[at + 4..at + 8 + len]);
185 data[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
186 at += 12 + len;
187 }
188}
189
190fn sweep(name: &str, seed_file: &str) {
191 // Mutated headers can claim canvases up to the budget, so a sweep is heavy too.
192 let _heavy = heavy();
193 let seed = std::fs::read(fixtures().join(seed_file)).unwrap();
194 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);
195 let mut decoded = 0usize;
196 for round in 0..ROUNDS {
197 // Half the rounds aim at the header, half at the whole file.
198 let head = if round % 2 == 0 { Some(48) } else { None };
199 let mut data = mutate(&mut rng, &seed, head);
200 if seed_file.ends_with(".png") {
201 repair_png_crcs(&mut data);
202 }
203 // The call is the assertion: a panic here fails the test with the
204 // round number, and the round number plus the fixed seed reproduces it.
205 if let Ok(image) = ec_image::decode_with_limits(&data, budget_limits()) {
206 decoded += 1;
207 let pixels = image.to_rgba8();
208 assert_eq!(
209 pixels.len(),
210 (image.width as usize) * (image.height as usize) * 4,
211 "{name} round {round}: buffer does not match the dimensions"
212 );
213 }
214 // Header-only parsing must survive the same input.
215 let _ = ec_image::info(&data);
216 }
217 eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded");
218}
219
220/// Single-seed sweeps: (old test name, format label, seed fixture). Each was a #[test]
221/// of its own; they run as one table so the mutation loop is written once.
222const SWEEPS: &[(&str, &str, &str)] = &[
223 ("png_survives_mutation", "png", "tiny.png"),
224 ("jpeg_survives_mutation", "jpeg", "tiny.jpg"),
225 ("webp_lossy_survives_mutation", "webp-lossy", "tiny-lossy.webp"),
226 ("webp_lossless_survives_mutation", "webp-lossless", "tiny-lossless.webp"),
227 ("gif_survives_mutation", "gif", "tiny.gif"),
228 // BMP sizes three separate things from header fields -- a palette, a row
229 // stride and, for the run-length compressions, a decoded row buffer -- so a
230 // mutation can put any two of them in disagreement.
231 ("bmp_survives_mutation", "bmp", "tiny.bmp"),
232 // The run-length path is the one that writes at a position the *file* chooses
233 // (delta codes move the cursor), so it gets its own seed.
234 ("a_run_length_bmp_survives_mutation", "bmp-rle", "rle8.bmp"),
235 // TIFF is a directory of offsets into itself: a mutation can point a strip,
236 // a palette or the directory's own continuation anywhere in the file.
237 ("tiff_survives_mutation", "tiff", "tiny.tiff"),
238 // The compressed, predicted path decodes into a row buffer whose length comes
239 // from tags the mutation is free to disagree about, so it gets its own seed.
240 ("a_compressed_tiff_survives_mutation", "tiff-lzw", "rgb8-lzw-pred.tiff"),
241];
242
243#[test]
244fn single_seed_sweeps_survive_mutation() {
245 // Scoped threads, as the separate #[test]s ran in parallel. `heavy()` still serializes the sweeps.
246 let failures: Vec<&str> = std::thread::scope(|s| {
247 let handles: Vec<_> = SWEEPS
248 .iter()
249 .map(|&(test, name, seed)| (test, s.spawn(move || sweep(name, seed))))
250 .collect();
251 handles
252 .into_iter()
253 .filter_map(|(test, h)| h.join().is_err().then_some(test))
254 .collect()
255 });
256 assert!(failures.is_empty(), "failed cases: {failures:?}");
257}
258
259/// The animation path has its own frame loop, its own canvas and its own
260/// disposal state machine, none of which `decode` reaches past frame one.
261#[test]
262fn a_gif_animation_survives_mutation() {
263 let seed = std::fs::read(fixtures().join("animated.gif")).unwrap();
264 let _heavy = heavy();
265 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37);
266 let mut decoded = 0usize;
267 for round in 0..ROUNDS {
268 let head = if round % 2 == 0 { Some(48) } else { None };
269 let data = mutate(&mut rng, &seed, head);
270 if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) {
271 decoded += 1;
272 for frame in &frames {
273 let image = &frame.image;
274 assert_eq!(
275 image.to_rgba8().len(),
276 (image.width as usize) * (image.height as usize) * 4,
277 "gif-animation round {round}: buffer does not match the dimensions"
278 );
279 }
280 }
281 }
282 eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded");
283}
284
285/// The WebP animation path parses its own ANMF headers and composites onto a
286/// canvas sized by a different chunk, so a mutation can make the two disagree.
287#[test]
288fn an_animated_webp_survives_mutation() {
289 let seed = std::fs::read(fixtures().join("anim-alpha.webp")).unwrap();
290 let _heavy = heavy();
291 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed);
292 let mut decoded = 0usize;
293 for round in 0..ROUNDS {
294 let head = if round % 2 == 0 { Some(48) } else { None };
295 let data = mutate(&mut rng, &seed, head);
296 if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) {
297 decoded += 1;
298 for frame in &frames {
299 let image = &frame.image;
300 assert_eq!(
301 image.to_rgba8().len(),
302 (image.width as usize) * (image.height as usize) * 4,
303 "webp-animation round {round}: buffer does not match the dimensions"
304 );
305 }
306 }
307 }
308 eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded");
309}
310
311#[test]
312fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
313 let signatures: [&[u8]; 6] = [
314 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
315 &[0xff, 0xd8, 0xff, 0xe0],
316 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
317 b"GIF89a",
318 // A TIFF header whose directory offset is inside the header itself.
319 b"II\x2a\x00\x04\x00\x00\x00",
320 // "BM" alone is two bytes anything could start with, so the guess also
321 // asks the file header to agree with itself: this prefix declares a
322 // 40-byte info header and pixels at 54, which is what makes the bytes
323 // behind it reach the decoder at all.
324 b"BM\x00\x10\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00",
325 ];
326 let _heavy = heavy();
327 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
328 for signature in signatures {
329 for _ in 0..ROUNDS / 4 {
330 let mut data = signature.to_vec();
331 for _ in 0..rng.below(200) {
332 data.push((rng.next() & 0xff) as u8);
333 }
334 let _ = ec_image::decode_with_limits(&data, budget_limits());
335 let _ = ec_image::info(&data);
336 }
337 }
338}
339
340#[test]
341fn a_header_asking_for_more_pixels_than_the_limit_is_refused() {
342 // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse
343 // it before any buffer is sized from those numbers.
344 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
345 let mut ihdr = Vec::new();
346 ihdr.extend_from_slice(&65535u32.to_be_bytes());
347 ihdr.extend_from_slice(&65535u32.to_be_bytes());
348 ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
349 png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
350 let start = png.len();
351 png.extend_from_slice(b"IHDR");
352 png.extend_from_slice(&ihdr);
353 let crc = crc32(&png[start..]);
354 png.extend_from_slice(&crc.to_be_bytes());
355 let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit");
356 assert!(format!("{err}").contains("limit"), "{err}");
357}
358
359/// LSB-first bit packer, matching how every decoder in this crate reads a
360/// GIF LZW or VP8L bitstream: used to hand-craft the smallest possible valid
361/// compressed payload for the budget tests below.
362struct BitWriter {
363 buffer: u64,
364 bits: u8,
365 out: Vec<u8>,
366}
367
368impl BitWriter {
369 fn new() -> Self {
370 BitWriter {
371 buffer: 0,
372 bits: 0,
373 out: Vec::new(),
374 }
375 }
376
377 fn push(&mut self, value: u16, width: u8) {
378 self.buffer |= u64::from(value) << self.bits;
379 self.bits += width;
380 while self.bits >= 8 {
381 self.out.push((self.buffer & 0xff) as u8);
382 self.buffer >>= 8;
383 self.bits -= 8;
384 }
385 }
386
387 fn finish(mut self) -> Vec<u8> {
388 if self.bits > 0 {
389 self.out.push((self.buffer & 0xff) as u8);
390 }
391 self.out
392 }
393}
394
395/// A minimal GIF: no global colour table, one 0x2C image descriptor with a
396/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end),
397/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen;
398/// the frame itself is always 1x1 so its own indices buffer is trivial —
399/// what grows per frame is the *composited canvas* `composite` clones.
400fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec<u8> {
401 let mut w = BitWriter::new();
402 w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2)
403 w.push(0, 3); // colour index 0, literal
404 w.push(5, 3); // end code
405 let lzw = w.finish();
406
407 let mut data = Vec::new();
408 data.extend_from_slice(b"GIF87a");
409 data.extend_from_slice(&canvas_w.to_le_bytes());
410 data.extend_from_slice(&canvas_h.to_le_bytes());
411 data.push(0x00); // no global colour table
412 data.push(0);
413 data.push(0);
414 for _ in 0..frames {
415 data.push(0x2C);
416 data.extend_from_slice(&0u16.to_le_bytes()); // left
417 data.extend_from_slice(&0u16.to_le_bytes()); // top
418 data.extend_from_slice(&1u16.to_le_bytes()); // width
419 data.extend_from_slice(&1u16.to_le_bytes()); // height
420 data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours
421 data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT
422 data.push(2); // min code size
423 data.push(lzw.len() as u8);
424 data.extend_from_slice(&lzw);
425 data.push(0); // sub-block terminator
426 }
427 data.push(0x3B); // trailer
428 data
429}
430
431#[test]
432fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() {
433 // A single 0x2C image descriptor declaring a 60000x60000 frame: the
434 // frame's own rectangle is a header field like the canvas is, and must
435 // be refused before it sizes the indices buffer below it.
436 let mut data = Vec::new();
437 data.extend_from_slice(b"GIF87a");
438 data.extend_from_slice(&4u16.to_le_bytes());
439 data.extend_from_slice(&4u16.to_le_bytes());
440 data.push(0x00);
441 data.push(0);
442 data.push(0);
443 data.push(0x2C);
444 data.extend_from_slice(&0u16.to_le_bytes());
445 data.extend_from_slice(&0u16.to_le_bytes());
446 data.extend_from_slice(&60000u16.to_le_bytes());
447 data.extend_from_slice(&60000u16.to_le_bytes());
448 data.push(0x00);
449
450 // Bounded by bytes, not by a clock: this refusal happens before the
451 // frame sizes anything at all, so the whole decode is a few hundred
452 // bytes of header parsing (measured: 421 B in 2.6 us) whatever the host's
453 // speed. The old 100 ms clock was a machine-dependent proxy for that.
454 let (err, allocated) = counting_allocations(|| {
455 ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit")
456 });
457 assert!(format!("{err}").contains("limit"), "{err}");
458 assert!(
459 allocated <= 64 * 1024,
460 "a header-only refusal allocated {allocated} bytes; it must refuse before sizing the frame"
461 );
462}
463
464#[test]
465fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
466 let _heavy = heavy();
467 // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but
468 // `composite` clones the *whole* canvas onto the result once per frame.
469 // A canvas near the single-buffer limit, repeated a few dozen times,
470 // must be caught by the decode-wide budget even though no single frame
471 // or single buffer ever looks large by itself.
472 let data = one_pixel_gif(4000, 2000, 64);
473 // A few real canvas clones run before the budget catches up (the budget
474 // is spent per frame, so it can't refuse before at least one clone), so
475 // this bounds "the decoder's own total budget, not a byte more", not "no
476 // allocation at all". Bytes, not a clock -- see the counting allocator
477 // above.
478 let limits = budget_limits();
479 let budget = limits.max_total_alloc as u64;
480 let (err, allocated) = counting_allocations(|| {
481 ec_image::decode_animation_with_limits(&data, limits)
482 .expect_err("64 clones of a near-limit canvas is past the total budget")
483 });
484 assert!(format!("{err}").contains("limit"), "{err}");
485 assert!(
486 allocated <= budget,
487 "refused decode allocated {allocated} bytes, past the {budget}-byte total budget"
488 );
489
490 // Size-relative, and the half that pins the guard: 64x the frames in the
491 // file must not buy 64x the work. A budget spent per *input* frame, or
492 // after the clone instead of before it, refuses later or not at all as
493 // the frame count grows.
494 let bomb = one_pixel_gif(4000, 2000, 4096);
495 let (err, allocated) = counting_allocations(|| {
496 ec_image::decode_animation_with_limits(&bomb, limits)
497 .expect_err("4096 clones of a near-limit canvas is past the total budget")
498 });
499 assert!(format!("{err}").contains("limit"), "{err}");
500 assert!(
501 allocated <= budget,
502 "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget"
503 );
504}
505
506#[test]
507fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() {
508 let _heavy = heavy();
509 // The other side of the same budget: a handful of frames over a large
510 // canvas is exactly what a real animation looks like, and must not be
511 // refused just because the guard above exists.
512 let data = one_pixel_gif(4000, 4000, 3);
513 let frames = ec_image::decode_animation_with_limits(&data, budget_limits())
514 .expect("well within every limit");
515 assert_eq!(frames.len(), 3);
516}
517
518/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks,
519/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a
520/// bitstream header plus one pixel, no transforms, no colour cache).
521fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u8> {
522 // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0,
523 // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the
524 // image data: no colour cache, no meta prefix, one simple prefix code
525 // per channel (colour index 0 for all four), then the single pixel.
526 let mut w = BitWriter::new();
527 w.push(0, 14); // width - 1
528 w.push(0, 14); // height - 1
529 w.push(0, 1); // alpha_is_used
530 w.push(0, 3); // version
531 w.push(0, 1); // no transform
532 w.push(0, 1); // no colour cache
533 w.push(0, 1); // no meta prefix
534 for _ in 0..5 {
535 // green/red/blue/alpha/distance, in that order: a simple code, one
536 // symbol, value 0.
537 w.push(1, 1); // simple code
538 w.push(0, 1); // one symbol
539 w.push(0, 1); // symbol is not a literal byte read as 8 bits
540 w.push(0, 1); // symbol0 = 0
541 }
542 let vp8l_bits = w.finish();
543 let mut vp8l = vec![0x2f];
544 vp8l.extend_from_slice(&vp8l_bits);
545 if vp8l.len() % 2 == 1 {
546 vp8l.push(0);
547 }
548
549 fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> {
550 let mut c = Vec::new();
551 c.extend_from_slice(tag);
552 c.extend_from_slice(&(body.len() as u32).to_le_bytes());
553 c.extend_from_slice(body);
554 if body.len() % 2 == 1 {
555 c.push(0);
556 }
557 c
558 }
559
560 let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation"
561 let off24 = |v: u32| v.to_le_bytes()[..3].to_vec();
562 let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec();
563 vp8x.extend_from_slice(&dim24(canvas_w));
564 vp8x.extend_from_slice(&dim24(canvas_h));
565 let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour
566 anim.extend_from_slice(&0u16.to_le_bytes()); // loop count
567
568 let mut anmf_body = Vec::new();
569 anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2)
570 anmf_body.extend_from_slice(&off24(0)); // y offset
571 anmf_body.extend_from_slice(&dim24(1)); // width - 1
572 anmf_body.extend_from_slice(&dim24(1)); // height - 1
573 anmf_body.extend_from_slice(&off24(1)); // duration
574 anmf_body.push(0x00); // reserved/blend/dispose
575 anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l));
576
577 let mut payload = Vec::new();
578 payload.extend_from_slice(&chunk(b"VP8X", &vp8x));
579 payload.extend_from_slice(&chunk(b"ANIM", &anim));
580 for _ in 0..frames {
581 payload.extend_from_slice(&chunk(b"ANMF", &anmf_body));
582 }
583
584 let mut data = Vec::new();
585 data.extend_from_slice(b"RIFF");
586 data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes());
587 data.extend_from_slice(b"WEBP");
588 data.extend_from_slice(&payload);
589 data
590}
591
592#[test]
593fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
594 let _heavy = heavy();
595 // The WebP analogue of the GIF test above: `decode_frames` clones the
596 // whole composited canvas into the result once per ANMF chunk.
597 //
598 // The bound here is *bytes*, not a clock. What this protects against is
599 // a guard that stops refusing and lets the clone multiplier run -- 64
600 // frames over this canvas is 64 GiB of compositing -- and a clock cannot
601 // express that: it measures the host's memcpy bandwidth, measured at
602 // 0.75-0.89 s on this desktop host against 3.89 s on a server for
603 // byte-identical decoder work, which is what reddened the old 2 s
604 // ceiling.
605 //
606 // The byte bound is an INDEPENDENT measurement, not the guard's own
607 // tally: `AllocBudget::spend` sums DECLARED byte counts at chosen call
608 // sites, while `counting_allocations` sums the ACTUAL `layout.size()` of
609 // every allocation (and every realloc's full new size, so an
610 // incrementally grown Vec contributes more than its final size), plus the
611 // refusal's own formatting inside the measured window. So "refused at the
612 // budget" does NOT by itself mean "allocated no more than the budget" --
613 // and this test's red proof (one clone moved past the spend -> 5.12e9
614 // bytes against the 4.29e9 budget) is exactly the check that the two
615 // stay close enough for the budget to be a meaningful ceiling.
616 let limits = budget_limits();
617 let budget = limits.max_total_alloc as u64;
618 let data = one_pixel_animated_webp(4000, 2000, 64);
619 let (err, allocated) = counting_allocations(|| {
620 ec_image::decode_animation_with_limits(&data, limits)
621 .expect_err("64 clones of a near-limit canvas is past the total budget")
622 });
623 assert!(format!("{err}").contains("limit"), "{err}");
624 assert!(
625 allocated <= budget,
626 "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget"
627 );
628
629 // Size-relative, and the half that pins the guard: 64x the frames in
630 // the file must not buy 64x the work. A budget spent per *input* frame,
631 // or after the clone instead of before it, refuses later or not at all
632 // as the frame count grows -- and no clock can tell those apart, since
633 // the work is the same order either way.
634 let bomb = one_pixel_animated_webp(4000, 2000, 4096);
635 assert!(
636 bomb.len() > data.len() * 16,
637 "the second input is meant to be far larger: {} vs {} bytes",
638 bomb.len(),
639 data.len()
640 );
641 let (err, allocated) = counting_allocations(|| {
642 ec_image::decode_animation_with_limits(&bomb, limits)
643 .expect_err("4096 clones of a near-limit canvas is past the total budget")
644 });
645 assert!(format!("{err}").contains("limit"), "{err}");
646 assert!(
647 allocated <= budget,
648 "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget"
649 );
650}
651
652/// Build an LZW-compressed data stream that keeps expanding after the
653/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal
654/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with
655/// entries of increasing length, then a run of plain references to the
656/// longest entry keeps emitting ~4 KB of output per 12-bit code with no
657/// further dictionary growth to bound it. This is the classic GIF LZW bomb:
658/// a stream well under 200 KB that decodes, uncapped, to hundreds of
659/// megabytes.
660fn lzw_bomb() -> Vec<u8> {
661 let min_code_size = 2u8;
662 let clear_code = 1u16 << min_code_size; // 4
663 let end_code = clear_code + 1; // 5
664 let mut next_code = clear_code + 2; // 6
665 let mut code_size = min_code_size + 1; // 3
666
667 let mut w = BitWriter::new();
668 w.push(clear_code, code_size);
669 w.push(0, code_size); // first code after clear: a literal, no dictionary entry
670
671 // Phase 1: cScSc every time -- fills the dictionary, entries growing
672 // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly,
673 // so the decoder reads this stream at the same code width we wrote it).
674 while next_code < 4096 {
675 w.push(next_code, code_size);
676 if next_code >= (1u16 << code_size) - 1 && code_size < 12 {
677 code_size += 1;
678 }
679 next_code += 1;
680 }
681
682 // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the
683 // longest entry's code keeps producing ~4 KB per code with nothing left
684 // to cap it.
685 let longest = next_code - 1;
686 for _ in 0..100_000 {
687 w.push(longest, code_size);
688 }
689
690 w.push(end_code, code_size);
691 w.finish()
692}
693
694/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if
695/// decoded past that point, expands to hundreds of megabytes: guards the
696/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds
697/// `expected` bytes, rather than only checking after the loop.
698#[test]
699fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() {
700 let _heavy = heavy();
701 let lzw = lzw_bomb();
702 eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len());
703
704 let mut data = Vec::new();
705 data.extend_from_slice(b"GIF87a");
706 data.extend_from_slice(&4u16.to_le_bytes());
707 data.extend_from_slice(&4u16.to_le_bytes());
708 data.push(0x00); // no global colour table
709 data.push(0);
710 data.push(0);
711 data.push(0x2C);
712 data.extend_from_slice(&0u16.to_le_bytes()); // left
713 data.extend_from_slice(&0u16.to_le_bytes()); // top
714 data.extend_from_slice(&4u16.to_le_bytes()); // width
715 data.extend_from_slice(&4u16.to_le_bytes()); // height
716 data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3)
717 data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]);
718 data.push(2); // min code size
719 for chunk in lzw.chunks(255) {
720 data.push(chunk.len() as u8);
721 data.extend_from_slice(chunk);
722 }
723 data.push(0); // sub-block terminator
724 data.push(0x3B); // trailer
725
726 // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour
727 // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is
728 // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes
729 // split as the budget tests above, and here the signal is much larger
730 // than any host's speed difference.
731 let (_out, allocated) =
732 counting_allocations(|| ec_image::decode_with_limits(&data, budget_limits()));
733 assert!(
734 allocated <= 1 << 20,
735 "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame"
736 );
737}
738
739/// The plain entry point must apply `Limits::default()`, and the limits must bind.
740///
741/// A canvas just over the default `max_alloc` cannot be built: `max_pixels` caps the canvas at
742/// exactly `max_alloc` bytes, so the total budget is the first limit a GIF canvas can cross.
743#[test]
744fn decode_animation_applies_the_default_limits() {
745 let data = one_pixel_gif(2, 2, 2);
746 let plain = ec_image::decode_animation(&data).expect("two frames within the default limits");
747 let explicit = ec_image::decode_animation_with_limits(&data, ec_image::Limits::default())
748 .expect("the same two frames");
749 assert_eq!(plain, explicit);
750
751 let tiny = ec_image::Limits {
752 max_total_alloc: 1,
753 ..ec_image::Limits::default()
754 };
755 assert!(
756 ec_image::decode_animation_with_limits(&data, tiny).is_err(),
757 "a one-byte total budget must refuse the same file"
758 );
759}
760
761fn crc32(data: &[u8]) -> u32 {
762 let mut c = 0xffff_ffffu32;
763 for &b in data {
764 c ^= u32::from(b);
765 for _ in 0..8 {
766 c = if c & 1 != 0 {
767 0xedb8_8320 ^ (c >> 1)
768 } else {
769 c >> 1
770 };
771 }
772 }
773 c ^ 0xffff_ffff
774}