forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

media_fuzz.rs231 lines, 8.0 KiBHistoryRawDownload
1//! Seeded mutation fuzz over the media corpus. Every entry point must return
2//! `Ok` or `Err` on a damaged file: a panic (on the calling thread or any worker
3//! it spawned) or a call that runs past `HANG` fails the test.
4//!
5//! Mutations per file, per iteration: truncate at a random offset, flip random
6//! bits, or zero a random range. `EDITH_FUZZ_ITERS` sets the iterations per file
7//! (default 16). Mutated copies go under `CARGO_TARGET_TMPDIR`, so /tmp stays out
8//! of it.
9
10use std::panic::{self, AssertUnwindSafe};
11use std::path::{Path, PathBuf};
12use std::sync::mpsc::{self, RecvTimeoutError};
13use std::sync::Mutex;
14use std::time::Duration;
15
16use engine::{audio::AudioSession, decode::DecodeSession, demux, playback::PlaybackSession, subtitle};
17
18/// Per-call budget. A file that takes longer than this is a hang.
19const HANG: Duration = Duration::from_secs(5);
20const MEDIA: &[&str] = &[
21 "mp4", "m4v", "mov", "mkv", "mka", "mks", "webm", "mpg", "mpeg", "wav", "mp3", "flac", "ogg",
22 "opus", "m4a", "aac", "srt", "vtt", "ass", "png", "jpg", "jpeg",
23];
24
25/// Panic messages from any thread, captured while a case runs.
26static PANICS: Mutex<Vec<String>> = Mutex::new(Vec::new());
27
28/// xorshift64: deterministic, dependency-free.
29struct Rng(u64);
30
31impl Rng {
32 fn next(&mut self) -> u64 {
33 self.0 ^= self.0 << 13;
34 self.0 ^= self.0 >> 7;
35 self.0 ^= self.0 << 17;
36 self.0
37 }
38
39 fn below(&mut self, n: usize) -> usize {
40 (self.next() % n as u64) as usize
41 }
42}
43
44fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
45 let Ok(entries) = std::fs::read_dir(dir) else {
46 return;
47 };
48 for entry in entries.flatten() {
49 let path = entry.path();
50 if path.is_dir() {
51 walk(&path, out);
52 } else if path
53 .extension()
54 .and_then(|e| e.to_str())
55 .is_some_and(|e| MEDIA.contains(&e.to_ascii_lowercase().as_str()))
56 {
57 out.push(path);
58 }
59 }
60}
61
62/// Every media file under the fixture dirs and `assets/`, sorted for a stable seed map.
63fn corpus() -> Vec<PathBuf> {
64 let root = Path::new(env!("CARGO_MANIFEST_DIR"));
65 let mut files = Vec::new();
66 for dir in ["tests/data", "tests/fixtures/fuzz", "../../assets"] {
67 walk(&root.join(dir), &mut files);
68 }
69 files.sort();
70 files
71}
72
73/// One damaged copy of `bytes`, and a label for the failure report.
74fn mutate(bytes: &[u8], rng: &mut Rng) -> (String, Vec<u8>) {
75 let len = bytes.len();
76 match rng.below(4) {
77 0 => {
78 let at = rng.below(len + 1);
79 (format!("truncate@{at}"), bytes[..at].to_vec())
80 }
81 // Container and codec headers sit at the front, so most flips land there.
82 m @ (1 | 3) => {
83 let mut out = bytes.to_vec();
84 let window = if m == 3 { len.min(512) } else { len };
85 let flips = 1 + rng.below(16);
86 for _ in 0..flips {
87 let at = rng.below(window);
88 out[at] ^= 1 << rng.below(8);
89 }
90 (format!("flip{flips}/w{window}"), out)
91 }
92 _ => {
93 let start = rng.below(len);
94 let span = 1 + rng.below((len - start).min(4096));
95 let mut out = bytes.to_vec();
96 out[start..start + span].fill(0);
97 (format!("zero@{start}+{span}"), out)
98 }
99 }
100}
101
102/// Drains up to `n` items from a worker channel, stopping at the first gap or end.
103fn drain<T>(rx: mpsc::Receiver<T>, n: usize) {
104 for _ in 0..n {
105 if rx.recv_timeout(Duration::from_secs(1)).is_err() {
106 break;
107 }
108 }
109}
110
111/// Every public entry point a damaged file can reach.
112fn exercise(path: &Path) {
113 let _ = demux::probe_media(path);
114 if let Ok(Some((_meta, rx))) = AudioSession::open(path) {
115 drain(rx, 4);
116 }
117 if let Ok((_meta, rx)) = DecodeSession::open(path) {
118 drain(rx, 3);
119 }
120 if let Ok(mut session) = PlaybackSession::open(path) {
121 let _ = session.import(path);
122 }
123 let _ = PlaybackSession::parse_subtitles(path);
124 let _ = subtitle::open(path, None);
125}
126
127fn payload_text(payload: Box<dyn std::any::Any + Send>) -> String {
128 payload
129 .downcast_ref::<&str>()
130 .map(|s| s.to_string())
131 .or_else(|| payload.downcast_ref::<String>().cloned())
132 .unwrap_or_else(|| "non-string panic".into())
133}
134
135/// Runs `exercise` on its own thread. `Err` is a panic, `Hang` a timeout.
136enum Outcome {
137 Ok,
138 Panic(String),
139 Hang,
140}
141
142fn run_case(path: &Path) -> Outcome {
143 let (tx, rx) = mpsc::channel();
144 let owned = path.to_path_buf();
145 std::thread::spawn(move || {
146 let result = panic::catch_unwind(AssertUnwindSafe(|| exercise(&owned)));
147 let _ = tx.send(result.err().map(payload_text));
148 });
149 match rx.recv_timeout(HANG) {
150 Ok(None) => Outcome::Ok,
151 Ok(Some(msg)) => Outcome::Panic(msg),
152 Err(RecvTimeoutError::Timeout) => Outcome::Hang,
153 Err(RecvTimeoutError::Disconnected) => Outcome::Panic("case thread died".into()),
154 }
155}
156
157/// Minimal inputs that once panicked or hung, kept as fixtures under
158/// `tests/fixtures/fuzz/`. Each must come back `Ok` or `Err` from every entry point.
159const REGRESSIONS: &[&str] = &["moov_largesize_wrap.mp4", "huge_block.mkv"];
160
161#[test]
162fn damaged_media_never_panics_or_hangs() {
163 panic::set_hook(Box::new(|info| {
164 let location = info
165 .location()
166 .map(|l| format!("{}:{}", l.file(), l.line()))
167 .unwrap_or_default();
168 let line = format!("{location}: {info}");
169 eprintln!("{line}");
170 PANICS.lock().unwrap().push(line);
171 }));
172
173 let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fuzz");
174 for name in REGRESSIONS {
175 let path = fixtures.join(name);
176 PANICS.lock().unwrap().clear();
177 let outcome = run_case(&path);
178 let captured = std::mem::take(&mut *PANICS.lock().unwrap());
179 match outcome {
180 Outcome::Ok if captured.is_empty() => {}
181 Outcome::Ok => panic!("{name}: worker panic: {}", captured.join(" | ")),
182 Outcome::Panic(msg) => panic!("{name}: panic: {msg}"),
183 Outcome::Hang => panic!("{name}: hang over {HANG:?}"),
184 }
185 }
186
187 let iters: usize = std::env::var("EDITH_FUZZ_ITERS")
188 .ok()
189 .and_then(|v| v.parse().ok())
190 .unwrap_or(16);
191 let scratch = Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("media_fuzz-{}", std::process::id()));
192 std::fs::create_dir_all(&scratch).unwrap();
193
194 let mut failures = Vec::new();
195 let files = corpus();
196 assert!(!files.is_empty(), "no media files found");
197 for (fi, file) in files.iter().enumerate() {
198 let bytes = std::fs::read(file).unwrap();
199 if bytes.is_empty() {
200 continue;
201 }
202 let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("bin");
203 let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("f");
204 for iter in 0..iters {
205 let seed = ((fi as u64 + 1) << 32) ^ (iter as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);
206 let mut rng = Rng(seed | 1);
207 let (label, damaged) = mutate(&bytes, &mut rng);
208 let case = scratch.join(format!("{stem}-{iter}.{ext}"));
209 std::fs::write(&case, &damaged).unwrap();
210
211 PANICS.lock().unwrap().clear();
212 let outcome = run_case(&case);
213 let captured = std::mem::take(&mut *PANICS.lock().unwrap());
214 let verdict = match outcome {
215 Outcome::Ok if captured.is_empty() => continue,
216 Outcome::Ok => format!("worker panic: {}", captured.join(" | ")),
217 Outcome::Panic(msg) => format!("panic: {msg}"),
218 Outcome::Hang => format!("hang over {HANG:?}"),
219 };
220 failures.push(format!("{} [{label}] {verdict} (input {})", file.display(), case.display()));
221 }
222 }
223
224 let _ = panic::take_hook();
225 assert!(
226 failures.is_empty(),
227 "{} failing case(s):\n{}",
228 failures.len(),
229 failures.join("\n")
230 );
231}