Skip to main content

engine_corpus/
engine_corpus.rs

1//! Runs a directory of simplifier inputs through an engine and prints, for each, its time in
2//! milliseconds, the result's reachable DAG nodes and its constant value, if any.
3//!
4//! `cargo run --release --example engine_corpus --no-default-features --features mba,prove -- DIR`
5//!
6//! Each file holds `# engine: deep|forms|...` and `# fuel: N` lines and, after `## root 0`, the
7//! expression in Bitwright's text form (as a devirtualizer's `--export-questions` writes them
8//! under `engine/`). Supply width-annotated symbols for mixed-width inputs. The default
9//! is the host's inline profile (no basis sums, kept steps 2^12); `DIR --default-strategy`
10//! uses the ordinary deobfuscation profile. Neither reconstructs omitted assumptions.
11use std::sync::Arc;
12
13use bitwright::engine::{Budget, Engine, Run, Strategy};
14use bitwright::mba::{MbaConfig, MbaSolver, NfOptions, NormalFormSolver};
15use bitwright::{Bounded, Context, ParseOptions, View, Width};
16
17fn stock() -> MbaConfig {
18    MbaConfig::default().with_opaque_sweep(true)
19}
20
21fn forms() -> MbaConfig {
22    stock().with_noise_forms(true).with_known_atoms(true)
23}
24
25fn main() {
26    let mut args = std::env::args_os().skip(1);
27    let dir = args.next().expect("directory [--default-strategy]");
28    let default_strategy = match args.next() {
29        None => false,
30        Some(arg) if arg == "--default-strategy" && args.next().is_none() => true,
31        _ => panic!("usage: engine_corpus DIR [--default-strategy]"),
32    };
33    let mut files: Vec<_> = std::fs::read_dir(&dir)
34        .expect("read dir")
35        .filter_map(|e| e.ok().map(|e| e.path()))
36        .collect();
37    files.sort();
38    let solver: Arc<dyn MbaSolver> = Arc::new(NormalFormSolver::new(
39        NfOptions::default()
40            .with_memo(1 << 14)
41            .with_basis_sums(default_strategy),
42    ));
43    let build = |m| {
44        let strategy = Strategy::deobfuscate().with_mba(m);
45        let strategy = if default_strategy {
46            strategy
47        } else {
48            strategy.with_basis_sums(false).with_kept_steps(1 << 12)
49        };
50        Engine::builder()
51            .builtin()
52            .strategy(strategy)
53            .mba_solver(Arc::clone(&solver))
54            .build()
55            .unwrap()
56    };
57    let (stock_engine, forms_engine) = (build(stock()), build(forms()));
58    let mut missing_assumptions = 0usize;
59    for f in files {
60        let mut cx = Context::new();
61        let text = std::fs::read_to_string(&f).unwrap();
62        if text.lines().any(|line| line == "# assumptions: true") {
63            missing_assumptions += 1;
64        }
65        let what = text
66            .lines()
67            .find_map(|l| l.strip_prefix("# engine: "))
68            .unwrap_or("deep")
69            .to_owned();
70        let fuel: u64 = text
71            .lines()
72            .find_map(|l| l.strip_prefix("# fuel: "))
73            .and_then(|v| v.parse().ok())
74            .unwrap_or(1 << 19);
75        let Some(root) = text.split("## root 0\n").nth(1) else {
76            continue;
77        };
78        let e = match cx.parse(root.trim(), &ParseOptions::width(Width::W64)) {
79            Ok(e) => e,
80            Err(err) => {
81                println!("{} parse-error {err}", f.display());
82                continue;
83            }
84        };
85        let engine = if what == "forms" {
86            &forms_engine
87        } else {
88            &stock_engine
89        };
90        let t = std::time::Instant::now();
91        let out = engine.run(
92            &mut cx,
93            &[e],
94            Run::default().with_per_call(Budget::fuel(fuel)),
95        );
96        let ms = t.elapsed().as_secs_f64() * 1e3;
97        let name = f.file_name().unwrap().to_string_lossy();
98        let o = match out {
99            Ok(o) => o,
100            Err(err) => {
101                println!("{name} {what} {ms:.2} error={err}");
102                continue;
103            }
104        };
105        let r = o.roots[0].expr;
106        let Bounded::Exact(nodes) = cx.dag_size(&[r], u32::MAX).expect("a result") else {
107            unreachable!("the arena's node indices fit in u32")
108        };
109        match cx.view(r).expect("a result") {
110            View::Const(v) => println!("{name} {what} {ms:.2} nodes={nodes} constant={v}"),
111            _ => println!("{name} {what} {ms:.2} nodes={nodes} constant=-"),
112        }
113    }
114    if missing_assumptions > 0 {
115        eprintln!("{missing_assumptions} inputs marked as assumed were replayed unconstrained");
116    }
117}