forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

fuzz.rs783 lines, 31.5 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("../../fixtures/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 Ok(seed) = std::fs::read(fixtures().join(seed_file)) else {
194 eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
195 return;
196 };
197 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);
198 let mut decoded = 0usize;
199 for round in 0..ROUNDS {
200 // Half the rounds aim at the header, half at the whole file.
201 let head = if round % 2 == 0 { Some(48) } else { None };
202 let mut data = mutate(&mut rng, &seed, head);
203 if seed_file.ends_with(".png") {
204 repair_png_crcs(&mut data);
205 }
206 // The call is the assertion: a panic here fails the test with the
207 // round number, and the round number plus the fixed seed reproduces it.
208 if let Ok(image) = ec_image::decode_with_limits(&data, budget_limits()) {
209 decoded += 1;
210 let pixels = image.to_rgba8();
211 assert_eq!(
212 pixels.len(),
213 (image.width as usize) * (image.height as usize) * 4,
214 "{name} round {round}: buffer does not match the dimensions"
215 );
216 }
217 // Header-only parsing must survive the same input.
218 let _ = ec_image::info(&data);
219 }
220 eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded");
221}
222
223/// Single-seed sweeps: (old test name, format label, seed fixture). Each was a #[test]
224/// of its own; they run as one table so the mutation loop is written once.
225const SWEEPS: &[(&str, &str, &str)] = &[
226 ("png_survives_mutation", "png", "tiny.png"),
227 ("jpeg_survives_mutation", "jpeg", "tiny.jpg"),
228 ("webp_lossy_survives_mutation", "webp-lossy", "tiny-lossy.webp"),
229 ("webp_lossless_survives_mutation", "webp-lossless", "tiny-lossless.webp"),
230 ("gif_survives_mutation", "gif", "tiny.gif"),
231 // BMP sizes three separate things from header fields -- a palette, a row
232 // stride and, for the run-length compressions, a decoded row buffer -- so a
233 // mutation can put any two of them in disagreement.
234 ("bmp_survives_mutation", "bmp", "tiny.bmp"),
235 // The run-length path is the one that writes at a position the *file* chooses
236 // (delta codes move the cursor), so it gets its own seed.
237 ("a_run_length_bmp_survives_mutation", "bmp-rle", "rle8.bmp"),
238 // TIFF is a directory of offsets into itself: a mutation can point a strip,
239 // a palette or the directory's own continuation anywhere in the file.
240 ("tiff_survives_mutation", "tiff", "tiny.tiff"),
241 // The compressed, predicted path decodes into a row buffer whose length comes
242 // from tags the mutation is free to disagree about, so it gets its own seed.
243 ("a_compressed_tiff_survives_mutation", "tiff-lzw", "rgb8-lzw-pred.tiff"),
244];
245
246#[test]
247fn single_seed_sweeps_survive_mutation() {
248 // Scoped threads, as the separate #[test]s ran in parallel. `heavy()` still serializes the sweeps.
249 let failures: Vec<&str> = std::thread::scope(|s| {
250 let handles: Vec<_> = SWEEPS
251 .iter()
252 .map(|&(test, name, seed)| (test, s.spawn(move || sweep(name, seed))))
253 .collect();
254 handles
255 .into_iter()
256 .filter_map(|(test, h)| h.join().is_err().then_some(test))
257 .collect()
258 });
259 assert!(failures.is_empty(), "failed cases: {failures:?}");
260}
261
262/// The animation path has its own frame loop, its own canvas and its own
263/// disposal state machine, none of which `decode` reaches past frame one.
264#[test]
265fn a_gif_animation_survives_mutation() {
266 let Ok(seed) = std::fs::read(fixtures().join("animated.gif")) else {
267 eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
268 return;
269 };
270 let _heavy = heavy();
271 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x9e37);
272 let mut decoded = 0usize;
273 for round in 0..ROUNDS {
274 let head = if round % 2 == 0 { Some(48) } else { None };
275 let data = mutate(&mut rng, &seed, head);
276 if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) {
277 decoded += 1;
278 for frame in &frames {
279 let image = &frame.image;
280 assert_eq!(
281 image.to_rgba8().len(),
282 (image.width as usize) * (image.height as usize) * 4,
283 "gif-animation round {round}: buffer does not match the dimensions"
284 );
285 }
286 }
287 }
288 eprintln!("gif-animation: {ROUNDS} mutations, {decoded} still decoded");
289}
290
291/// The WebP animation path parses its own ANMF headers and composites onto a
292/// canvas sized by a different chunk, so a mutation can make the two disagree.
293#[test]
294fn an_animated_webp_survives_mutation() {
295 let Ok(seed) = std::fs::read(fixtures().join("anim-alpha.webp")) else {
296 eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
297 return;
298 };
299 let _heavy = heavy();
300 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ 0x5eed);
301 let mut decoded = 0usize;
302 for round in 0..ROUNDS {
303 let head = if round % 2 == 0 { Some(48) } else { None };
304 let data = mutate(&mut rng, &seed, head);
305 if let Ok(frames) = ec_image::decode_animation_with_limits(&data, budget_limits()) {
306 decoded += 1;
307 for frame in &frames {
308 let image = &frame.image;
309 assert_eq!(
310 image.to_rgba8().len(),
311 (image.width as usize) * (image.height as usize) * 4,
312 "webp-animation round {round}: buffer does not match the dimensions"
313 );
314 }
315 }
316 }
317 eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded");
318}
319
320#[test]
321fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
322 let signatures: [&[u8]; 6] = [
323 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
324 &[0xff, 0xd8, 0xff, 0xe0],
325 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
326 b"GIF89a",
327 // A TIFF header whose directory offset is inside the header itself.
328 b"II\x2a\x00\x04\x00\x00\x00",
329 // "BM" alone is two bytes anything could start with, so the guess also
330 // asks the file header to agree with itself: this prefix declares a
331 // 40-byte info header and pixels at 54, which is what makes the bytes
332 // behind it reach the decoder at all.
333 b"BM\x00\x10\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00",
334 ];
335 let _heavy = heavy();
336 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
337 for signature in signatures {
338 for _ in 0..ROUNDS / 4 {
339 let mut data = signature.to_vec();
340 for _ in 0..rng.below(200) {
341 data.push((rng.next() & 0xff) as u8);
342 }
343 let _ = ec_image::decode_with_limits(&data, budget_limits());
344 let _ = ec_image::info(&data);
345 }
346 }
347}
348
349#[test]
350fn a_header_asking_for_more_pixels_than_the_limit_is_refused() {
351 // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse
352 // it before any buffer is sized from those numbers.
353 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
354 let mut ihdr = Vec::new();
355 ihdr.extend_from_slice(&65535u32.to_be_bytes());
356 ihdr.extend_from_slice(&65535u32.to_be_bytes());
357 ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
358 png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
359 let start = png.len();
360 png.extend_from_slice(b"IHDR");
361 png.extend_from_slice(&ihdr);
362 let crc = crc32(&png[start..]);
363 png.extend_from_slice(&crc.to_be_bytes());
364 let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit");
365 assert!(format!("{err}").contains("limit"), "{err}");
366}
367
368/// LSB-first bit packer, matching how every decoder in this crate reads a
369/// GIF LZW or VP8L bitstream: used to hand-craft the smallest possible valid
370/// compressed payload for the budget tests below.
371struct BitWriter {
372 buffer: u64,
373 bits: u8,
374 out: Vec<u8>,
375}
376
377impl BitWriter {
378 fn new() -> Self {
379 BitWriter {
380 buffer: 0,
381 bits: 0,
382 out: Vec::new(),
383 }
384 }
385
386 fn push(&mut self, value: u16, width: u8) {
387 self.buffer |= u64::from(value) << self.bits;
388 self.bits += width;
389 while self.bits >= 8 {
390 self.out.push((self.buffer & 0xff) as u8);
391 self.buffer >>= 8;
392 self.bits -= 8;
393 }
394 }
395
396 fn finish(mut self) -> Vec<u8> {
397 if self.bits > 0 {
398 self.out.push((self.buffer & 0xff) as u8);
399 }
400 self.out
401 }
402}
403
404/// A minimal GIF: no global colour table, one 0x2C image descriptor with a
405/// 2-colour local table and a one-pixel LZW stream (clear, colour 0, end),
406/// followed by the trailer. `canvas_w`/`canvas_h` size the logical screen;
407/// the frame itself is always 1x1 so its own indices buffer is trivial —
408/// what grows per frame is the *composited canvas* `composite` clones.
409fn one_pixel_gif(canvas_w: u16, canvas_h: u16, frames: usize) -> Vec<u8> {
410 let mut w = BitWriter::new();
411 w.push(4, 3); // clear code (min_code_size 2 -> clear = 1<<2)
412 w.push(0, 3); // colour index 0, literal
413 w.push(5, 3); // end code
414 let lzw = w.finish();
415
416 let mut data = Vec::new();
417 data.extend_from_slice(b"GIF87a");
418 data.extend_from_slice(&canvas_w.to_le_bytes());
419 data.extend_from_slice(&canvas_h.to_le_bytes());
420 data.push(0x00); // no global colour table
421 data.push(0);
422 data.push(0);
423 for _ in 0..frames {
424 data.push(0x2C);
425 data.extend_from_slice(&0u16.to_le_bytes()); // left
426 data.extend_from_slice(&0u16.to_le_bytes()); // top
427 data.extend_from_slice(&1u16.to_le_bytes()); // width
428 data.extend_from_slice(&1u16.to_le_bytes()); // height
429 data.push(0x80); // has LCT, sorted=0, size field 0 -> 2 colours
430 data.extend_from_slice(&[0, 0, 0, 255, 255, 255]); // 2-colour LCT
431 data.push(2); // min code size
432 data.push(lzw.len() as u8);
433 data.extend_from_slice(&lzw);
434 data.push(0); // sub-block terminator
435 }
436 data.push(0x3B); // trailer
437 data
438}
439
440#[test]
441fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() {
442 // A single 0x2C image descriptor declaring a 60000x60000 frame: the
443 // frame's own rectangle is a header field like the canvas is, and must
444 // be refused before it sizes the indices buffer below it.
445 let mut data = Vec::new();
446 data.extend_from_slice(b"GIF87a");
447 data.extend_from_slice(&4u16.to_le_bytes());
448 data.extend_from_slice(&4u16.to_le_bytes());
449 data.push(0x00);
450 data.push(0);
451 data.push(0);
452 data.push(0x2C);
453 data.extend_from_slice(&0u16.to_le_bytes());
454 data.extend_from_slice(&0u16.to_le_bytes());
455 data.extend_from_slice(&60000u16.to_le_bytes());
456 data.extend_from_slice(&60000u16.to_le_bytes());
457 data.push(0x00);
458
459 // Bounded by bytes, not by a clock: this refusal happens before the
460 // frame sizes anything at all, so the whole decode is a few hundred
461 // bytes of header parsing (measured: 421 B in 2.6 us) whatever the host's
462 // speed. The old 100 ms clock was a machine-dependent proxy for that.
463 let (err, allocated) = counting_allocations(|| {
464 ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit")
465 });
466 assert!(format!("{err}").contains("limit"), "{err}");
467 assert!(
468 allocated <= 64 * 1024,
469 "a header-only refusal allocated {allocated} bytes; it must refuse before sizing the frame"
470 );
471}
472
473#[test]
474fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
475 let _heavy = heavy();
476 // Each frame is 1x1 -- cheap to encode, cheap to check on its own -- but
477 // `composite` clones the *whole* canvas onto the result once per frame.
478 // A canvas near the single-buffer limit, repeated a few dozen times,
479 // must be caught by the decode-wide budget even though no single frame
480 // or single buffer ever looks large by itself.
481 let data = one_pixel_gif(4000, 2000, 64);
482 // A few real canvas clones run before the budget catches up (the budget
483 // is spent per frame, so it can't refuse before at least one clone), so
484 // this bounds "the decoder's own total budget, not a byte more", not "no
485 // allocation at all". Bytes, not a clock -- see the counting allocator
486 // above.
487 let limits = budget_limits();
488 let budget = limits.max_total_alloc as u64;
489 let (err, allocated) = counting_allocations(|| {
490 ec_image::decode_animation_with_limits(&data, limits)
491 .expect_err("64 clones of a near-limit canvas is past the total budget")
492 });
493 assert!(format!("{err}").contains("limit"), "{err}");
494 assert!(
495 allocated <= budget,
496 "refused decode allocated {allocated} bytes, past the {budget}-byte total budget"
497 );
498
499 // Size-relative, and the half that pins the guard: 64x the frames in the
500 // file must not buy 64x the work. A budget spent per *input* frame, or
501 // after the clone instead of before it, refuses later or not at all as
502 // the frame count grows.
503 let bomb = one_pixel_gif(4000, 2000, 4096);
504 let (err, allocated) = counting_allocations(|| {
505 ec_image::decode_animation_with_limits(&bomb, limits)
506 .expect_err("4096 clones of a near-limit canvas is past the total budget")
507 });
508 assert!(format!("{err}").contains("limit"), "{err}");
509 assert!(
510 allocated <= budget,
511 "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget"
512 );
513}
514
515#[test]
516fn a_gif_with_a_few_tiny_frames_over_a_huge_canvas_still_decodes() {
517 let _heavy = heavy();
518 // The other side of the same budget: a handful of frames over a large
519 // canvas is exactly what a real animation looks like, and must not be
520 // refused just because the guard above exists.
521 let data = one_pixel_gif(4000, 4000, 3);
522 let frames = ec_image::decode_animation_with_limits(&data, budget_limits())
523 .expect("well within every limit");
524 assert_eq!(frames.len(), 3);
525}
526
527/// A minimal RIFF WebP with an ANIM/VP8X header and `frames` ANMF chunks,
528/// each carrying a 1x1 VP8L payload (the smallest valid lossless image: a
529/// bitstream header plus one pixel, no transforms, no colour cache).
530fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u8> {
531 // VP8L bitstream for a 1x1 image: signature 0x2f, 14-bit width-1=0,
532 // 14-bit height-1=0, 1-bit alpha flag=0, 3-bit version=0, then the
533 // image data: no colour cache, no meta prefix, one simple prefix code
534 // per channel (colour index 0 for all four), then the single pixel.
535 let mut w = BitWriter::new();
536 w.push(0, 14); // width - 1
537 w.push(0, 14); // height - 1
538 w.push(0, 1); // alpha_is_used
539 w.push(0, 3); // version
540 w.push(0, 1); // no transform
541 w.push(0, 1); // no colour cache
542 w.push(0, 1); // no meta prefix
543 for _ in 0..5 {
544 // green/red/blue/alpha/distance, in that order: a simple code, one
545 // symbol, value 0.
546 w.push(1, 1); // simple code
547 w.push(0, 1); // one symbol
548 w.push(0, 1); // symbol is not a literal byte read as 8 bits
549 w.push(0, 1); // symbol0 = 0
550 }
551 let vp8l_bits = w.finish();
552 let mut vp8l = vec![0x2f];
553 vp8l.extend_from_slice(&vp8l_bits);
554 if vp8l.len() % 2 == 1 {
555 vp8l.push(0);
556 }
557
558 fn chunk(tag: &[u8; 4], body: &[u8]) -> Vec<u8> {
559 let mut c = Vec::new();
560 c.extend_from_slice(tag);
561 c.extend_from_slice(&(body.len() as u32).to_le_bytes());
562 c.extend_from_slice(body);
563 if body.len() % 2 == 1 {
564 c.push(0);
565 }
566 c
567 }
568
569 let mut vp8x = vec![0x02, 0, 0, 0]; // flags: bit 0x02 is "has animation"
570 let off24 = |v: u32| v.to_le_bytes()[..3].to_vec();
571 let dim24 = |v: u32| (v - 1).to_le_bytes()[..3].to_vec();
572 vp8x.extend_from_slice(&dim24(canvas_w));
573 vp8x.extend_from_slice(&dim24(canvas_h));
574 let mut anim = vec![0, 0, 0, 0, 0, 0]; // background colour
575 anim.extend_from_slice(&0u16.to_le_bytes()); // loop count
576
577 let mut anmf_body = Vec::new();
578 anmf_body.extend_from_slice(&off24(0)); // x offset (raw value, x = field*2)
579 anmf_body.extend_from_slice(&off24(0)); // y offset
580 anmf_body.extend_from_slice(&dim24(1)); // width - 1
581 anmf_body.extend_from_slice(&dim24(1)); // height - 1
582 anmf_body.extend_from_slice(&off24(1)); // duration
583 anmf_body.push(0x00); // reserved/blend/dispose
584 anmf_body.extend_from_slice(&chunk(b"VP8L", &vp8l));
585
586 let mut payload = Vec::new();
587 payload.extend_from_slice(&chunk(b"VP8X", &vp8x));
588 payload.extend_from_slice(&chunk(b"ANIM", &anim));
589 for _ in 0..frames {
590 payload.extend_from_slice(&chunk(b"ANMF", &anmf_body));
591 }
592
593 let mut data = Vec::new();
594 data.extend_from_slice(b"RIFF");
595 data.extend_from_slice(&(4 + payload.len() as u32).to_le_bytes());
596 data.extend_from_slice(b"WEBP");
597 data.extend_from_slice(&payload);
598 data
599}
600
601#[test]
602fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
603 let _heavy = heavy();
604 // The WebP analogue of the GIF test above: `decode_frames` clones the
605 // whole composited canvas into the result once per ANMF chunk.
606 //
607 // The bound here is *bytes*, not a clock. What this protects against is
608 // a guard that stops refusing and lets the clone multiplier run -- 64
609 // frames over this canvas is 64 GiB of compositing -- and a clock cannot
610 // express that: it measures the host's memcpy bandwidth, measured at
611 // 0.75-0.89 s on this desktop host against 3.89 s on a server for
612 // byte-identical decoder work, which is what reddened the old 2 s
613 // ceiling.
614 //
615 // The byte bound is an INDEPENDENT measurement, not the guard's own
616 // tally: `AllocBudget::spend` sums DECLARED byte counts at chosen call
617 // sites, while `counting_allocations` sums the ACTUAL `layout.size()` of
618 // every allocation (and every realloc's full new size, so an
619 // incrementally grown Vec contributes more than its final size), plus the
620 // refusal's own formatting inside the measured window. So "refused at the
621 // budget" does NOT by itself mean "allocated no more than the budget" --
622 // and this test's red proof (one clone moved past the spend -> 5.12e9
623 // bytes against the 4.29e9 budget) is exactly the check that the two
624 // stay close enough for the budget to be a meaningful ceiling.
625 let limits = budget_limits();
626 let budget = limits.max_total_alloc as u64;
627 let data = one_pixel_animated_webp(4000, 2000, 64);
628 let (err, allocated) = counting_allocations(|| {
629 ec_image::decode_animation_with_limits(&data, limits)
630 .expect_err("64 clones of a near-limit canvas is past the total budget")
631 });
632 assert!(format!("{err}").contains("limit"), "{err}");
633 assert!(
634 allocated <= budget,
635 "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget"
636 );
637
638 // Size-relative, and the half that pins the guard: 64x the frames in
639 // the file must not buy 64x the work. A budget spent per *input* frame,
640 // or after the clone instead of before it, refuses later or not at all
641 // as the frame count grows -- and no clock can tell those apart, since
642 // the work is the same order either way.
643 let bomb = one_pixel_animated_webp(4000, 2000, 4096);
644 assert!(
645 bomb.len() > data.len() * 16,
646 "the second input is meant to be far larger: {} vs {} bytes",
647 bomb.len(),
648 data.len()
649 );
650 let (err, allocated) = counting_allocations(|| {
651 ec_image::decode_animation_with_limits(&bomb, limits)
652 .expect_err("4096 clones of a near-limit canvas is past the total budget")
653 });
654 assert!(format!("{err}").contains("limit"), "{err}");
655 assert!(
656 allocated <= budget,
657 "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget"
658 );
659}
660
661/// Build an LZW-compressed data stream that keeps expanding after the
662/// dictionary itself has stopped growing: a run of `cScSc` codes (each equal
663/// to the not-yet-assigned `next_code`) fills the 4096-entry dictionary with
664/// entries of increasing length, then a run of plain references to the
665/// longest entry keeps emitting ~4 KB of output per 12-bit code with no
666/// further dictionary growth to bound it. This is the classic GIF LZW bomb:
667/// a stream well under 200 KB that decodes, uncapped, to hundreds of
668/// megabytes.
669fn lzw_bomb() -> Vec<u8> {
670 let min_code_size = 2u8;
671 let clear_code = 1u16 << min_code_size; // 4
672 let end_code = clear_code + 1; // 5
673 let mut next_code = clear_code + 2; // 6
674 let mut code_size = min_code_size + 1; // 3
675
676 let mut w = BitWriter::new();
677 w.push(clear_code, code_size);
678 w.push(0, code_size); // first code after clear: a literal, no dictionary entry
679
680 // Phase 1: cScSc every time -- fills the dictionary, entries growing
681 // 2, 3, 4, ... bytes long (mirrors `Lzw::derive`'s widening rule exactly,
682 // so the decoder reads this stream at the same code width we wrote it).
683 while next_code < 4096 {
684 w.push(next_code, code_size);
685 if next_code >= (1u16 << code_size) - 1 && code_size < 12 {
686 code_size += 1;
687 }
688 next_code += 1;
689 }
690
691 // Phase 2: dictionary is full (`derive` is now a no-op), so repeating the
692 // longest entry's code keeps producing ~4 KB per code with nothing left
693 // to cap it.
694 let longest = next_code - 1;
695 for _ in 0..100_000 {
696 w.push(longest, code_size);
697 }
698
699 w.push(end_code, code_size);
700 w.finish()
701}
702
703/// A GIF whose frame declares 4x4 (16 indices) but whose LZW stream, if
704/// decoded past that point, expands to hundreds of megabytes: guards the
705/// `lzw_decode` bound at gif.rs that stops the loop once `out` already holds
706/// `expected` bytes, rather than only checking after the loop.
707#[test]
708fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() {
709 let _heavy = heavy();
710 let lzw = lzw_bomb();
711 eprintln!("gif-lzw-bomb: {} bytes of LZW data", lzw.len());
712
713 let mut data = Vec::new();
714 data.extend_from_slice(b"GIF87a");
715 data.extend_from_slice(&4u16.to_le_bytes());
716 data.extend_from_slice(&4u16.to_le_bytes());
717 data.push(0x00); // no global colour table
718 data.push(0);
719 data.push(0);
720 data.push(0x2C);
721 data.extend_from_slice(&0u16.to_le_bytes()); // left
722 data.extend_from_slice(&0u16.to_le_bytes()); // top
723 data.extend_from_slice(&4u16.to_le_bytes()); // width
724 data.extend_from_slice(&4u16.to_le_bytes()); // height
725 data.push(0x81); // has LCT, size field 1 -> 4 colours (indices 0..3)
726 data.extend_from_slice(&[0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]);
727 data.push(2); // min code size
728 for chunk in lzw.chunks(255) {
729 data.push(chunk.len() as u8);
730 data.extend_from_slice(chunk);
731 }
732 data.push(0); // sub-block terminator
733 data.push(0x3B); // trailer
734
735 // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour
736 // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is
737 // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes
738 // split as the budget tests above, and here the signal is much larger
739 // than any host's speed difference.
740 let (_out, allocated) =
741 counting_allocations(|| ec_image::decode_with_limits(&data, budget_limits()));
742 assert!(
743 allocated <= 1 << 20,
744 "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame"
745 );
746}
747
748/// The plain entry point must apply `Limits::default()`, and the limits must bind.
749///
750/// A canvas just over the default `max_alloc` cannot be built: `max_pixels` caps the canvas at
751/// exactly `max_alloc` bytes, so the total budget is the first limit a GIF canvas can cross.
752#[test]
753fn decode_animation_applies_the_default_limits() {
754 let data = one_pixel_gif(2, 2, 2);
755 let plain = ec_image::decode_animation(&data).expect("two frames within the default limits");
756 let explicit = ec_image::decode_animation_with_limits(&data, ec_image::Limits::default())
757 .expect("the same two frames");
758 assert_eq!(plain, explicit);
759
760 let tiny = ec_image::Limits {
761 max_total_alloc: 1,
762 ..ec_image::Limits::default()
763 };
764 assert!(
765 ec_image::decode_animation_with_limits(&data, tiny).is_err(),
766 "a one-byte total budget must refuse the same file"
767 );
768}
769
770fn crc32(data: &[u8]) -> u32 {
771 let mut c = 0xffff_ffffu32;
772 for &b in data {
773 c ^= u32::from(b);
774 for _ in 0..8 {
775 c = if c & 1 != 0 {
776 0xedb8_8320 ^ (c >> 1)
777 } else {
778 c >> 1
779 };
780 }
781 }
782 c ^ 0xffff_ffff
783}