forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

no_panic.rs150 lines, 5.1 KiBHistoryRawDownload
1//! No-panic robustness: truncated and corrupted streams must come back as
2//! `Ok` or `Err`, never as a panic. Every mutation comes from a fixed-seed
3//! generator, so a reported case replays bit-for-bit.
4//!
5//! The inputs are the crate's own committed fixtures (`tests/data/*.ivf`),
6//! so the test needs no fixtures checkout.
7
8use crate::ivf;
9
10use ec_vp9::decode::Decoder;
11use ec_vp9::stream::decode_stream;
12use std::panic::{AssertUnwindSafe, catch_unwind};
13use std::path::{Path, PathBuf};
14
15/// Fixed seed: a failing case is reproduced by re-running with the same seed.
16const SEED: u64 = 0x5EED_00F0_0009;
17/// Random container-level truncations per fixture.
18const STREAM_CUTS: usize = 24;
19/// Random container-level byte corruptions per fixture.
20const STREAM_FLIPS: usize = 24;
21/// Frames probed per fixture (the first few, where the reference state is
22/// still small enough to replay cheaply).
23const FRAMES_PER_FIXTURE: usize = 3;
24/// Random mutations applied to each probed frame.
25const FRAME_MUTATIONS: usize = 24;
26
27/// xorshift64*: small, deterministic, dependency-free.
28struct Rng(u64);
29
30impl Rng {
31 fn new(seed: u64) -> Self {
32 Rng(seed | 1)
33 }
34
35 fn next_u64(&mut self) -> u64 {
36 let mut x = self.0;
37 x ^= x >> 12;
38 x ^= x << 25;
39 x ^= x >> 27;
40 self.0 = x;
41 x.wrapping_mul(0x2545_F491_4F6C_DD1D)
42 }
43
44 /// Uniform-ish value in `0..n` (`n > 0`).
45 fn below(&mut self, n: usize) -> usize {
46 (self.next_u64() % n as u64) as usize
47 }
48
49 /// Flip 1..=8 random bytes of `buf` to random values.
50 fn corrupt(&mut self, buf: &mut [u8]) {
51 if buf.is_empty() {
52 return;
53 }
54 for _ in 0..1 + self.below(8) {
55 let at = self.below(buf.len());
56 buf[at] = self.next_u64() as u8;
57 }
58 }
59}
60
61/// Every `*.ivf` in the crate's `tests/data`, sorted for a stable order.
62fn fixtures() -> Vec<PathBuf> {
63 let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data");
64 let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
65 .unwrap_or_else(|e| panic!("read {}: {e}", dir.display()))
66 .map(|entry| entry.expect("dir entry").path())
67 .filter(|p| p.extension().is_some_and(|e| e == "ivf"))
68 .collect();
69 paths.sort();
70 assert!(!paths.is_empty(), "no .ivf fixtures in {}", dir.display());
71 paths
72}
73
74/// The panic payload as text, for the failure report.
75fn payload_text(payload: &(dyn std::any::Any + Send)) -> String {
76 if let Some(s) = payload.downcast_ref::<&str>() {
77 (*s).to_string()
78 } else if let Some(s) = payload.downcast_ref::<String>() {
79 s.clone()
80 } else {
81 "non-string panic payload".to_string()
82 }
83}
84
85/// Run `f` and record a failure if it panics. The decoder's result is
86/// discarded: `Ok` and `Err` are both acceptable outcomes here.
87fn no_panic(failures: &mut Vec<String>, case: &str, f: impl FnOnce()) {
88 if let Err(payload) = catch_unwind(AssertUnwindSafe(f)) {
89 failures.push(format!("{case}: {}", payload_text(&*payload)));
90 }
91}
92
93#[test]
94fn truncated_and_corrupted_streams_never_panic() {
95 let mut rng = Rng::new(SEED);
96 let mut failures = Vec::new();
97 let mut cases = 0usize;
98
99 for path in fixtures() {
100 let name = path.file_name().unwrap().to_string_lossy().into_owned();
101 let bytes = std::fs::read(&path).expect("committed fixture");
102
103 // Container level: whole-stream truncation and byte corruption.
104 for _ in 0..STREAM_CUTS {
105 let cut = rng.below(bytes.len());
106 cases += 1;
107 no_panic(&mut failures, &format!("{name} stream cut={cut}"), || {
108 let _ = decode_stream(&bytes[..cut]);
109 });
110 }
111 for flip in 0..STREAM_FLIPS {
112 let mut buf = bytes.clone();
113 rng.corrupt(&mut buf);
114 cases += 1;
115 no_panic(&mut failures, &format!("{name} stream flip={flip}"), || {
116 let _ = decode_stream(&buf);
117 });
118 }
119
120 // Frame level: a valid prefix, then one mutated frame.
121 let (_, _, _, frames) = ivf::parse_ivf(&bytes);
122 for f in 0..FRAMES_PER_FIXTURE.min(frames.len()) {
123 for m in 0..FRAME_MUTATIONS {
124 let mut frame = frames[f].data.clone();
125 if m % 2 == 0 {
126 frame.truncate(rng.below(frame.len()));
127 } else {
128 rng.corrupt(&mut frame);
129 }
130 cases += 1;
131 let case = format!("{name} frame={f} mutation={m}");
132 no_panic(&mut failures, &case, || {
133 let mut dec = Decoder::new();
134 for prior in &frames[..f] {
135 let _ = dec.decode(&prior.data);
136 }
137 let _ = dec.decode(&frame);
138 });
139 }
140 }
141 }
142
143 assert!(cases > 0, "no mutation cases ran");
144 assert!(
145 failures.is_empty(),
146 "{} of {cases} mutated inputs panicked (seed {SEED:#x}):\n{}",
147 failures.len(),
148 failures.iter().take(20).cloned().collect::<Vec<_>>().join("\n"),
149 );
150}