diff --git a/scripts/benchmark.mjs b/scripts/benchmark.mjs new file mode 100644 index 0000000..9a9fa8f --- /dev/null +++ b/scripts/benchmark.mjs @@ -0,0 +1,109 @@ +// End-to-end timing and output-identity checks. Inputs and reports stay local. +import { createHash } from 'node:crypto'; +import { createReadStream } from 'node:fs'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, relative, resolve } from 'node:path'; +import { performance } from 'node:perf_hooks'; +import { spawnSync } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; + +export function summarize(samples) { + if (samples.length === 0 || samples.some(n => !Number.isFinite(n) || n < 0)) { + throw new Error('timings must contain finite, non-negative samples'); + } + const sorted = [...samples].sort((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return { + minimum_ms: sorted[0], + median_ms: sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2, + p95_ms: sorted[Math.ceil(sorted.length * 0.95) - 1], + }; +} + +export async function fingerprintOutputs(root) { + const files = []; + async function walk(dir) { + const entries = await readdir(dir, { withFileTypes: true }); + entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0); + for (const entry of entries) { + const path = join(dir, entry.name); + if (entry.isSymbolicLink()) throw new Error('benchmark outputs must not contain links'); + if (entry.isDirectory()) { + await walk(path); + } else if (entry.isFile()) { + const hash = createHash('sha256'); + for await (const chunk of createReadStream(path)) hash.update(chunk); + files.push({ path: relative(root, path).replaceAll('\\', '/'), sha256: hash.digest('hex') }); + } else { + throw new Error('benchmark outputs must be regular files'); + } + } + } + await walk(root); + return files; +} + +function positive(value, label) { + if (!/^[0-9]+$/.test(value)) throw new Error(`${label} must be a positive integer`); + const number = Number(value); + if (!Number.isSafeInteger(number) || number < 1) throw new Error(`${label} must be a positive integer`); + return number; +} + +export async function benchmark(cli, input, iterations, caps) { + if (!Number.isSafeInteger(iterations) || iterations < 1 || caps.length === 0 || + caps.some(n => !Number.isSafeInteger(n) || n < 1)) { + throw new Error('benchmark needs positive iterations and at least one positive thread cap'); + } + const results = []; + let reference; + for (const threads of caps) { + const timings = []; + // The first run for each cap is a warm-up, but its bytes are still checked. + for (let iteration = 0; iteration <= iterations; iteration++) { + const output = await mkdtemp(join(tmpdir(), 'senbei-bench-')); + try { + const start = performance.now(); + const child = spawnSync(cli, [input, '--threads', String(threads), '--out', output, + '--no-log', '--no-pause', '--strict-integrity', '-q', '-q'], + { timeout: 600_000, maxBuffer: 1024 * 1024, encoding: 'utf8' }); + const elapsed = performance.now() - start; + if (child.error) throw child.error; + if (child.status !== 0) { + throw new Error(`restore failed for ${threads} thread(s), exit=${child.status}, signal=${child.signal}`); + } + const outputs = await fingerprintOutputs(output); + if (outputs.length === 0) throw new Error('restore produced no outputs; refusing an empty benchmark'); + const identity = JSON.stringify(outputs); + if (reference === undefined) reference = identity; + if (identity !== reference) throw new Error('restored bytes differ across benchmark runs'); + if (iteration > 0) timings.push(elapsed); + } finally { + // Only the new temporary output tree is removed, never the input tree. + await rm(output, { recursive: true, force: true }); + } + } + results.push({ threads, samples_ms: timings, ...summarize(timings) }); + } + return { format_version: 1, input, measurement: 'end_to_end_process_ms', + warmup_runs_per_cap: 1, iterations, outputs: JSON.parse(reference), results }; +} + +async function main(args) { + if (args.length < 2 || args.length > 4) { + throw new Error('usage: node scripts/benchmark.mjs CLI INPUT [ITERATIONS=3] [THREADS=1,2,4]'); + } + const [cli, input, repeat = '3', threadList = '1,2,4'] = args; + const iterations = positive(repeat, 'iterations'); + const caps = [...new Set(threadList.split(',').map(value => positive(value, 'thread count')))]; + const report = await benchmark(resolve(cli), resolve(input), iterations, caps); + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + main(process.argv.slice(2)).catch(error => { + process.stderr.write(`${error.message}\n`); + process.exitCode = 1; + }); +} diff --git a/scripts/benchmark.test.mjs b/scripts/benchmark.test.mjs new file mode 100644 index 0000000..192daca --- /dev/null +++ b/scripts/benchmark.test.mjs @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { benchmark, fingerprintOutputs, summarize } from './benchmark.mjs'; + +test('timings summarize sorted copies with even and odd medians', () => { + const values = [4, 1, 3, 2]; + assert.deepEqual(summarize(values), { minimum_ms: 1, median_ms: 2.5, p95_ms: 4 }); + assert.deepEqual(values, [4, 1, 3, 2]); + assert.deepEqual(summarize([3, 1, 2]), { minimum_ms: 1, median_ms: 2, p95_ms: 3 }); +}); + +test('timings reject empty, negative, and non-finite samples', () => { + for (const values of [[], [-1], [NaN], [Infinity]]) { + assert.throws(() => summarize(values)); + } +}); + +test('benchmark rejects empty work before starting a process', async () => { + for (const [iterations, caps] of [[0, [1]], [1, []], [1, [0]]]) { + await assert.rejects(benchmark('unused', 'unused', iterations, caps)); + } +}); + +test('output fingerprints include sorted relative paths and file bytes', async () => { + const root = await mkdtemp(join(tmpdir(), 'senbei-bench-test-')); + try { + await mkdir(join(root, 'nested')); + await writeFile(join(root, 'z.bin'), 'z'); + await writeFile(join(root, 'nested', 'a.bin'), 'a'); + const hash = value => createHash('sha256').update(value).digest('hex'); + assert.deepEqual(await fingerprintOutputs(root), [ + { path: 'nested/a.bin', sha256: hash('a') }, + { path: 'z.bin', sha256: hash('z') }, + ]); + await writeFile(join(root, 'nested', 'a.bin'), 'changed'); + const changed = await fingerprintOutputs(root); + assert.equal(changed[0].sha256, hash('changed')); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/senbei-cli/src/main.rs b/senbei-cli/src/main.rs index f5bd566..54b1beb 100644 --- a/senbei-cli/src/main.rs +++ b/senbei-cli/src/main.rs @@ -1,5 +1,6 @@ use senbei_engine::android::ResourceLimits; use senbei_io::{job, pause, scan}; +use std::num::NonZeroUsize; use std::path::Path; fn main() -> std::process::ExitCode { @@ -11,7 +12,10 @@ fn main() -> std::process::ExitCode { return std::process::ExitCode::from(2); } }; - let code = execute(&mut options); + let code = match options.threads { + Some(count) => senbei_engine::with_thread_cap(count, || execute(&mut options)), + None => execute(&mut options), + }; if !options.machine { pause::maybe_pause(options.no_pause); } @@ -37,6 +41,7 @@ struct Options { verbose: bool, scan_all: bool, strict_integrity: bool, + threads: Option, limits: ResourceLimits, /// Machine-readable output on stdout and nothing else. machine: bool, @@ -62,6 +67,7 @@ impl Options { let mut verbose = false; let mut scan_all = false; let mut strict_integrity = false; + let mut threads = None; let mut machine = false; let mut dry_run = false; let mut limits = ResourceLimits::default(); @@ -84,6 +90,7 @@ impl Options { "--strict-integrity" => strict_integrity = true, "--json" => machine = true, "--dry-run" => dry_run = true, + "--threads" => threads = Some(parse_thread_cap(args.next().as_deref())?), flag @ ("--max-entry-mib" | "--max-total-mib" | "--max-entries" | "--max-depth") => { set_resource_limit(&mut limits, flag, args.next().as_deref())?; @@ -171,6 +178,7 @@ impl Options { verbose, scan_all, strict_integrity, + threads, limits, machine, dry_run, @@ -178,6 +186,13 @@ impl Options { } } +fn parse_thread_cap(value: Option<&str>) -> Result { + value + .filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())) + .and_then(|text| text.parse().ok()) + .ok_or_else(|| "--threads requires a positive integer argument".to_owned()) +} + /// Run the parsed command. Kept separate from argument parsing and the pause /// prompt so the execution step can be wrapped on its own. fn execute(options: &mut Options) -> u8 { @@ -369,7 +384,7 @@ fn set_resource_limit( fn print_help() { println!( - "senbei [inspect|unpack] [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]" + "senbei [inspect|unpack] [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--threads N] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]" ); println!( " \n\ @@ -395,6 +410,10 @@ fn print_help() { \x20 no log. Android extraction still uses its own temporary\n\ \x20 workspace, which is discarded." ); + println!( + " --threads N positive worker cap for this run. Overrides SENBEI_THREADS;\n\ + \x20 1 selects the sequential path. The environment is unchanged." + ); println!( " --scan-all probe selected .exe/.dll/.so/metadata names below the\n\ \x20 size floor; other filenames remain excluded." @@ -425,6 +444,45 @@ fn print_help() { ); } +#[cfg(test)] +mod thread_options { + use super::*; + + #[test] + fn worker_cap_requires_a_positive_decimal_integer() { + assert_eq!(parse_thread_cap(Some("1")).unwrap().get(), 1); + assert_eq!(parse_thread_cap(Some("4")).unwrap().get(), 4); + for value in [ + None, + Some(""), + Some("0"), + Some("-1"), + Some("+1"), + Some("1.5"), + Some("many"), + Some("999999999999999999999999999999"), + ] { + assert!(parse_thread_cap(value).is_err(), "{value:?}"); + } + } + + #[test] + fn caps_are_optional_and_work_with_both_commands() { + for (args, expected) in [ + (vec!["x"], None), + (vec!["unpack", "x", "--threads", "1"], Some(1)), + (vec!["--threads", "4", "inspect", "x"], Some(4)), + ] { + let Outcome::Run(options) = + Options::parse(args.into_iter().map(str::to_owned)).unwrap() + else { + panic!("expected a parsed command"); + }; + assert_eq!(options.threads.map(NonZeroUsize::get), expected); + } + } +} + #[cfg(test)] mod strict_integrity { use super::exit_code; diff --git a/senbei-cli/tests/threads.rs b/senbei-cli/tests/threads.rs new file mode 100644 index 0000000..e47b8dc --- /dev/null +++ b/senbei-cli/tests/threads.rs @@ -0,0 +1,63 @@ +//! CLI worker-cap parsing and composition with report-only inspection. + +use std::process::Command; + +fn senbei() -> Command { + Command::new(env!("CARGO_BIN_EXE_senbei")) +} + +#[test] +fn rejects_missing_zero_negative_and_overflowing_caps() { + for value in [ + "", + "0", + "-1", + "+1", + "1.5", + "many", + "999999999999999999999999999999", + ] { + let output = senbei() + .args(["--threads", value, "--no-pause"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2), "{value:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains("--threads")); + } + assert_eq!( + senbei().arg("--threads").output().unwrap().status.code(), + Some(2) + ); +} + +#[test] +fn composes_with_inspection_and_machine_output_without_writes() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("plain.bin"); + std::fs::write(&input, b"not a protected image").unwrap(); + for cap in ["1", "4"] { + let output = senbei() + .env("SENBEI_THREADS", "invalid") + .arg("inspect") + .arg(&input) + .args(["--threads", cap, "--json", "--no-pause"]) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty()); + let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["mode"], "inspect"); + assert_eq!(report["format_version"], 1); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); +} + +#[test] +fn help_describes_the_environment_override() { + let output = senbei().arg("--help").output().unwrap(); + assert!(output.status.success()); + let help = String::from_utf8(output.stdout).unwrap(); + assert!(help.contains("--threads N")); + assert!(help.contains("Overrides SENBEI_THREADS")); + assert!(help.contains("sequential")); +} diff --git a/senbei-engine/src/lib.rs b/senbei-engine/src/lib.rs index 277b8b2..5001400 100644 --- a/senbei-engine/src/lib.rs +++ b/senbei-engine/src/lib.rs @@ -4,6 +4,7 @@ pub mod android; mod findings; mod panic_capture; pub mod profile; +mod threading; pub mod windows; pub use panic_capture::catch_unwind_quiet; @@ -12,6 +13,7 @@ pub use profile::{ ProtectionEvidence, ProtectionProfile, RecognitionStatus, RecoveryStatus, TargetFormat, ValidationStatus, }; +pub use threading::{thread_cap, with_thread_cap}; pub use windows::{ Detected, IntegrityFinding, IntegrityReport, IntegritySeverity, Kind, UnpackError, @@ -19,16 +21,3 @@ pub use windows::{ unpack_auto_profiled_v, unpack_auto_v, unpack_dll, unpack_dll_v, unpack_exe, unpack_exe_profiled, unpack_exe_profiled_v, unpack_exe_v, }; - -/// Deterministic worker-thread cap shared by filesystem scanning and engines. -pub fn thread_cap() -> usize { - if let Ok(value) = std::env::var("SENBEI_THREADS") - && let Ok(count) = value.trim().parse::() - && count >= 1 - { - return count; - } - std::thread::available_parallelism() - .map(|count| count.get()) - .unwrap_or(1) -} diff --git a/senbei-engine/src/threading.rs b/senbei-engine/src/threading.rs new file mode 100644 index 0000000..3f7f1e9 --- /dev/null +++ b/senbei-engine/src/threading.rs @@ -0,0 +1,133 @@ +//! Run-scoped worker limits without changing the process environment. + +use std::cell::Cell; +use std::num::NonZeroUsize; + +thread_local! { + static OVERRIDE: Cell> = const { Cell::new(None) }; +} + +/// Deterministic worker-thread cap shared by filesystem scanning and engines. +/// A scoped override takes precedence over `SENBEI_THREADS` and host parallelism. +pub fn thread_cap() -> usize { + if let Some(count) = OVERRIDE.get() { + return count.get(); + } + if let Ok(value) = std::env::var("SENBEI_THREADS") + && let Some(count) = parse_cap(&value) + { + return count.get(); + } + std::thread::available_parallelism() + .map(|count| count.get()) + .unwrap_or(1) +} + +fn parse_cap(value: &str) -> Option { + value.trim().parse().ok() +} + +/// Run a synchronous job with an explicit worker cap on the calling thread. +/// +/// The scanner and unpacker choose their worker counts before spawning workers. +/// This does not mutate the environment or affect unrelated caller threads. A +/// nested scope or unwinding restores the previous cap. Callers that spawn new +/// top-level jobs must apply the scope on those threads as well. +pub fn with_thread_cap(count: NonZeroUsize, run: impl FnOnce() -> R) -> R { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + OVERRIDE.set(self.0); + } + } + let _restore = Restore(OVERRIDE.replace(Some(count))); + run() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn count(n: usize) -> NonZeroUsize { + NonZeroUsize::new(n).unwrap() + } + + #[test] + fn preserves_environment_parsing() { + assert_eq!(parse_cap(" 3 "), Some(count(3))); + for value in [ + "", + "0", + "-1", + "1.5", + "many", + "999999999999999999999999999999", + ] { + assert_eq!(parse_cap(value), None); + } + } + + #[test] + fn nested_scopes_restore_the_previous_cap() { + let before = thread_cap(); + let result = with_thread_cap(count(3), || { + assert_eq!(thread_cap(), 3); + with_thread_cap(count(1), || assert_eq!(thread_cap(), 1)); + assert_eq!(thread_cap(), 3); + 42 + }); + assert_eq!(result, 42); + assert_eq!(thread_cap(), before); + } + + #[test] + fn unwind_restores_the_previous_cap() { + with_thread_cap(count(2), || { + let result = std::panic::catch_unwind(|| { + with_thread_cap(count(7), || panic!("test unwind")); + }); + assert!(result.is_err()); + assert_eq!(thread_cap(), 2); + }); + } + + #[test] + fn sequential_and_parallel_blocks_produce_identical_bytes() { + fn run(workers: usize) -> Vec { + let mut bytes = vec![0; 256]; + let spans: Vec<_> = (0..16).map(|i| (i * 16, (i + 1) * 16)).collect(); + let caller = std::thread::current().id(); + with_thread_cap(count(workers), || { + crate::windows::parallel::parallel_for( + &mut bytes, + &spans, + 1, + |index, base, span| { + assert_eq!(std::thread::current().id() == caller, workers == 1); + for (offset, byte) in span.iter_mut().enumerate() { + *byte = (index ^ (base + offset)) as u8; + } + Ok::<_, ()>(()) + }, + ) + .unwrap(); + }); + bytes + } + assert_eq!(run(1), run(4)); + } + + #[test] + fn concurrent_callers_keep_independent_caps() { + with_thread_cap(count(2), || { + std::thread::scope(|scope| { + let worker = scope.spawn(|| { + with_thread_cap(count(5), || assert_eq!(thread_cap(), 5)); + }); + assert_eq!(thread_cap(), 2); + worker.join().unwrap(); + }); + assert_eq!(thread_cap(), 2); + }); + } +}