diff --git a/Cargo.lock b/Cargo.lock index 9d8e92a1..817bbf6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -591,7 +591,6 @@ dependencies = [ "ec-inflate", "ec-testkit", "image", - "tracking-allocator", ] [[package]] @@ -1326,12 +1325,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - [[package]] name = "pkg-config" version = "0.3.34" @@ -1794,44 +1787,6 @@ dependencies = [ "zune-jpeg", ] -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "pin-project-lite", - "tracing-core", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "tracing-core", -] - -[[package]] -name = "tracking-allocator" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b61e0cb3385e17df7db29c565b40fd0350dfe8a076c7eea83d416e30cfd0581" -dependencies = [ - "tracing", - "tracing-subscriber", -] - [[package]] name = "transpose" version = "0.2.3" 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/examples/bench.rs b/crates/ec-image/examples/bench.rs deleted file mode 100644 index ace00600..00000000 --- a/crates/ec-image/examples/bench.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! bench: still-image decode and PNG encode rows for lanes/bench.md ("lane benchrest"). -//! -//! usage: -//! bench png-dec [reps] -//! bench jpeg-dec [reps] -//! bench png-enc [reps] -//! -//! `png-dec` and `jpeg-dec` decode the file with `ec_image::decode`, `reps` times (default 5), and -//! keep the best wall time. After timing, the last decode is converted with `to_rgb8` and written to -//! `` (untimed) so the pixels can be compared with ffmpeg's `-f rawvideo -pix_fmt rgb24`. -//! `png-enc` encodes raw RGBA8 with `ec_image::png_encode::encode_rgba8`, best of `reps`, and writes -//! the last PNG to ``. -use std::hint::black_box; -use std::time::Instant; - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("png-dec" | "jpeg-dec") if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - assert!(reps >= 1, "reps must be at least 1"); - let data = std::fs::read(&args[2]).expect("read input"); - let mut best = f64::MAX; - let mut last = None; - for _ in 0..reps { - let t = Instant::now(); - let img = ec_image::decode(black_box(&data)).expect("decode"); - best = best.min(t.elapsed().as_secs_f64()); - last = Some(img); - } - let img = last.expect("at least one rep"); - let (w, h) = img.dimensions(); - let rgb = img.to_rgb8(); - std::fs::write(&args[3], &rgb).expect("write output"); - let mpix = f64::from(w) * f64::from(h) / 1e6; - println!( - "width={w} height={h} channels={} best_decode_s={best:.4} mpix_per_s={:.2} mb_per_s={:.2} out_bytes={} reps={reps}", - img.pixels.channels(), - mpix / best, - rgb.len() as f64 / best / 1e6, - rgb.len() - ); - } - Some("png-enc") if args.len() >= 6 => { - let reps: usize = args.get(6).map_or(5, |s| s.parse().expect("reps")); - assert!(reps >= 1, "reps must be at least 1"); - let w: u32 = args[3].parse().expect("width"); - let h: u32 = args[4].parse().expect("height"); - let raw = std::fs::read(&args[2]).expect("read input"); - let mut best = f64::MAX; - let mut out = Vec::new(); - for _ in 0..reps { - let t = Instant::now(); - out = ec_image::png_encode::encode_rgba8(w, h, black_box(&raw)).expect("encode"); - best = best.min(t.elapsed().as_secs_f64()); - } - std::fs::write(&args[5], &out).expect("write output"); - let mpix = f64::from(w) * f64::from(h) / 1e6; - println!( - "width={w} height={h} best_encode_s={best:.4} mpix_per_s={:.2} mb_per_s={:.2} out_bytes={} reps={reps}", - mpix / best, - raw.len() as f64 / best / 1e6, - out.len() - ); - } - _ => { - eprintln!( - "usage: bench png-dec [reps]\n bench jpeg-dec [reps]\n bench png-enc [reps]" - ); - std::process::exit(2); - } - } -} diff --git a/crates/ec-image/fuzz/Cargo.toml b/crates/ec-image/fuzz/Cargo.toml index ce7a1f66..a0b0f74f 100644 --- a/crates/ec-image/fuzz/Cargo.toml +++ b/crates/ec-image/fuzz/Cargo.toml @@ -24,20 +24,6 @@ test = false doc = false bench = false -[[bin]] -name = "decode_with_limits" -path = "fuzz_targets/decode_with_limits.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "info" -path = "fuzz_targets/info.rs" -test = false -doc = false -bench = false - [[bin]] name = "decode_animation" path = "fuzz_targets/decode_animation.rs" @@ -45,48 +31,6 @@ test = false doc = false bench = false -[[bin]] -name = "bmp" -path = "fuzz_targets/bmp.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "gif" -path = "fuzz_targets/gif.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "jpeg" -path = "fuzz_targets/jpeg.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "png" -path = "fuzz_targets/png.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "tiff" -path = "fuzz_targets/tiff.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "webp" -path = "fuzz_targets/webp.rs" -test = false -doc = false -bench = false - [[bin]] name = "probe" path = "fuzz_targets/probe.rs" diff --git a/crates/ec-image/fuzz/fuzz_targets/bmp.rs b/crates/ec-image/fuzz/fuzz_targets/bmp.rs deleted file mode 100644 index 3bb9bd76..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/bmp.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// The bmp module's own entry points, called directly so the format signature check in the -// dispatcher does not filter the input first. Header parse, then a decode under small limits. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::bmp::info(data); - let _ = ec_image::bmp::decode(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/decode_with_limits.rs b/crates/ec-image/fuzz/fuzz_targets/decode_with_limits.rs deleted file mode 100644 index bff5b0a8..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/decode_with_limits.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// Small limits: 4096x4096 pixels, 64 MiB per buffer, 128 MiB across one call. Under these a -// hostile header is refused before it sizes anything, and every path that multiplies a count by -// a size still gets exercised against a real budget. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::decode_with_limits(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/gif.rs b/crates/ec-image/fuzz/fuzz_targets/gif.rs deleted file mode 100644 index f75b5ce0..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/gif.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// The gif module's own entry points, called directly so the format signature check in the -// dispatcher does not filter the input first. Header parse, then a decode under small limits. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::gif::info(data); - let _ = ec_image::gif::decode(data, LIMITS); - let _ = ec_image::gif::decode_animation(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/info.rs b/crates/ec-image/fuzz/fuzz_targets/info.rs deleted file mode 100644 index f6ce5e97..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/info.rs +++ /dev/null @@ -1,8 +0,0 @@ -#![no_main] - -use libfuzzer_sys::fuzz_target; - -// Header-only parse: dimensions and format details without decoding any pixels. -fuzz_target!(|data: &[u8]| { - let _ = ec_image::info(data); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/jpeg.rs b/crates/ec-image/fuzz/fuzz_targets/jpeg.rs deleted file mode 100644 index f3ad427d..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/jpeg.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// The jpeg module's own entry points, called directly so the format signature check in the -// dispatcher does not filter the input first. Header parse, then a decode under small limits. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::jpeg::info(data); - let _ = ec_image::jpeg::decode(data, LIMITS); - let _ = ec_image::jpeg::decode_yuv(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/png.rs b/crates/ec-image/fuzz/fuzz_targets/png.rs deleted file mode 100644 index fd6bf435..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/png.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// The png module's own entry points, called directly so the format signature check in the -// dispatcher does not filter the input first. Header parse, then a decode under small limits. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::png::info(data); - let _ = ec_image::png::decode(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/tiff.rs b/crates/ec-image/fuzz/fuzz_targets/tiff.rs deleted file mode 100644 index 43dec73d..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/tiff.rs +++ /dev/null @@ -1,17 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// The tiff module's own entry points, called directly so the format signature check in the -// dispatcher does not filter the input first. Header parse, then a decode under small limits. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::tiff::info(data); - let _ = ec_image::tiff::decode(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/fuzz_targets/webp.rs b/crates/ec-image/fuzz/fuzz_targets/webp.rs deleted file mode 100644 index b74c3714..00000000 --- a/crates/ec-image/fuzz/fuzz_targets/webp.rs +++ /dev/null @@ -1,18 +0,0 @@ -#![no_main] - -use ec_image::Limits; -use libfuzzer_sys::fuzz_target; - -// The webp module's own entry points, called directly so the format signature check in the -// dispatcher does not filter the input first. Header parse, then a decode under small limits. -const LIMITS: Limits = Limits { - max_pixels: 4096 * 4096, - max_alloc: 1 << 26, - max_total_alloc: 1 << 27, -}; - -fuzz_target!(|data: &[u8]| { - let _ = ec_image::webp::info(data); - let _ = ec_image::webp::decode(data, LIMITS); - let _ = ec_image::webp::decode_frames(data, LIMITS); -}); diff --git a/crates/ec-image/fuzz/seed.sh b/crates/ec-image/fuzz/seed.sh index 73f62fc3..cf7b6745 100755 --- a/crates/ec-image/fuzz/seed.sh +++ b/crates/ec-image/fuzz/seed.sh @@ -1,11 +1,7 @@ #!/usr/bin/env bash # seed.sh: fill fuzz/corpus// from the repo's still-image fixtures. # -# Every file under tests/data/stills (PNG, JPEG, WebP, GIF, BMP, TIFF) seeds the whole-file targets: -# decode, decode_with_limits, info, probe, decode_animation. Each format target gets only the files of its -# own format, so its corpus starts on the right signature. The VP8 frames under fixtures/vp8 are -# VP8 bitstreams, not stills, and are not used here. -# +# Every file under tests/data/stills seeds each whole-file target: decode, decode_animation, probe. # Corpus lives under fuzz/corpus, which is git-ignored. set -euo pipefail @@ -14,39 +10,16 @@ STILLS="$FUZZ_DIR/../tests/data/stills" [ -d "$STILLS" ] || { echo "seed.sh: $STILLS missing" >&2; exit 2; } CORPUS="$FUZZ_DIR/corpus" -mkdir -p "$CORPUS"/{decode,decode_with_limits,info,probe,decode_animation,bmp,gif,jpeg,png,tiff,webp} - -python3 -I - "$STILLS" "$CORPUS" <<'PY' -import glob, os, sys - -stills, corpus = sys.argv[1], sys.argv[2] -by_format = { - "png": (".png",), "jpeg": (".jpg", ".jpeg"), "webp": (".webp",), - "gif": (".gif",), "bmp": (".bmp",), "tiff": (".tif", ".tiff"), -} -all_files = sorted(p for p in glob.glob(os.path.join(stills, "*")) if os.path.isfile(p)) -if not all_files: - sys.exit("seed.sh: no still-image fixtures found") - -def write(target, name, data): - with open(os.path.join(corpus, target, name), "wb") as f: - f.write(data) - -count = {} -def bump(t): - count[t] = count.get(t, 0) + 1 +TARGETS=(decode decode_animation probe) +mkdir -p "${TARGETS[@]/#/$CORPUS/}" -for path in all_files: - name = os.path.basename(path) - ext = os.path.splitext(name)[1].lower() - data = open(path, "rb").read() - for t in ("decode", "decode_with_limits", "info", "probe", "decode_animation"): - write(t, name, data) - bump(t) - for fmt, exts in by_format.items(): - if ext in exts: - write(fmt, name, data) - bump(fmt) -for t in ("decode", "decode_with_limits", "info", "decode_animation", "bmp", "gif", "jpeg", "png", "tiff", "webp"): - print(f"{t}: {count.get(t, 0)} seeds") -PY +n=0 +for path in "$STILLS"/*; do + [ -f "$path" ] || continue + for t in "${TARGETS[@]}"; do + cp "$path" "$CORPUS/$t/$(basename "$path")" + n=$((n + 1)) + done +done +[ "$n" -gt 0 ] || { echo "seed.sh: no still-image fixtures found" >&2; exit 2; } +echo "seeded $n files under $CORPUS" diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index ef163d62..dca332e3 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -333,11 +333,6 @@ fn narrow(v: u16) -> u8 { ((u32::from(v) + 128) / 257) as u8 } -/// 8-bit sample widened to 16: `v * 65535 / 255`, exact. -fn widen(v: u8) -> u16 { - u16::from(v) * 257 -} - impl Image { /// `(width, height)`. pub fn dimensions(&self) -> (u32, u32) { @@ -404,34 +399,6 @@ impl Image { out } - /// Packed 16-bit R,G,B — 8-bit sources widened exactly (`v * 257`). - pub fn to_rgb16(&self) -> Vec { - match &self.pixels { - Pixels::Rgb16(d) => d.clone(), - Pixels::Rgba16(d) => d.as_chunks::<4>().0.iter().flat_map(|p| p[..3].to_vec()).collect(), - Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l]).collect(), - Pixels::La16(d) => d.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0]]).collect(), - _ => self.to_rgb8().into_iter().map(widen).collect(), - } - } - - /// Packed 16-bit R,G,B,A; opaque where the source had no alpha. - pub fn to_rgba16(&self) -> Vec { - match &self.pixels { - Pixels::Rgba16(d) => d.clone(), - Pixels::Rgb16(d) => d - .as_chunks::<3>().0.iter() - .flat_map(|p| [p[0], p[1], p[2], u16::MAX]) - .collect(), - Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(), - Pixels::La16(d) => d - .as_chunks::<2>().0.iter() - .flat_map(|p| [p[0], p[0], p[0], p[1]]) - .collect(), - _ => self.to_rgba8().into_iter().map(widen).collect(), - } - } - /// The image as an [`ec_core::VideoFrame`], packed RGB8 or RGBA8. /// /// The natural bridge for a caller that composes stills and decoded video @@ -466,6 +433,15 @@ pub struct Info { pub orientation: u8, } +fn format_of(data: &[u8]) -> Result { + ImageFormat::guess(data).ok_or_else(|| { + Error::unsupported( + "image", + "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", + ) + }) +} + /// Decode `data`, guessing the format from its leading bytes. pub fn decode(data: &[u8]) -> Result { decode_with_limits(data, Limits::default()) @@ -473,17 +449,13 @@ pub fn decode(data: &[u8]) -> Result { /// [`decode`] with caller-chosen [`Limits`]. pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { - match ImageFormat::guess(data) { - Some(ImageFormat::Png) => png::decode(data, limits), - Some(ImageFormat::Jpeg) => jpeg::decode(data, limits), - Some(ImageFormat::WebP) => webp::decode(data, limits), - Some(ImageFormat::Gif) => gif::decode(data, limits), - Some(ImageFormat::Bmp) => bmp::decode(data, limits), - Some(ImageFormat::Tiff) => tiff::decode(data, limits), - None => Err(Error::unsupported( - "image", - "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", - )), + match format_of(data)? { + ImageFormat::Png => png::decode(data, limits), + ImageFormat::Jpeg => jpeg::decode(data, limits), + ImageFormat::WebP => webp::decode(data, limits), + ImageFormat::Gif => gif::decode(data, limits), + ImageFormat::Bmp => bmp::decode(data, limits), + ImageFormat::Tiff => tiff::decode(data, limits), } } @@ -493,17 +465,13 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { /// The whole of `data` is read as header. To look at a bounded prefix or a /// stream instead, use [`probe`] or [`probe_reader`]. pub fn info(data: &[u8]) -> Result { - match ImageFormat::guess(data) { - Some(ImageFormat::Png) => png::info(data), - Some(ImageFormat::Jpeg) => jpeg::info(data), - Some(ImageFormat::WebP) => webp::info(data), - Some(ImageFormat::Gif) => gif::info(data), - Some(ImageFormat::Bmp) => bmp::info(data), - Some(ImageFormat::Tiff) => tiff::info(data), - None => Err(Error::unsupported( - "image", - "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", - )), + match format_of(data)? { + ImageFormat::Png => png::info(data), + ImageFormat::Jpeg => jpeg::info(data), + ImageFormat::WebP => webp::info(data), + ImageFormat::Gif => gif::info(data), + ImageFormat::Bmp => bmp::info(data), + ImageFormat::Tiff => tiff::info(data), } } @@ -535,9 +503,9 @@ pub fn decode_animation(data: &[u8]) -> Result> { /// The limits bound every frame and the whole composite, so a caller with a /// tighter memory budget than the default can lower them here. pub fn decode_animation_with_limits(data: &[u8], limits: Limits) -> Result> { - match ImageFormat::guess(data) { - Some(ImageFormat::Gif) => gif::decode_animation(data, limits), - Some(ImageFormat::WebP) if webp::is_animated(data) => webp::decode_frames(data, limits), + match format_of(data)? { + ImageFormat::Gif => gif::decode_animation(data, limits), + ImageFormat::WebP if webp::is_animated(data) => webp::decode_frames(data, limits), _ => Ok(vec![AnimationFrame { image: decode_with_limits(data, limits)?, delay_num: 0, @@ -552,12 +520,6 @@ pub fn open(path: impl AsRef) -> Result { decode(&data) } -/// Read the file at `path` and report its header dimensions. -pub fn open_info(path: impl AsRef) -> Result { - let data = std::fs::read(path).map_err(Error::Io)?; - info(&data) -} - #[cfg(test)] mod tests { use super::*; @@ -582,7 +544,7 @@ mod tests { #[test] fn sample_conversion_round_trips_through_eight_bits() { for v in 0..=255u8 { - assert_eq!(narrow(widen(v)), v, "{v}"); + assert_eq!(narrow(u16::from(v) * 257), v, "{v}"); } assert_eq!(narrow(0), 0); assert_eq!(narrow(u16::MAX), 255); 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 -} diff --git a/crates/ec-image/tests/it/differential.rs b/crates/ec-image/tests/it/differential.rs index caeb8346..7d0ffc00 100644 --- a/crates/ec-image/tests/it/differential.rs +++ b/crates/ec-image/tests/it/differential.rs @@ -85,6 +85,17 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { } } +fn rgba16(img: &ec_image::Image) -> Vec { + use ec_image::Pixels; + match &img.pixels { + Pixels::L16(d) => d.iter().flat_map(|&l| [l, l, l, u16::MAX]).collect(), + Pixels::La16(d) => d.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0], p[1]]).collect(), + Pixels::Rgb16(d) => d.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], u16::MAX]).collect(), + Pixels::Rgba16(d) => d.clone(), + _ => unreachable!("only called for 16-bit pictures"), + } +} + #[test] fn png_decodes_pixel_exactly() { let files = corpus("png"); @@ -102,7 +113,7 @@ fn png_decodes_pixel_exactly() { if ours.pixels.bit_depth() == 16 { // Compared at 16 bits so the comparison is not laundered through // two different 16-to-8 rounding conventions. - let a = ours.to_rgba16(); + let a = rgba16(&ours); let b = theirs.to_rgba16().into_raw(); assert_eq!(a, b, "{} (16-bit samples)", path.display()); } else { diff --git a/crates/ec-inflate/examples/bench.rs b/crates/ec-inflate/examples/bench.rs deleted file mode 100644 index b96f8314..00000000 --- a/crates/ec-inflate/examples/bench.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! bench: zlib inflate rows for lanes/bench.md ("lane benchrest"). -//! -//! usage: -//! bench zlib [reps] -//! bench blocks [reps] -//! -//! `zlib` inflates one zlib stream with `inflate_zlib`, `reps` times (default 5), and keeps the -//! best wall time. `blocks` reads a sequence of `[u32 little-endian length][zlib stream]` records -//! (one per subtitle-sized packet) and inflates every record with `inflate_zlib`, timing the whole -//! loop. Both write the concatenated output of the last pass to ``, untimed, for the md5 -//! check against python's `zlib.decompress`. -use std::hint::black_box; -use std::time::Instant; - -/// Output ceiling passed to every call: far above the inputs used here, but not "no ceiling". -const LIMIT: usize = 1 << 30; - -fn split_blocks(data: &[u8]) -> Vec<&[u8]> { - let mut out = Vec::new(); - let mut at = 0usize; - while at < data.len() { - let len = u32::from_le_bytes(data[at..at + 4].try_into().expect("4 bytes")) as usize; - at += 4; - out.push(&data[at..at + len]); - at += len; - } - out -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some(mode @ ("zlib" | "blocks")) if args.len() >= 4 => { - let reps: usize = args.get(4).map_or(5, |s| s.parse().expect("reps")); - assert!(reps >= 1, "reps must be at least 1"); - let data = std::fs::read(&args[2]).expect("read input"); - let blocks = if mode == "blocks" { split_blocks(&data) } else { Vec::new() }; - let mut best = f64::MAX; - let mut out = Vec::new(); - for _ in 0..reps { - let t = Instant::now(); - out = Vec::new(); - if mode == "zlib" { - out = ec_inflate::inflate_zlib(black_box(&data), LIMIT).expect("inflate"); - } else { - for b in &blocks { - let v = ec_inflate::inflate_zlib(black_box(b), LIMIT).expect("inflate block"); - out.extend_from_slice(&v); - } - } - best = best.min(t.elapsed().as_secs_f64()); - } - std::fs::write(&args[3], &out).expect("write output"); - let streams = if mode == "blocks" { blocks.len() } else { 1 }; - println!( - "mode={mode} streams={streams} in_bytes={} out_bytes={} best_inflate_s={best:.4} mb_per_s={:.2} reps={reps}", - data.len(), - out.len(), - out.len() as f64 / best / 1e6 - ); - } - _ => { - eprintln!( - "usage: bench zlib [reps]\n bench blocks [reps]" - ); - std::process::exit(2); - } - } -} diff --git a/crates/ec-inflate/fuzz/fuzz_targets/inflate_diff.rs b/crates/ec-inflate/fuzz/fuzz_targets/inflate_diff.rs index ab682dab..fb1b5164 100644 --- a/crates/ec-inflate/fuzz/fuzz_targets/inflate_diff.rs +++ b/crates/ec-inflate/fuzz/fuzz_targets/inflate_diff.rs @@ -1,6 +1,6 @@ #![no_main] -use ec_inflate::{inflate, inflate_zlib}; +use ec_inflate::{Format, inflate_into, inflate_zlib}; use libfuzzer_sys::fuzz_target; const LIMIT: usize = 16 << 20; @@ -12,8 +12,9 @@ fuzz_target!(|data: &[u8]| { return; }; let (ours, theirs) = if sel & 1 == 0 { + let mut out = Vec::new(); ( - inflate(body, LIMIT), + inflate_into(body, &mut out, LIMIT, Format::Raw).map(|()| out), miniz_oxide::inflate::decompress_to_vec_with_limit(body, LIMIT), ) } else { diff --git a/crates/ec-inflate/fuzz/fuzz_targets/inflate_raw.rs b/crates/ec-inflate/fuzz/fuzz_targets/inflate_raw.rs index eecc15d5..c973832a 100644 --- a/crates/ec-inflate/fuzz/fuzz_targets/inflate_raw.rs +++ b/crates/ec-inflate/fuzz/fuzz_targets/inflate_raw.rs @@ -1,9 +1,9 @@ #![no_main] -use ec_inflate::inflate; +use ec_inflate::{Format, inflate_into}; use libfuzzer_sys::fuzz_target; // Whole input is one raw DEFLATE stream, capped at 16 MiB of output. fuzz_target!(|data: &[u8]| { - let _ = inflate(data, 16 << 20); + let _ = inflate_into(data, &mut Vec::new(), 16 << 20, Format::Raw); }); diff --git a/crates/ec-inflate/src/bits.rs b/crates/ec-inflate/src/bits.rs index 13e238f4..4fa0aa54 100644 --- a/crates/ec-inflate/src/bits.rs +++ b/crates/ec-inflate/src/bits.rs @@ -39,8 +39,8 @@ impl<'a> Bits<'a> { /// most symbols. #[inline] pub(crate) fn refill(&mut self) { - if let Some(next) = self.src.get(self.pos..self.pos + 8) { - let bytes = u64::from_le_bytes(next.try_into().expect("an eight byte slice")); + if let Some(next) = self.src.get(self.pos..).and_then(<[u8]>::first_chunk::<8>) { + let bytes = u64::from_le_bytes(*next); self.buf |= bytes << self.count; self.pos += ((63 - self.count) >> 3) as usize; self.count |= 56; diff --git a/crates/ec-inflate/src/deflate.rs b/crates/ec-inflate/src/deflate.rs index 75b3066d..98edb40a 100644 --- a/crates/ec-inflate/src/deflate.rs +++ b/crates/ec-inflate/src/deflate.rs @@ -205,7 +205,7 @@ fn stored_blocks(input: &[u8]) -> Vec { #[cfg(test)] mod tests { use super::*; - use crate::{inflate, inflate_zlib}; + use crate::inflate_zlib; fn pseudo_random(n: usize, seed: u32) -> Vec { let mut s = seed; @@ -217,6 +217,11 @@ mod tests { .collect() } + fn inflate(raw: &[u8], limit: usize) -> Result, crate::Error> { + let mut out = Vec::new(); + crate::inflate_into(raw, &mut out, limit, crate::Format::Raw).map(|()| out) + } + #[test] fn empty_and_tiny_inputs_round_trip() { for input in [&b""[..], b"a", b"ab", b"abc", b"abcabcabc"] { diff --git a/crates/ec-inflate/src/lib.rs b/crates/ec-inflate/src/lib.rs index 57ba2107..32942b85 100644 --- a/crates/ec-inflate/src/lib.rs +++ b/crates/ec-inflate/src/lib.rs @@ -1,9 +1,9 @@ //! DEFLATE (RFC 1951) and zlib (RFC 1950) decompression. //! -//! Two entry points, both one-shot over a complete buffer: [`inflate`] for a -//! raw DEFLATE stream (what PNG's `IDAT` chain and Matroska header stripping -//! hand over) and [`inflate_zlib`] for the same thing inside a zlib wrapper, -//! header checked and Adler-32 verified. +//! Two entry points, both one-shot over a complete buffer: [`inflate_zlib`] for a +//! zlib stream, header checked and Adler-32 verified, and [`inflate_into`] for +//! either wrapper, with [`Format::Raw`] for a bare DEFLATE stream (what +//! Matroska header stripping hands over). //! //! Contracts worth knowing before implementing against this crate: //! @@ -117,13 +117,6 @@ pub enum Format { Zlib, } -/// Decompress a raw DEFLATE stream, producing at most `limit` bytes. -pub fn inflate(input: &[u8], limit: usize) -> Result, Error> { - let mut out = Vec::new(); - inflate_into(input, &mut out, limit, Format::Raw)?; - Ok(out) -} - /// Decompress a zlib stream, producing at most `limit` bytes. /// /// The two header bytes are checked and the Adler-32 trailer is verified @@ -153,13 +146,11 @@ pub fn inflate_into( let mut bits = Bits::new(body); let end = inflate::blocks(&mut bits, out, limit)?; if format == Format::Zlib { - let trailer: [u8; 4] = body + let trailer = body .get(end..) - .and_then(|rest| rest.get(..4)) - .ok_or(Error::Truncated)? - .try_into() - .expect("a four byte slice"); - let expected = u32::from_be_bytes(trailer); + .and_then(<[u8]>::first_chunk::<4>) + .ok_or(Error::Truncated)?; + let expected = u32::from_be_bytes(*trailer); let actual = adler32(&out[start..]); if expected != actual { return Err(Error::Adler32Mismatch { expected, actual }); diff --git a/crates/ec-inflate/tests/inflate.rs b/crates/ec-inflate/tests/inflate.rs index 379380b2..af8b5381 100644 --- a/crates/ec-inflate/tests/inflate.rs +++ b/crates/ec-inflate/tests/inflate.rs @@ -7,12 +7,17 @@ use std::io::Write; -use ec_inflate::{Error, Format, inflate, inflate_into, inflate_zlib}; +use ec_inflate::{Error, Format, inflate_into, inflate_zlib}; use flate2::Compression; use flate2::write::{DeflateEncoder, ZlibEncoder}; const NO_LIMIT: usize = usize::MAX; +fn inflate(input: &[u8], limit: usize) -> Result, Error> { + let mut out = Vec::new(); + inflate_into(input, &mut out, limit, Format::Raw).map(|()| out) +} + /// xorshift64*, so the "random" inputs are the same on every run. fn pseudo_random(seed: u64, len: usize) -> Vec { let mut state = seed | 1;