Spaces:
Running
Running
File size: 4,095 Bytes
443f404 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | /*
* Web Worker: runs Pyodide + the WebAssembly target off the main thread so the
* page stays responsive. The student's Python fuzzer runs here. Progress is
* streamed back to the page via postMessage; "Stop" on the page simply
* terminates and respawns this worker.
*/
importScripts("https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js");
let pyodide = null;
let wasm = null; // exports of target.wasm
// --- bridge functions the Python shim calls (visible from Python as js.*) ---
self.runTargetJS = function (bytes) {
// bytes: a JS Array/TypedArray of ints. Returns {coverage:[...], crashed:int}.
// `crashed` is a BITMASK: bit0 = bug 1, bit1 = bug 2. Either, both, or
// neither bit may be set for a given input.
const mem = new Uint8Array(wasm.memory.buffer); // recompute in case of growth
const inp = wasm.input_ptr();
const n = Math.min(bytes.length, 256);
for (let i = 0; i < 256; i++) mem[inp + i] = 0;
for (let i = 0; i < n; i++) mem[inp + i] = bytes[i] & 0xff;
wasm.run(n);
const cov = wasm.cov_ptr();
const csz = wasm.cov_size();
return {
coverage: Array.from(mem.slice(cov, cov + csz)),
crashed: mem[wasm.crashed_ptr()],
};
};
let lastReport = 0;
self.reportJS = function (execs, corpus, coveredEdges, execsPerSec) {
self.postMessage({
type: "progress",
execs,
corpus,
covered: Array.from(coveredEdges),
numEdges: wasm.cov_size(),
execsPerSec,
});
};
self.saveCrashJS = function (bytes, which) {
const arr = Array.from(bytes, (b) => b & 0xff);
self.postMessage({ type: "crash", bytes: arr, which: String(which) });
};
self.logJS = function (text) {
self.postMessage({ type: "log", text: String(text) });
};
// --- Python bootstrap injected before the student's code ---
const PY_BOOTSTRAP = `
import js, time
from pyodide.ffi import to_js
NUM_EDGES = int(js.runTargetJS(to_js([0])).coverage.length)
SEED = bytes([0x41] * 5) + bytes([0x12, 0x34, 0x56, 0x78]) # wrong magic, offset='A', a generic non-zero count
_t0 = time.time()
def run(data):
"""Execute the target on 'data' (bytes/bytearray/list of ints).
Returns (coverage, crashed):
coverage : list[int] of length NUM_EDGES; coverage[k] = hits on edge k
crashed : int BITMASK. bit0 (value 1) = bug 1 fired on this run;
bit1 (value 2) = bug 2 fired. Either, both, or neither bit
may be set. Falsy (0) means nothing crashed.
"""
res = js.runTargetJS(to_js(list(bytearray(data))))
return list(res.coverage.to_py()), int(res.crashed)
def report(execs, corpus_size, covered_edges):
"""Update the on-screen dashboard. 'covered_edges' is any iterable of the
edge indices your fuzzer has reached so far."""
eps = execs / max(time.time() - _t0, 1e-6)
js.reportJS(int(execs), int(corpus_size),
to_js(sorted({int(e) for e in covered_edges})), float(eps))
def save_crash(data, which):
"""Record a crashing input; the page will offer it as a download.
'which' is a short label identifying which bug this input triggers
(e.g. "bug1" or "bug2") -- used only to show it in the right slot on
the dashboard."""
js.saveCrashJS(to_js(list(bytearray(data))), which)
def log(*args):
js.logJS(" ".join(str(a) for a in args))
`;
async function init() {
pyodide = await loadPyodide();
const resp = await fetch("target/target.wasm");
const { instance } = await WebAssembly.instantiate(
await resp.arrayBuffer(),
{}
);
wasm = instance.exports;
// redirect Python stdout/stderr to the page
pyodide.setStdout({ batched: (t) => self.postMessage({ type: "print", text: t }) });
pyodide.setStderr({ batched: (t) => self.postMessage({ type: "print", text: t }) });
self.postMessage({ type: "ready" });
}
const ready = init();
self.onmessage = async (e) => {
if (e.data.type !== "run") return;
await ready;
try {
await pyodide.runPythonAsync(PY_BOOTSTRAP + "\n" + e.data.code);
self.postMessage({ type: "done" });
} catch (err) {
self.postMessage({ type: "error", text: String(err) });
}
};
|