mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-24 02:52:47 +08:00
test: add bounded fuzz targets and native-WASM parity
This commit is contained in:
1 parent
e0dc177885
commit
767eae2a79
14 files changed
+1111
-3
No files matched your search
@@ -30,6 +30,16 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- run: cargo test --release --workspace
|
||||
|
||||
fuzz-smoke:
|
||||
# The libFuzzer targets need nightly and are exercised locally (fuzz/run.sh).
|
||||
# This gate only proves the standalone fuzz crate still builds on stable and
|
||||
# that the deterministic bounded smoke corpus completes without a panic.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: cargo check --manifest-path fuzz/Cargo.toml
|
||||
- run: cargo run --release --manifest-path fuzz/Cargo.toml --bin smoke
|
||||
|
||||
check-portable:
|
||||
# Build-only portability gate: non-Windows host and the wasm target the
|
||||
# web build uses. Clippy runs here too, not just on Windows: the platform
|
||||
@@ -81,6 +91,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
- run: cargo install wasm-pack --locked
|
||||
# `-- --locked` forwards to cargo: senbei-wasm/Cargo.lock is committed on
|
||||
# purpose, so the wasm build must be pinned by it rather than silently
|
||||
@@ -88,6 +101,13 @@ jobs:
|
||||
# --out-dir emits the JS/wasm package into the static frontend's web/pkg/.
|
||||
- run: wasm-pack build --target web --release --out-dir ../web/pkg -- --locked
|
||||
working-directory: senbei-wasm
|
||||
- name: Build Node bindings for native/WASM parity
|
||||
run: wasm-pack build --target nodejs --release --out-dir ../target/wasm-parity/pkg -- --locked
|
||||
working-directory: senbei-wasm
|
||||
- name: Compare synthetic native and WASM transforms
|
||||
run: cargo test --release -p senbei-cli --test wasm_parity
|
||||
env:
|
||||
SENBEI_WASM_PARITY: '1'
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: senbei-web
|
||||
|
||||
+10
-1
@@ -157,4 +157,13 @@ target/
|
||||
# the JS/wasm package into web/pkg/ for the static frontend.
|
||||
/senbei-wasm/target/
|
||||
/web/pkg/
|
||||
/web/.playwright-cli
|
||||
/web/.playwright-cli
|
||||
|
||||
### senbei fuzz ###
|
||||
# cargo-fuzz outputs: mutated corpus, crash artifacts, and coverage can contain
|
||||
# bytes derived from user-supplied private corpora. Never commit them.
|
||||
/fuzz/target/
|
||||
/fuzz/artifacts/
|
||||
/fuzz/corpus/
|
||||
/fuzz/coverage/
|
||||
/fuzz/Cargo.lock
|
||||
+3
-2
@@ -10,8 +10,9 @@ members = [
|
||||
]
|
||||
default-members = ["senbei-cli"]
|
||||
# The wasm bindings crate is its own crate (own Cargo.lock, cdylib) and stays
|
||||
# outside the workspace.
|
||||
exclude = ["senbei-wasm"]
|
||||
# outside the workspace. `fuzz` is a cargo-fuzz crate with its own nightly
|
||||
# requirements and must not join workspace builds.
|
||||
exclude = ["senbei-wasm", "fuzz"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
[package]
|
||||
name = "senbei-fuzz"
|
||||
version = "0.0.0"
|
||||
publish = false
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
# Standalone cargo-fuzz crate. It is listed in the workspace `exclude` array
|
||||
# and depends on the parent path crates, so `cargo fuzz` can build it without
|
||||
# changing any workspace manifest.
|
||||
[package.metadata]
|
||||
cargo-fuzz = true
|
||||
|
||||
[dependencies]
|
||||
libfuzzer-sys = "0.4"
|
||||
|
||||
[dependencies.senbei-engine]
|
||||
path = "../senbei-engine"
|
||||
|
||||
[dependencies.senbei-elf]
|
||||
path = "../senbei-elf"
|
||||
|
||||
[dependencies.senbei-metadata]
|
||||
path = "../senbei-metadata"
|
||||
|
||||
[dependencies.senbei-pe]
|
||||
path = "../senbei-pe"
|
||||
|
||||
# A ZIP parser target would duplicate senbei-io's archive preflight, which is
|
||||
# private to that crate. There is no small public seam to reach, so this crate
|
||||
# leaves ZIP fuzzing out rather than re-implementing preflight.
|
||||
|
||||
[[bin]]
|
||||
name = "pe_detect"
|
||||
path = "fuzz_targets/pe_detect.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "pe_integrity"
|
||||
path = "fuzz_targets/pe_integrity.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "pe_parse"
|
||||
path = "fuzz_targets/pe_parse.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "elf_layout"
|
||||
path = "fuzz_targets/elf_layout.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "metadata_parse"
|
||||
path = "fuzz_targets/metadata_parse.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "metadata_restore"
|
||||
path = "fuzz_targets/metadata_restore.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
# Deterministic smoke runner. It exercises the same entry points with bounded
|
||||
# generated inputs, so a build/`cargo check` gate can run without nightly
|
||||
# libFuzzer. `cargo run --manifest-path fuzz/Cargo.toml --bin smoke`.
|
||||
[[bin]]
|
||||
name = "smoke"
|
||||
path = "src/smoke.rs"
|
||||
test = false
|
||||
doc = false
|
||||
@@ -0,0 +1,27 @@
|
||||
#![no_main]
|
||||
|
||||
//! ELF64/AArch64 layout parsing and section-name resolution.
|
||||
//!
|
||||
//! Only structure is checked: no restoration, no filesystem. Input is capped
|
||||
//! because the parser materializes program/section header vectors.
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_INPUT: usize = 1024 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let data = &data[..data.len().min(MAX_INPUT)];
|
||||
if !senbei_elf::is_aarch64_prefix(data) {
|
||||
return;
|
||||
}
|
||||
let _ = senbei_elf::is_aarch64(data);
|
||||
let _ = senbei_elf::load_file_end(data);
|
||||
let Ok(layout) = senbei_elf::ElfLayout::parse(data, false) else {
|
||||
return;
|
||||
};
|
||||
let _ = layout.load_end();
|
||||
let _ = layout.file_load_end();
|
||||
let _ = layout.load_alignment();
|
||||
let _ = layout.section_names(data);
|
||||
let _ = layout.private_section();
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
#![no_main]
|
||||
|
||||
//! il2cpp metadata parsing (structural transform and seed discovery).
|
||||
//!
|
||||
//! Input is capped at 2 MiB: real metadata is large, but a fuzz corpus of
|
||||
//! multi-megabyte blobs slows iteration without reaching new code, and the
|
||||
//! parser's bounds checks are index-driven, not size-driven.
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_INPUT: usize = 2 * 1024 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let data = &data[..data.len().min(MAX_INPUT)];
|
||||
let _ = senbei_metadata::is_metadata(data);
|
||||
let _ = senbei_metadata::deobfuscate(data);
|
||||
let _ = senbei_metadata::android::discover_method_token_seeds(data);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
#![no_main]
|
||||
|
||||
//! Metadata restorers that depend on a decoded module.
|
||||
//!
|
||||
//! The first byte splits the input into a seed selector and the metadata
|
||||
//! bytes, so both `restore_method_tokens` and the v24.1 method-index restore
|
||||
//! get structured-but-arbitrary inputs. Bounded to 2 MiB per iteration.
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_INPUT: usize = 2 * 1024 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let data = &data[..data.len().min(MAX_INPUT)];
|
||||
let Some((&selector, body)) = data.split_first() else {
|
||||
return;
|
||||
};
|
||||
let seed = u32::from(selector);
|
||||
let _ = senbei_metadata::android::restore_method_tokens(body, seed);
|
||||
// The module bytes are attacker-shaped too: an arbitrary "module 0x0C"
|
||||
// must fail validation, never panic.
|
||||
let _ = senbei_metadata::android::restore_method_indices_v24_1(body, body);
|
||||
let _ = senbei_metadata::android::extract_embedded_metadata(body);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
#![no_main]
|
||||
|
||||
//! Crackproof PE detection over bounded, attacker-shaped bytes.
|
||||
//!
|
||||
//! Ceilings: input is capped by the harness (`-max_len`, see run.sh) and the
|
||||
//! detector itself reads only fixed header offsets. This target asserts the
|
||||
//! detector never panics — the folder scanner calls it on untrusted prefixes.
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_INPUT: usize = 64 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let data = &data[..data.len().min(MAX_INPUT)];
|
||||
let _ = senbei_engine::detect(data);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
#![no_main]
|
||||
|
||||
//! Static PE integrity check over arbitrary images.
|
||||
//!
|
||||
//! The checker is documented never to panic on any input; this target enforces
|
||||
//! that. Input is capped so a crafted `SizeOfImage` cannot turn one iteration
|
||||
//! into a multi-gigabyte allocation.
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_INPUT: usize = 512 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let data = &data[..data.len().min(MAX_INPUT)];
|
||||
let report = senbei_engine::check_integrity(data);
|
||||
// Keep the report observable so the optimizer cannot elide the call.
|
||||
std::hint::black_box(report.issues.len());
|
||||
std::hint::black_box(report.findings.len());
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
#![no_main]
|
||||
|
||||
//! PE header/RVA parser over arbitrary bytes.
|
||||
//!
|
||||
//! Exercises `parse`, `sections`, `data_directory`, `rva_to_offset`, and
|
||||
//! `rva_range`. Every failure is an `Err`; a panic is a bug.
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
const MAX_INPUT: usize = 256 * 1024;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let data = &data[..data.len().min(MAX_INPUT)];
|
||||
let Ok(headers) = senbei_pe::parse(data) else {
|
||||
return;
|
||||
};
|
||||
let _ = senbei_pe::sections(data, headers);
|
||||
let _ = senbei_pe::characteristics(data, headers);
|
||||
for index in 0..16u16 {
|
||||
let _ = senbei_pe::data_directory(data, headers, index);
|
||||
}
|
||||
let _ = senbei_pe::rva_to_offset(data, headers, headers.entry_rva);
|
||||
let _ = senbei_pe::rva_range(data, headers, headers.entry_rva, 0x10);
|
||||
let _ = senbei_pe::rva_range(data, headers, u32::MAX, 4);
|
||||
});
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/bin/sh
|
||||
# cargo-fuzz runner with explicit per-target input ceilings.
|
||||
#
|
||||
# The project pins stable Rust in rust-toolchain.toml, while cargo-fuzz and
|
||||
# libFuzzer require nightly. The toolchain is therefore selected explicitly on
|
||||
# every invocation (`cargo +nightly fuzz ...`) so installing nightly does not
|
||||
# change the repository's active toolchain and is not confused with it.
|
||||
#
|
||||
# rustup toolchain install nightly
|
||||
# ./fuzz/run.sh # 60 seconds per target
|
||||
# ./fuzz/run.sh pe_detect 300 # one target, 300 seconds
|
||||
#
|
||||
# libFuzzer execution was not verified in the development environment used for
|
||||
# this harness (`cargo fuzz` was not installed); only the crate build and the
|
||||
# deterministic `smoke` binary were exercised. `--runs`/`-max_total_time` are
|
||||
# passed through unchanged so a caller can choose bounded smoke runs.
|
||||
set -eu
|
||||
|
||||
# Run from the repository root so the script works when invoked by absolute or
|
||||
# relative path from any working directory.
|
||||
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
repo_root=$(dirname -- "$script_dir")
|
||||
cd "$repo_root"
|
||||
|
||||
target=${1:-all}
|
||||
seconds=${2:-60}
|
||||
|
||||
# Ceilings keep one iteration cheap and prevent crafted headers from asking for
|
||||
# a large allocation. They are intentionally generous for real inputs.
|
||||
common="-max_len=2097152 -timeout=10 -rss_limit_mb=4096 -runs=1000000"
|
||||
|
||||
run() {
|
||||
name=$1
|
||||
shift
|
||||
echo "== $name"
|
||||
cargo +nightly fuzz run "$name" -- $common "$@"
|
||||
}
|
||||
|
||||
case "$target" in
|
||||
all)
|
||||
run pe_detect -max_total_time="$seconds"
|
||||
run pe_integrity -max_total_time="$seconds"
|
||||
run pe_parse -max_total_time="$seconds"
|
||||
run elf_layout -max_total_time="$seconds"
|
||||
run metadata_parse -max_total_time="$seconds"
|
||||
run metadata_restore -max_total_time="$seconds"
|
||||
;;
|
||||
pe_detect | pe_integrity | pe_parse | elf_layout | metadata_parse | metadata_restore)
|
||||
run "$target" -max_total_time="$seconds"
|
||||
;;
|
||||
*)
|
||||
echo "unknown target: $target" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Deterministic bounded smoke runner for the fuzz entry points.
|
||||
//!
|
||||
//! `cargo fuzz` needs nightly; this binary needs only the pinned stable
|
||||
//! toolchain. It feeds a fixed, generated set of inputs (valid-ish headers,
|
||||
//! truncations, bit flips, random bytes) through the same calls the libFuzzer
|
||||
//! targets make, with the same size ceilings. A panic is a failure; an `Err`
|
||||
//! is expected and ignored.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo run --manifest-path fuzz/Cargo.toml --bin smoke
|
||||
//! ```
|
||||
//!
|
||||
//! This is a regression gate, not a substitute for fuzzing: coverage-guided
|
||||
//! mutation finds paths this generator does not.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
const MAX_PE: usize = 64 * 1024;
|
||||
const MAX_METADATA: usize = 2 * 1024 * 1024;
|
||||
|
||||
/// Tiny deterministic PRNG (xorshift64*), so the smoke corpus is identical on
|
||||
/// every run and platform.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
let mut x = self.0;
|
||||
x ^= x >> 12;
|
||||
x ^= x << 25;
|
||||
x ^= x >> 27;
|
||||
self.0 = x;
|
||||
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
|
||||
fn byte(&mut self) -> u8 {
|
||||
(self.next() >> 24) as u8
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
if bound == 0 {
|
||||
0
|
||||
} else {
|
||||
(self.next() % bound as u64) as usize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut rng = Rng(0x5EED_1234_ABCD_9876);
|
||||
let mut iterations = 0usize;
|
||||
|
||||
// --- PE-shaped inputs ---------------------------------------------------
|
||||
let mut seeds: Vec<Vec<u8>> = vec![
|
||||
crackproof_pe(false, false),
|
||||
crackproof_pe(true, false),
|
||||
crackproof_pe(false, true),
|
||||
crackproof_pe(true, true),
|
||||
plain_pe(),
|
||||
clean_metadata(),
|
||||
obfuscated_metadata(),
|
||||
];
|
||||
for seed in &seeds {
|
||||
iterations += mutations(seed, &mut rng);
|
||||
}
|
||||
// Pure random blobs of a few sizes.
|
||||
for length in [0usize, 1, 4, 64, 4128, 8192, MAX_PE] {
|
||||
let data: Vec<u8> = (0..length).map(|_| rng.byte()).collect();
|
||||
pe_calls(&data);
|
||||
iterations += 1;
|
||||
}
|
||||
// Truncations and bit flips of each seed.
|
||||
for seed in seeds.clone() {
|
||||
for cut in [0, 1, 2, 3, 4, 8, 16, 4096, seed.len() / 2] {
|
||||
let data = &seed[..cut.min(seed.len())];
|
||||
pe_calls(data);
|
||||
metadata_calls(data);
|
||||
iterations += 1;
|
||||
}
|
||||
}
|
||||
seeds.clear();
|
||||
|
||||
// --- ELF shape ----------------------------------------------------------
|
||||
let elf = minimal_elf();
|
||||
for cut in [0, 4, 6, 16, 64, elf.len()] {
|
||||
elf_calls(&elf[..cut.min(elf.len())]);
|
||||
iterations += 1;
|
||||
}
|
||||
let mut mutated = elf.clone();
|
||||
for _ in 0..256 {
|
||||
let index = rng.below(mutated.len());
|
||||
mutated[index] ^= 1 << (rng.below(8) as u8);
|
||||
}
|
||||
elf_calls(&mutated);
|
||||
iterations += 1;
|
||||
|
||||
println!("fuzz smoke: {iterations} iteration(s), no panic");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn mutations(seed: &[u8], rng: &mut Rng) -> usize {
|
||||
let mut count = 0;
|
||||
pe_calls(seed);
|
||||
metadata_calls(seed);
|
||||
count += 1;
|
||||
for _ in 0..64 {
|
||||
let mut data = seed.to_vec();
|
||||
let flips = 1 + rng.below(8);
|
||||
for _ in 0..flips {
|
||||
let index = rng.below(data.len());
|
||||
data[index] ^= 1 << (rng.below(8) as u8);
|
||||
}
|
||||
let truncate = rng.below(data.len() + 1);
|
||||
data.truncate(truncate);
|
||||
pe_calls(&data);
|
||||
metadata_calls(&data);
|
||||
count += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn pe_calls(data: &[u8]) {
|
||||
let data = &data[..data.len().min(MAX_PE)];
|
||||
let _ = senbei_engine::detect(data);
|
||||
let _ = senbei_engine::check_integrity(data);
|
||||
if let Ok(headers) = senbei_pe::parse(data) {
|
||||
let _ = senbei_pe::sections(data, headers);
|
||||
let _ = senbei_pe::characteristics(data, headers);
|
||||
for index in 0..16u16 {
|
||||
let _ = senbei_pe::data_directory(data, headers, index);
|
||||
}
|
||||
let _ = senbei_pe::rva_to_offset(data, headers, headers.entry_rva);
|
||||
let _ = senbei_pe::rva_range(data, headers, headers.entry_rva, 0x10);
|
||||
let _ = senbei_pe::rva_range(data, headers, u32::MAX, 4);
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata_calls(data: &[u8]) {
|
||||
let data = &data[..data.len().min(MAX_METADATA)];
|
||||
if !senbei_metadata::is_metadata(data) {
|
||||
return;
|
||||
}
|
||||
let _ = senbei_metadata::deobfuscate(data);
|
||||
let _ = senbei_metadata::android::discover_method_token_seeds(data);
|
||||
if let Some((&selector, body)) = data.split_first() {
|
||||
let _ = senbei_metadata::android::restore_method_tokens(body, u32::from(selector));
|
||||
}
|
||||
let _ = senbei_metadata::android::restore_method_indices_v24_1(data, data);
|
||||
let _ = senbei_metadata::android::extract_embedded_metadata(data);
|
||||
}
|
||||
|
||||
fn elf_calls(data: &[u8]) {
|
||||
if !senbei_elf::is_aarch64_prefix(data) {
|
||||
return;
|
||||
}
|
||||
let _ = senbei_elf::is_aarch64(data);
|
||||
let _ = senbei_elf::load_file_end(data);
|
||||
if let Ok(layout) = senbei_elf::ElfLayout::parse(data, false) {
|
||||
let _ = layout.load_end();
|
||||
let _ = layout.section_names(data);
|
||||
}
|
||||
}
|
||||
|
||||
fn crackproof_pe(dll: bool, managed: bool) -> Vec<u8> {
|
||||
const KONN: u32 = 0x4E4E_4F4B;
|
||||
const PE: usize = 0x80;
|
||||
let mut data = vec![0u8; 4096 + 32];
|
||||
data[..2].copy_from_slice(b"MZ");
|
||||
data[0x3C..0x40].copy_from_slice(&(PE as u32).to_le_bytes());
|
||||
data[PE..PE + 4].copy_from_slice(b"PE\0\0");
|
||||
let chars: u16 = if dll { 0x2000 } else { 0 };
|
||||
data[PE + 22..PE + 24].copy_from_slice(&chars.to_le_bytes());
|
||||
data[PE + 20..PE + 22].copy_from_slice(&0xF0u16.to_le_bytes());
|
||||
data[PE + 24..PE + 26].copy_from_slice(&0x20Bu16.to_le_bytes());
|
||||
let directories = PE + 24 + 112;
|
||||
if managed {
|
||||
data[directories + 14 * 8..directories + 14 * 8 + 4]
|
||||
.copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
data[directories + 14 * 8 + 4..directories + 14 * 8 + 8]
|
||||
.copy_from_slice(&0x48u32.to_le_bytes());
|
||||
}
|
||||
data[4096..4100].copy_from_slice(&0u32.to_le_bytes());
|
||||
data[4100..4104].copy_from_slice(&KONN.to_le_bytes());
|
||||
data
|
||||
}
|
||||
|
||||
fn plain_pe() -> Vec<u8> {
|
||||
let mut data = crackproof_pe(false, false);
|
||||
data[4100..4104].copy_from_slice(&0x1234_5678u32.to_le_bytes());
|
||||
data
|
||||
}
|
||||
|
||||
const METADATA_MAGIC: u32 = 0xFAB1_1BAF;
|
||||
|
||||
fn clean_metadata() -> Vec<u8> {
|
||||
metadata(&[
|
||||
0x0600_0001,
|
||||
0x0600_0002,
|
||||
0x0600_0001,
|
||||
0x0600_0002,
|
||||
0x0600_0003,
|
||||
])
|
||||
}
|
||||
|
||||
fn obfuscated_metadata() -> Vec<u8> {
|
||||
metadata(&[
|
||||
0x0600_D49F,
|
||||
0x0600_FFFF,
|
||||
0x0600_1234,
|
||||
0x0600_ABCD,
|
||||
0x0600_5555,
|
||||
])
|
||||
}
|
||||
|
||||
fn metadata(tokens: &[u32; 5]) -> Vec<u8> {
|
||||
const HDR_METHODS: usize = 0x30;
|
||||
const HDR_TYPES: usize = 0xA0;
|
||||
const HDR_IMAGES: usize = 0xA8;
|
||||
let images = 0x100usize;
|
||||
let types = images + 2 * 0x28;
|
||||
let methods = types + 2 * 0x58;
|
||||
let mut data = vec![0u8; methods + tokens.len() * 0x24];
|
||||
let put32 = |data: &mut [u8], offset: usize, value: u32| {
|
||||
data[offset..offset + 4].copy_from_slice(&value.to_le_bytes())
|
||||
};
|
||||
let put16 = |data: &mut [u8], offset: usize, value: u16| {
|
||||
data[offset..offset + 2].copy_from_slice(&value.to_le_bytes())
|
||||
};
|
||||
put32(&mut data, 0, METADATA_MAGIC);
|
||||
put32(&mut data, 4, 31);
|
||||
put32(&mut data, HDR_METHODS, methods as u32);
|
||||
put32(&mut data, HDR_METHODS + 4, (tokens.len() * 0x24) as u32);
|
||||
put32(&mut data, HDR_TYPES, types as u32);
|
||||
put32(&mut data, HDR_TYPES + 4, (2 * 0x58) as u32);
|
||||
put32(&mut data, HDR_IMAGES, images as u32);
|
||||
put32(&mut data, HDR_IMAGES + 4, (2 * 0x28) as u32);
|
||||
put32(&mut data, images + 0x08, 0);
|
||||
put32(&mut data, images + 0x0C, 1);
|
||||
put32(&mut data, images + 0x28 + 0x08, 1);
|
||||
put32(&mut data, images + 0x28 + 0x0C, 1);
|
||||
put32(&mut data, types + 0x24, 0);
|
||||
put16(&mut data, types + 0x40, 2);
|
||||
put32(&mut data, types + 0x58 + 0x24, 2);
|
||||
put16(&mut data, types + 0x58 + 0x40, 3);
|
||||
for (index, token) in tokens.iter().enumerate() {
|
||||
put32(&mut data, methods + index * 0x24 + 0x18, *token);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn minimal_elf() -> Vec<u8> {
|
||||
let mut data = vec![0u8; 0x100];
|
||||
data[..4].copy_from_slice(b"\x7fELF");
|
||||
data[4] = 2; // ELF64
|
||||
data[5] = 1; // little-endian
|
||||
data[6] = 1;
|
||||
data[0x12..0x14].copy_from_slice(&0xB7u16.to_le_bytes()); // AArch64
|
||||
data[0x14..0x18].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[0x18..0x20].copy_from_slice(&0x1000u64.to_le_bytes());
|
||||
data[0x20..0x28].copy_from_slice(&0x40u64.to_le_bytes());
|
||||
data[0x28..0x30].copy_from_slice(&0u64.to_le_bytes());
|
||||
data[0x36..0x38].copy_from_slice(&0x38u16.to_le_bytes());
|
||||
data[0x38..0x3A].copy_from_slice(&0u16.to_le_bytes());
|
||||
data[0x3A..0x3C].copy_from_slice(&0x40u16.to_le_bytes());
|
||||
data[0x3C..0x3E].copy_from_slice(&0u16.to_le_bytes());
|
||||
data
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Native/WASM parity over the same byte API.
|
||||
//!
|
||||
//! The browser binding calls `senbei_io::job::unpack_bytes`,
|
||||
//! `..._force_exe`, `senbei_metadata::deobfuscate`, and
|
||||
//! `senbei_engine::detect`. This test feeds the *same* fixtures to the native
|
||||
//! functions and to a `wasm-pack --target nodejs` build of `senbei-wasm`, and
|
||||
//! compares kind, byte length, SHA-256, remap counts, and suspect state.
|
||||
//!
|
||||
//! What this does NOT prove: it uses synthetic, hand-built fixtures only. It
|
||||
//! says nothing about real protected PE recovery, real Android restoration, or
|
||||
//! arbitrary third-party binaries — those need fixtures in the corpus and are
|
||||
//! deliberately out of scope here.
|
||||
//!
|
||||
//! The test is opt-in because it needs a wasm build:
|
||||
//!
|
||||
//! ```text
|
||||
//! cd senbei-wasm
|
||||
//! wasm-pack build --target nodejs --release --out-dir ../target/wasm-parity/pkg
|
||||
//! cd ..
|
||||
//! SENBEI_WASM_PARITY=1 cargo test --release -p senbei-cli --test wasm_parity
|
||||
//! ```
|
||||
//!
|
||||
//! `SENBEI_WASM_PKG` overrides the package directory; `SENBEI_NODE` overrides
|
||||
//! the node binary. Private-corpus parity can be requested by setting
|
||||
//! `SENBEI_WASM_PARITY_CORPUS=<manifest.json>`: every `pe`/`metadata` case in
|
||||
//! that harness manifest is also compared, still without writing any output.
|
||||
|
||||
#[path = "support/fixtures.rs"]
|
||||
mod fixtures;
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn enabled() -> bool {
|
||||
match std::env::var("SENBEI_WASM_PARITY") {
|
||||
Ok(value) => !matches!(value.trim(), "" | "0"),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn wasm_pkg_dir() -> PathBuf {
|
||||
std::env::var_os("SENBEI_WASM_PKG")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/wasm-parity/pkg")
|
||||
})
|
||||
}
|
||||
|
||||
fn node_binary() -> String {
|
||||
std::env::var("SENBEI_NODE").unwrap_or_else(|_| "node".to_owned())
|
||||
}
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(bytes);
|
||||
digest
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct WasmJob {
|
||||
op: &'static str,
|
||||
input: PathBuf,
|
||||
companion: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Run every job in one Node process and return the parsed result lines.
|
||||
fn run_wasm(jobs: &[WasmJob]) -> Vec<Value> {
|
||||
let driver = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/wasm_parity_driver.mjs");
|
||||
let mut child = Command::new(node_binary())
|
||||
.arg(&driver)
|
||||
.arg(wasm_pkg_dir())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap_or_else(|error| panic!("start node: {error}"));
|
||||
{
|
||||
let stdin = child.stdin.as_mut().expect("stdin");
|
||||
for job in jobs {
|
||||
let line = json!({
|
||||
"op": job.op,
|
||||
"input": job.input.to_string_lossy(),
|
||||
"companion": job.companion.as_ref().map(|path| path.to_string_lossy().to_string()),
|
||||
});
|
||||
writeln!(stdin, "{line}").expect("write job");
|
||||
}
|
||||
}
|
||||
let output = child.wait_with_output().expect("wait for node");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"node driver failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let results: Vec<Value> = text
|
||||
.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.map(|line| serde_json::from_str(line).unwrap_or_else(|e| panic!("bad result {e}: {line}")))
|
||||
.collect();
|
||||
assert_eq!(results.len(), jobs.len(), "one result per job");
|
||||
results
|
||||
}
|
||||
|
||||
fn write_fixture(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wasm_parity_is_opt_in_and_reports_why() {
|
||||
if !enabled() {
|
||||
eprintln!(
|
||||
"wasm parity skipped: set SENBEI_WASM_PARITY=1 and build senbei-wasm \
|
||||
with wasm-pack --target nodejs into target/wasm-parity/pkg"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let pkg = wasm_pkg_dir();
|
||||
assert!(
|
||||
pkg.join("senbei_wasm.js").is_file(),
|
||||
"wasm package not found at {}; build it with wasm-pack",
|
||||
pkg.display()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_byte_transforms_match_wasm() {
|
||||
if !enabled() {
|
||||
eprintln!("wasm parity skipped (SENBEI_WASM_PARITY not set)");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut jobs = Vec::new();
|
||||
let mut native = Vec::new();
|
||||
|
||||
// Detection: every variant plus a non-target.
|
||||
for (name, dll, managed) in [
|
||||
("native-exe.bin", false, false),
|
||||
("native-dll.bin", true, false),
|
||||
("managed-exe.bin", false, true),
|
||||
("managed-dll.bin", true, true),
|
||||
] {
|
||||
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
|
||||
let path = write_fixture(dir.path(), name, &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "detect",
|
||||
input: path,
|
||||
companion: None,
|
||||
});
|
||||
native.push(native_detect(&bytes));
|
||||
}
|
||||
let plain = write_fixture(dir.path(), "plain.bin", &fixtures::synthetic_plain_pe());
|
||||
jobs.push(WasmJob {
|
||||
op: "detect",
|
||||
input: plain,
|
||||
companion: None,
|
||||
});
|
||||
native.push(json!({ "ok": true, "kind": null }));
|
||||
|
||||
// Metadata: clean (idempotent) and obfuscated (5 rewrites).
|
||||
let mut metadata_native = Vec::new();
|
||||
for (name, bytes) in [
|
||||
("clean.dat", fixtures::clean_metadata()),
|
||||
("obfuscated.dat", fixtures::obfuscated_metadata()),
|
||||
] {
|
||||
let path = write_fixture(dir.path(), name, &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "metadata",
|
||||
input: path,
|
||||
companion: None,
|
||||
});
|
||||
let (out, report) = senbei_metadata::deobfuscate(&bytes).unwrap();
|
||||
metadata_native.push(json!({
|
||||
"ok": true,
|
||||
"bytes": out.len(),
|
||||
"sha256": sha256_hex(&out),
|
||||
"version": report.version,
|
||||
"methods": report.methods,
|
||||
"remapped": report.remapped,
|
||||
"modules": report.modules,
|
||||
}));
|
||||
}
|
||||
|
||||
// Metadata probes: both sides must reject with the same error text.
|
||||
let mut probe_native = Vec::new();
|
||||
for (name, bytes) in fixtures::malformed_metadata_probes() {
|
||||
let path = write_fixture(dir.path(), &format!("probe-{name}.dat"), &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "metadata",
|
||||
input: path,
|
||||
companion: None,
|
||||
});
|
||||
probe_native.push(match senbei_metadata::deobfuscate(&bytes) {
|
||||
Ok(_) => json!({ "ok": false, "error": "unexpected success" }),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
}
|
||||
|
||||
// Native unpack for every detection fixture: both sides must agree on the
|
||||
// error wording for these non-protected/header-only inputs.
|
||||
let mut unpack_native = Vec::new();
|
||||
for (name, dll, managed) in [
|
||||
("u-native-exe.bin", false, false),
|
||||
("u-native-dll.bin", true, false),
|
||||
("u-managed-exe.bin", false, true),
|
||||
("u-managed-dll.bin", true, true),
|
||||
] {
|
||||
let bytes = fixtures::synthetic_crackproof_pe(dll, managed);
|
||||
let path = write_fixture(dir.path(), name, &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "unpack",
|
||||
input: path.clone(),
|
||||
companion: None,
|
||||
});
|
||||
unpack_native.push(match senbei_io::job::unpack_bytes(&bytes, None) {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues,
|
||||
"companion": image.companion,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
// Force-exe is the browser's recovery path; it must agree too.
|
||||
let path2 = write_fixture(dir.path(), &format!("{name}.force"), &bytes);
|
||||
jobs.push(WasmJob {
|
||||
op: "unpack_force_exe",
|
||||
input: path2,
|
||||
companion: None,
|
||||
});
|
||||
unpack_native.push(match senbei_io::job::unpack_bytes_force_exe(&bytes, None) {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues,
|
||||
"companion": image.companion,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
}
|
||||
|
||||
let results = run_wasm(&jobs);
|
||||
// Negative control: the driver must have produced a real SHA-256 for the
|
||||
// clean metadata. If the WASM call silently no-op'd, this would not match
|
||||
// the native digest and the control would fail before the loop below.
|
||||
let clean_index = jobs
|
||||
.iter()
|
||||
.position(|job| job.op == "metadata")
|
||||
.expect("metadata jobs exist");
|
||||
let native_clean = &metadata_native[0];
|
||||
assert_eq!(
|
||||
results[clean_index]["sha256"], native_clean["sha256"],
|
||||
"negative control: wasm metadata digest must match native"
|
||||
);
|
||||
let all_native: Vec<Value> = native
|
||||
.into_iter()
|
||||
.chain(metadata_native)
|
||||
.chain(probe_native)
|
||||
.chain(unpack_native)
|
||||
.collect();
|
||||
for (index, (want, got)) in all_native.iter().zip(&results).enumerate() {
|
||||
assert_eq!(
|
||||
want,
|
||||
got,
|
||||
"parity mismatch at job {index} ({}):\nnative {want}\nwasm {got}",
|
||||
jobs.get(index).map(|job| job.op).unwrap_or("?")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn native_detect(bytes: &[u8]) -> Value {
|
||||
match senbei_engine::detect(bytes) {
|
||||
Some(detected) => json!({ "ok": true, "kind": kind_name(detected.kind) }),
|
||||
None => json!({ "ok": true, "kind": null }),
|
||||
}
|
||||
}
|
||||
|
||||
fn kind_name(kind: senbei_engine::Kind) -> &'static str {
|
||||
match kind {
|
||||
senbei_engine::Kind::NativeExe => "native-exe",
|
||||
senbei_engine::Kind::ManagedExe => "managed-exe",
|
||||
senbei_engine::Kind::NativeDll => "native-dll",
|
||||
senbei_engine::Kind::ManagedDll => "managed-dll",
|
||||
}
|
||||
}
|
||||
|
||||
/// Optional: compare private corpus cases as well, when a harness manifest and
|
||||
/// the gate are both provided. Restored bytes still go nowhere.
|
||||
#[test]
|
||||
fn optional_private_corpus_parity() {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
let Some(manifest) = std::env::var_os("SENBEI_WASM_PARITY_CORPUS") else {
|
||||
return;
|
||||
};
|
||||
let manifest = PathBuf::from(manifest);
|
||||
let report = harness_run(&manifest);
|
||||
let base = PathBuf::from(report["manifest"]["base_dir"].as_str().unwrap_or("."));
|
||||
let mut jobs = Vec::new();
|
||||
let mut native = Vec::new();
|
||||
for case in report["cases"].as_array().cloned().unwrap_or_default() {
|
||||
let kind = case["kind"].as_str().unwrap_or("");
|
||||
let status = case["status"].as_str().unwrap_or("");
|
||||
if status != "pass" {
|
||||
continue;
|
||||
}
|
||||
let input = base.join(case["input"].as_str().unwrap_or(""));
|
||||
let companion = case["companion"].as_str().map(|path| base.join(path));
|
||||
match kind {
|
||||
"pe" => {
|
||||
let bytes = std::fs::read(&input).expect("read corpus input");
|
||||
let comp = companion
|
||||
.as_ref()
|
||||
.map(|path| std::fs::read(path).expect("read companion"));
|
||||
jobs.push(WasmJob {
|
||||
op: "unpack",
|
||||
input: input.clone(),
|
||||
companion: companion.clone(),
|
||||
});
|
||||
native.push(
|
||||
match senbei_io::job::unpack_bytes(&bytes, comp.as_deref()) {
|
||||
Ok(image) => json!({
|
||||
"ok": true,
|
||||
"kind": kind_name(image.kind),
|
||||
"bytes": image.bytes.len(),
|
||||
"sha256": sha256_hex(&image.bytes),
|
||||
"suspect": !image.integrity.ok(),
|
||||
"issues": image.integrity.issues,
|
||||
"companion": image.companion,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
},
|
||||
);
|
||||
}
|
||||
"metadata" => {
|
||||
let bytes = std::fs::read(&input).expect("read corpus metadata");
|
||||
jobs.push(WasmJob {
|
||||
op: "metadata",
|
||||
input,
|
||||
companion: None,
|
||||
});
|
||||
native.push(match senbei_metadata::deobfuscate(&bytes) {
|
||||
Ok((out, detail)) => json!({
|
||||
"ok": true,
|
||||
"bytes": out.len(),
|
||||
"sha256": sha256_hex(&out),
|
||||
"version": detail.version,
|
||||
"methods": detail.methods,
|
||||
"remapped": detail.remapped,
|
||||
"modules": detail.modules,
|
||||
}),
|
||||
Err(error) => json!({ "ok": false, "error": error.to_string() }),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if jobs.is_empty() {
|
||||
eprintln!("private corpus parity: no eligible passing cases");
|
||||
return;
|
||||
}
|
||||
let results = run_wasm(&jobs);
|
||||
for (want, got) in native.iter().zip(&results) {
|
||||
assert_eq!(want, got, "private corpus parity mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal in-process harness invocation shared with the example's module.
|
||||
fn harness_run(manifest: &Path) -> Value {
|
||||
#[path = "support/harness.rs"]
|
||||
mod harness;
|
||||
let report = harness::run(
|
||||
manifest,
|
||||
&harness::RunOptions {
|
||||
commit: None,
|
||||
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
},
|
||||
);
|
||||
serde_json::to_value(report).expect("report to JSON")
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Native/WASM parity driver. Reads a JSON job list on stdin and prints one
|
||||
// JSON result per job on stdout. The Rust test starts `node` with this file.
|
||||
//
|
||||
// Job: { "op": "detect" | "unpack" | "unpack_force_exe" | "metadata",
|
||||
// "input": "<path>", "companion": "<path>|null" }
|
||||
// Result: { "ok": true, "kind": ..., "bytes": <n>, "sha256": ...,
|
||||
// "suspect": ..., "issues": [...], "remapped": ... }
|
||||
// or { "ok": false, "error": "..." }
|
||||
//
|
||||
// The wasm package directory is argv[2] (wasm-pack --target nodejs output).
|
||||
//
|
||||
// Isolation: every job runs in a *fresh Node Worker thread* and that worker is
|
||||
// terminated before the next job starts. This matches the browser binding's
|
||||
// disposable-worker architecture: WebAssembly cannot recover from a trap in the
|
||||
// same instance, and a Rust result handle must not survive into the next job.
|
||||
// Worker threads get their own module registry, so requiring the wasm package
|
||||
// inside a worker instantiates a new module each time. Jobs are processed
|
||||
// strictly sequentially so the JSON-lines output order matches the input order.
|
||||
//
|
||||
// A per-job timeout (SENBEI_WASM_PARITY_TIMEOUT_MS, default 120000) bounds a
|
||||
// hung call; on expiry the worker is terminated and the job reports an error.
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createInterface } from "node:readline";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
|
||||
|
||||
function sha256(bytes) {
|
||||
return createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
|
||||
// Runs in a worker: one job, one freshly instantiated module.
|
||||
function runJob(pkgDir, job) {
|
||||
const require = createRequire(import.meta.url);
|
||||
const wasm = require(path.join(pkgDir, "senbei_wasm.js"));
|
||||
let handle;
|
||||
try {
|
||||
if (job.op === "detect") {
|
||||
const bytes = readFileSync(job.input);
|
||||
return { ok: true, kind: wasm.detect(bytes) ?? null };
|
||||
}
|
||||
if (job.op === "unpack" || job.op === "unpack_force_exe") {
|
||||
const input = readFileSync(job.input);
|
||||
const companion = job.companion ? readFileSync(job.companion) : undefined;
|
||||
handle =
|
||||
job.op === "unpack"
|
||||
? wasm.unpack_file(input, companion)
|
||||
: wasm.unpack_file_force_exe(input, companion);
|
||||
const bytes = handle.bytes;
|
||||
return {
|
||||
ok: true,
|
||||
kind: handle.kind,
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
suspect: handle.suspect,
|
||||
issues: handle.issues,
|
||||
companion: handle.companion,
|
||||
};
|
||||
}
|
||||
if (job.op === "metadata") {
|
||||
const data = readFileSync(job.input);
|
||||
handle = wasm.deobfuscate_metadata(data);
|
||||
const bytes = handle.bytes;
|
||||
return {
|
||||
ok: true,
|
||||
bytes: bytes.length,
|
||||
sha256: sha256(bytes),
|
||||
version: handle.version,
|
||||
methods: handle.methods,
|
||||
remapped: handle.remapped,
|
||||
modules: handle.modules,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: `unknown op ${job.op}` };
|
||||
} finally {
|
||||
// The worker is terminated immediately after this, so this is belt and
|
||||
// braces: release the Rust-side allocation without waiting for GC.
|
||||
if (handle && typeof handle.free === "function") {
|
||||
try {
|
||||
handle.free();
|
||||
} catch {
|
||||
// A poisoned instance after a trap can refuse; the worker dies anyway.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function runWorker(pkgDir, job) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const timeoutMs = Number(process.env.SENBEI_WASM_PARITY_TIMEOUT_MS ?? 120000);
|
||||
const worker = new Worker(fileURLToPath(import.meta.url), {
|
||||
workerData: { pkgDir, job },
|
||||
});
|
||||
let timer;
|
||||
const finish = (result) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
// Terminate before reporting: a trapped instance must never be reused.
|
||||
worker.terminate().finally(() => resolve(result));
|
||||
};
|
||||
worker.once("message", (message) => finish(message));
|
||||
worker.once("error", (error) =>
|
||||
finish({ ok: false, error: `worker error: ${error && error.message ? error.message : error}` })
|
||||
);
|
||||
worker.once("exit", (code) => {
|
||||
if (!settled) finish({ ok: false, error: `worker exited without a result (code ${code})` });
|
||||
});
|
||||
if (timeoutMs > 0) {
|
||||
timer = setTimeout(
|
||||
() => finish({ ok: false, error: `worker timed out after ${timeoutMs} ms` }),
|
||||
timeoutMs
|
||||
);
|
||||
timer.unref();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function main(pkgDir) {
|
||||
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
for await (const line of lines) {
|
||||
if (!line.trim()) continue;
|
||||
let job;
|
||||
try {
|
||||
job = JSON.parse(line);
|
||||
} catch (error) {
|
||||
process.stdout.write(JSON.stringify({ ok: false, error: `bad job: ${error}` }) + "\n");
|
||||
continue;
|
||||
}
|
||||
const result = await runWorker(pkgDir, job);
|
||||
process.stdout.write(JSON.stringify(result) + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (isMainThread) {
|
||||
const pkgDir = process.argv[2];
|
||||
if (!pkgDir) {
|
||||
console.error("usage: wasm_parity_driver.mjs <wasm-pkg-dir>");
|
||||
process.exit(2);
|
||||
}
|
||||
main(pkgDir).catch((error) => {
|
||||
console.error(String(error && error.stack ? error.stack : error));
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
let result;
|
||||
try {
|
||||
result = runJob(workerData.pkgDir, workerData.job);
|
||||
} catch (error) {
|
||||
result = { ok: false, error: String(error && error.message ? error.message : error) };
|
||||
}
|
||||
parentPort.postMessage(result);
|
||||
}
|
||||
Reference in new issue
Block a user