|
| 1 | +// Fuzzes ffmpeg.wasm through the FFmpeg class in Chromium and saves every |
| 2 | +// case that crashes or hangs the core, so it can be replayed. |
| 3 | +// |
| 4 | +// pnpm fuzz 2 minutes, every strategy |
| 5 | +// pnpm fuzz --time=600 --strategy=media --seed=42 |
| 6 | +// pnpm fuzz --repro=tests/fuzz/crashes/media-42-17.json |
| 7 | +// |
| 8 | +// Strategies live in tests/fuzz/strategies/<name>.mjs and export |
| 9 | +// generate(rng, seeds) -> [[method, ...args], ...] calls on FFmpeg. A case |
| 10 | +// fails when a call rejects with a trap or worker error (not an ordinary |
| 11 | +// error such as a missing file) or doesn't finish in time. |
| 12 | +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; |
| 13 | +import { join } from "node:path"; |
| 14 | +import { chromium } from "playwright"; |
| 15 | +import { startServer, root } from "../helpers/server.js"; |
| 16 | +import { rng, SEEDS, SEED_INPUT } from "./lib.mjs"; |
| 17 | + |
| 18 | +const args = Object.fromEntries( |
| 19 | + process.argv.slice(2).map((a) => { |
| 20 | + const [key, value = true] = a.replace(/^--/, "").split("="); |
| 21 | + return [key, value]; |
| 22 | + }) |
| 23 | +); |
| 24 | +const seconds = Number(args.time ?? 120); |
| 25 | +const seed = Number(args.seed ?? Date.now() % 1e6); |
| 26 | +const names = (args.strategy ?? readdirSync(join(root, "tests/fuzz/strategies")).map((f) => f.replace(".mjs", "")).join(",")).split(","); |
| 27 | +const strategies = Object.fromEntries(await Promise.all(names.map(async (n) => [n, await import(`./strategies/${n}.mjs`)]))); |
| 28 | +const TIMEOUT_MS = 20000; |
| 29 | +const CRASH = /RuntimeError|out of bounds|unreachable|Aborted|signature mismatch|table index|worker failed|not loaded|stack|OOM|Cannot enlarge/i; |
| 30 | +const crashes = join(root, "tests/fuzz/crashes"); |
| 31 | + |
| 32 | +const { server, url } = await startServer(); |
| 33 | +const browser = await chromium.launch(); |
| 34 | +const page = await browser.newPage(); |
| 35 | +await page.goto(`${url}/tests/fuzz/page.html`); |
| 36 | +await page.waitForFunction(() => window.ready); |
| 37 | +const reload = () => page.evaluate(() => window.reload()); |
| 38 | +await reload(); |
| 39 | + |
| 40 | +// Calls since the core was (re)loaded: a crash can depend on earlier ones. |
| 41 | +let history = []; |
| 42 | + |
| 43 | +// Runs one case; returns the reason it failed, or null. |
| 44 | +async function run(calls, log = () => {}) { |
| 45 | + history.push(...calls); |
| 46 | + const hang = new Promise((r) => setTimeout(() => r("hang"), TIMEOUT_MS * calls.length + 10000)); |
| 47 | + const results = await Promise.race([page.evaluate(([c, t]) => window.runCase(c, t), [calls, TIMEOUT_MS]), hang]); |
| 48 | + log(results); |
| 49 | + const failure = |
| 50 | + results === "hang" ? "hang" : |
| 51 | + results.find((x) => x.error && CRASH.test(x.error))?.error ?? |
| 52 | + ((await page.evaluate(() => window.alive())) ? null : "the core stopped answering after this case"); |
| 53 | + if (failure) { |
| 54 | + lastResults = results; |
| 55 | + await page.reload(); |
| 56 | + await page.waitForFunction(() => window.ready); |
| 57 | + await reload(); |
| 58 | + } |
| 59 | + return failure ?? null; |
| 60 | +} |
| 61 | +let lastResults; |
| 62 | + |
| 63 | +if (args.repro) { |
| 64 | + const saved = JSON.parse(readFileSync(args.repro, "utf8")); |
| 65 | + console.log(`${args.repro}: ${(await run(saved.calls, console.log)) ?? "no crash"}`); |
| 66 | + await browser.close(); |
| 67 | + server.close(); |
| 68 | + process.exit(0); |
| 69 | +} |
| 70 | + |
| 71 | +// Seed media, generated once with ffmpeg.wasm and cached. |
| 72 | +const seedDir = join(root, ".cache/fuzz-seeds"); |
| 73 | +mkdirSync(seedDir, { recursive: true }); |
| 74 | +const seeds = []; |
| 75 | +for (const [name, out] of SEEDS) { |
| 76 | + const path = join(seedDir, name); |
| 77 | + let bytes; |
| 78 | + try { |
| 79 | + bytes = readFileSync(path); |
| 80 | + } catch { |
| 81 | + const [result] = await page.evaluate(([args]) => window.runCase([["exec", args]], 60000), [[...SEED_INPUT, ...out, `/${name}`]]); |
| 82 | + if (result.ok !== 0) throw new Error(`seed ${name}: ${JSON.stringify(result)}`); |
| 83 | + bytes = Buffer.from(await page.evaluate((n) => window.readBytes(n), `/${name}`)); |
| 84 | + writeFileSync(path, bytes); |
| 85 | + } |
| 86 | + seeds.push([name, new Uint8Array(bytes)]); |
| 87 | +} |
| 88 | + |
| 89 | +console.log(`fuzzing ${names.join(", ")} for ${seconds}s, seed ${seed}`); |
| 90 | +const r = rng(seed); |
| 91 | +const stats = Object.fromEntries(names.map((n) => [n, { cases: 0, crashes: 0 }])); |
| 92 | +const end = Date.now() + seconds * 1000; |
| 93 | +for (let i = 0; Date.now() < end; i++) { |
| 94 | + // A fresh core every so often keeps crash histories short and replayable. |
| 95 | + if (i % 200 === 0 && history.length) { |
| 96 | + history = []; |
| 97 | + await reload(); |
| 98 | + } |
| 99 | + const name = names[i % names.length]; |
| 100 | + const calls = strategies[name].generate(r, seeds); |
| 101 | + stats[name].cases++; |
| 102 | + const failure = await run(calls); |
| 103 | + if (!failure) continue; |
| 104 | + stats[name].crashes++; |
| 105 | + mkdirSync(crashes, { recursive: true }); |
| 106 | + const file = join(crashes, `${name}-${seed}-${i}.json`); |
| 107 | + // `calls` replays everything since the last reload; the last ones crashed. |
| 108 | + writeFileSync(file, JSON.stringify({ strategy: name, seed, iteration: i, failure, results: lastResults, calls: history })); |
| 109 | + history = []; |
| 110 | + console.log(`✗ ${name} case ${i}: ${failure.slice(0, 200)}\n saved ${file}`); |
| 111 | +} |
| 112 | + |
| 113 | +await browser.close(); |
| 114 | +server.close(); |
| 115 | +for (const [name, s] of Object.entries(stats)) console.log(`${name}: ${s.cases} cases, ${s.crashes} crashes`); |
| 116 | +process.exit(Object.values(stats).some((s) => s.crashes) ? 1 : 0); |
0 commit comments