Deobfuscation and MBA
Obfuscators hide simple operations behind mixed boolean-arithmetic (MBA) identities, such as
x + y = (x ^ y) + 2·(x & y), and behind bit shuffles that take a value apart and put it back;
code lifted from a binary also has the compiler’s own disguises, such as divisions by constants
done with multiplications. Strategy::deobfuscate() adds five passes to the standard strategy
for these (hash comparisons through invertible mixers are handled by the standard strategy; see
Invertibility):
- Divisions by constants. The multiply-high sequences a compiler emits for
x / dandx % dbecomeudiv,sdiv,uremandsremagain, when they are proved to be (see below). - Carry networks. Additions and subtractions written out as bitwise operations and shifts
(a parallel-prefix adder, a ripple chain of up to about 40 bits) over up to three atoms
become
x + y,x - yor whatever affine form they compute: the pass reads the form off the network’s values, checks it at a fixed set of points, and commits it only when bitwright’s own prover proves it equal within the pass’s caps (featureprove, on by default; shifts of one atom,2^k·a, need no proof). Arithmetic done in limbs, the carry between them written as a comparison of the low ones, is read too: the high digits and the carry are the high digit of the sum (also the carry out of a middle digit, of a digit computed apart from its word or in another spelling of it, or in a register narrower than the word; where the register is wider than the limb, of the sum with its carry out,zext(a) + zext(b)); limbs of one word under the coefficients of a product are the product of the word; and a limb that is a slice of a word computed below it, or of that word plus a constant the handler added limb by limb, becomes that slice, when proved. A sum several readers read through truncations of their own is read once, at the root, on the bits that reach it. Readings that pay only over the whole expression are taken in a late stage of the rounds, after the words pass has asked. - Linear MBA. A linear combination of bitwise functions of up to six atoms is determined by its values at the corners where every atom is 0 or all ones. The pass computes that signature and emits the cheapest equivalent form it knows, if that is smaller.
- Shuffle. Values assembled from slices of other values (extracts, shifts, masks, concats, ors of disjoint parts) are traced bit by bit, and re-emitted as the rotation, byte swap, extension or plain slice they are.
- Words. Arithmetic done digit by digit (a virtual machine’s handlers working on limbs of
its registers, a multi-precision routine) is read as arithmetic on the words: the digits of
the operands and the carries between them, a product by a constant spread over the limbs, a
constant added limb by limb. Every node is read as an integer form over
floor(x / 2^k)terms kept in one shape, in which the digits cancel; nothing is matched and nothing is proved (see below).
#![allow(unused)]
fn main() {
use bitwright::engine::{Engine, Strategy};
use bitwright::{Context, ParseOptions, Width};
let engine = Engine::builder().builtin().strategy(Strategy::deobfuscate()).build()?;
let mut cx = Context::new();
let o = ParseOptions::width(Width::W32);
for (obfuscated, plain) in [
("(x | y) - (x & y)", "x ^ y"),
("(x & 0xff) + (x & 0xff00) - 2 * (x ^ y) + (x | y) * 2 - 2 * (x & y)", "x & 65535"),
(
"(zext<32>(trunc<8>(x)) << 24) | (zext<32>(extract<8, 8>(x)) << 16) \
| (zext<32>(extract<16, 8>(x)) << 8) | zext<32>(extract<24, 8>(x))",
"bswap(x)",
),
] {
let e = cx.parse(obfuscated, &o)?;
let out = engine.simplify(&mut cx, e)?;
assert_eq!(cx.display(out.expr).to_string(), plain);
}
Ok::<(), Box<dyn std::error::Error>>(())
}
Limb arithmetic
A virtual machine that keeps a 32-bit value as limbs of 12 and 20 bits adds two of them limb by limb: the low limbs at the register’s width, and the high limbs with the carry out of the low ones, which it takes by comparing the low limb of the sum with an operand’s. A product by a constant is done on each limb with its own shift of the constant, and a constant is added in two parts. The pass reads each of these as the operation on the whole value:
#![allow(unused)]
fn main() {
use bitwright::engine::{Engine, Strategy};
use bitwright::{Context, ParseOptions, Width};
let engine = Engine::builder().builtin().strategy(Strategy::deobfuscate()).build()?;
let mut cx = Context::new();
for (limbs, width, word) in [
// The high limb of a sum: the operands' high limbs and the carry of the low ones.
(
"trunc<20>((a:32 >>u 12) + (b:32 >>u 12) + zext<32>((a + b & 4095) <u (a & 4095)))",
20,
"extract<12, 20>(a + b)",
),
// A product by a constant, limb by limb.
("(x & 0xffff) * 0x1234567 + (x >>u 16) * 0x45670000", 32, "x * 0x1234567"),
// A constant added in two parts: the low one to the word, the high one to a slice of it.
("extract<16, 16>(x:32 * 5 + 0x1234) + 0xab", 16, "extract<16, 16>(x * 5 + 0xab1234)"),
// Three registers XORed limb by limb, each limb in its own order.
(
"((a:32 & 4095) ^ (b:32 & 4095) ^ (c:32 & 4095)) \
| (((c >>u 12) ^ (a >>u 12) ^ (b >>u 12)) << 12)",
32,
"a ^ b ^ c",
),
// A register or a constant, chosen limb by limb.
(
"zext<32>(select(t:1, 113, trunc<12>(r:32))) \
| (zext<32>(select(t, 0x352ac, extract<12, 20>(r))) << 12)",
32,
"select(t, 0x352ac071, r)",
),
] {
let e = cx.parse(limbs, &ParseOptions::width(Width::new(width)?))?;
let out = engine.simplify(&mut cx, e)?;
assert_eq!(cx.display(out.expr).to_string(), word);
}
Ok::<(), Box<dyn std::error::Error>>(())
}
Each node’s unsigned value is written as a sum of terms over the integers, among them
floor(F / 2^k) of such sums: a slice is two floors, a sum that wraps is itself less 2^w
times a floor, and x <u y is −floor((x − y) / 2^k). Three identities keep every floor in one
shape, and in that shape the carry above is floor((a + b) / 2^k) − floor(a / 2^k) − floor(b / 2^k): the digits of a and b cancel against it, and what is left is the slice of
a + b. A chain of such operations collapses one after the other. The result is written back
from the root down, each node for all its users at once, wherever that leaves the expression
smaller; where it does not, nothing changes.
An XOR is read as one term of its operands, however many and in whatever order and grouping,
and a slice of it is the XOR of the slices: the limbs of an XOR of 3 registers or of 100 are
the limbs of one value. It is also read as the sum x + y − 2·(x & y), which is how code that
has no XOR instruction spells it and what the carries of arithmetic done on it belong to; a
root is asked with each reading, and the one that leaves it smaller once nothing more is
found is kept. Chains of ANDs and of ORs are read with their operands in one order as well,
so the same operation written twice in two orders is one value.
Divisions by constants
A compiler divides by a constant d by multiplying with a magic number M ≈ 2^k / d and
keeping the high bits (Granlund and Montgomery): for a 32-bit x, x / 3 is
umulhi(x, 0xaaaaaaab) >>u 1. The division pass (Phase::Division) recognizes the forms
compilers use:
umulhi(x, M) >>u s, with a shift of the dividend first for some even divisors, and the add-and-halve form for a multiplier ofW + 1bits:(t + ((x - t) >>u 1)) >>u switht = umulhi(x, M - 2^W);- the product in a register twice as wide, as x86-64 code divides 32-bit values:
trunc<32>((zext<64>(x) * M) >>u (32 + s)), and the high half of a 128-bit product for 64-bit ones; - signed division (C’s
int),smulhiwith an arithmetic shift (and+ xor- xwhere the multiplier’s sign needs it), then a correction by the sign of the quotient (LLVM,q + (q >>u 31)) or of the dividend (GCC,q - (x >>s 31)), for divisors of either sign; - and a remainder computed from such a quotient,
x - d·q, however the sum spells the product.
It does not trust the multiplier to be one. It reads the sequence as an exact function of its
input n: on each interval of n it is floor((a·n + b) / c), an affine function under a
floor, and where the bits of some step wrap around (or a sign bit flips) the interval is split
there. On each interval, such a function equals floor(n / d) everywhere exactly when it does
at no more than eight points (the extremes of an affine function over the pairs of quotient
and remainder), computed with integers wide enough that nothing wraps, so the check covers
every input without trying them. A multiplier that is exact only for a bounded dividend, as
LLVM picks for one with known leading zeros, is accepted where the facts show the bound.
#![allow(unused)]
fn main() {
use bitwright::engine::{Engine, Strategy};
use bitwright::{Context, ParseOptions, Width};
let engine = Engine::builder().builtin().strategy(Strategy::deobfuscate()).build()?;
let mut cx = Context::new();
let o = ParseOptions::width(Width::W32);
for (compiled, source) in [
("umulhi(x, 0xaaaaaaab) >>u 1", "udiv(x, 3)"),
// x % 7: the multiplier 0x124924925 needs 33 bits.
(
"x - 7 * ((umulhi(x, 0x24924925) + ((x - umulhi(x, 0x24924925)) >>u 1)) >>u 2)",
"urem(x, 7)",
),
// x86-64: a 32-bit division in 64-bit registers.
("trunc<32>((zext<64>(x) * 0xaaaaaaab) >>u 33)", "udiv(x, 3)"),
// int division by 7 (LLVM), by -7 and remainder by 5 (GCC).
("((smulhi(x, 0x92492493) + x) >>s 2) + (x >>u 31)", "sdiv(x, 7)"),
("(x >>s 31) - ((smulhi(x, 0x92492493) + x) >>s 2)", "sdiv(x, -7)"),
(
"x - 5 * (trunc<32>((sext<64>(x) * 0x66666667) >>s 33) - (x >>s 31))",
"srem(x, 5)",
),
// Exact for dividends below 2^31 only: kept for any x, divided for x & 0x7fffffff.
("umulhi(x, 0x92492493) >>u 2", "umulhi(x, 0x92492493) >>u 2"),
("umulhi(x & 0x7fffffff, 0x92492493) >>u 2", "udiv(x & 0x7fffffff, 7)"),
] {
let e = cx.parse(compiled, &o)?;
let out = engine.simplify(&mut cx, e)?;
assert_eq!(cx.display(out.expr).to_string(), source);
}
Ok::<(), Box<dyn std::error::Error>>(())
}
Only Strategy::deobfuscate() runs the pass: a division is fewer nodes than its multiply-high
sequence, so in a compiler’s strategy it would undo the strength reduction the compiler did on
purpose.
The MBA service (feature mba)
Nonlinear MBA (products of bitwise terms, for example) needs a solver. The MBA service lowers a
fragment of an expression into a small standalone MbaExpr, asks an MbaSolver, and publishes
the answer only through an evidence gate:
- the answer must have the input’s variables and width and agree with it at 64 points (always): zero, all ones, one, the signed minimum, the constants of both sides and their neighbours, single bit positions, and seeded random values;
- lifted back into the context, it must make the DAG smaller (checked before any proof, so an answer that would be rejected anyway is not proved);
- then evidence, in order: bitwright’s own certificates (below), a configured
EquivalenceProver, the backend’s ownProvedorCertifiedclaim ifMbaTrust::backend_certificatesis set (off by default), or agreement at the sampled points ifMbaTrust::sampledis set (off by default); - the lifted answer must agree with the original at seeded values of its symbols, and pass the usual postconditions and host veto.
bitwright’s certificates are finite evaluation tests, each complete for its fragment:
- linear MBA (only 0 and all-ones constants inside bitwise parts): the values at the corners where every variable is 0 or all ones;
- polynomial MBA (sums of products of bitwise functions, any constants): the points where
the set bits of all variables together lie in at most
dbit positions,dthe most bitwise factors in one product. For(x & y)·(x | y) + (x & ~y)·(~x & y) = x·yat 64 bits that is 18,337 points; - polynomials without bitwise operators: a small grid,
{0, 1, 2}per variable for degree 2; - every assignment when the variables total at most 20 bits;
- anything else through atoms: right shifts, casts and arithmetic under a bitwise operator
are abstracted, paired between the two sides when they are provably equal (also as each
other’s complements,
x − 1and−x, or when an atom’s bits follow a bitwise function of its definition’s leaves), and the two skeletons are compared by one of the tests above; - polynomials over symbols: two sides that expand to the same polynomial in variables,
conjunctions and other bitwise subterms are equal whatever values those take. Where a test
above would take far longer, this is tried first; it never refutes, so the verdict is the
test’s either way (the identity above is the same polynomial over
x,yandx & y, and is proved without its 18,337 points); - carries: expressions built from
+ − ~ & | ^, small left shifts and products by small constants are compared bit by bit, over every carry that can reach each position, which decides them exactly ((y + y) & y & −yis 0 at every width); - when those leave the question open, a bitwise operation with a constant that reads only
known bits of its other operand is read as arithmetic (
−2·(x & 1) | 1is−2·(x & 1) + 1, the low bit being known to be 0), and a variable is split into cases over a few of its bits: the bits it is read through a narrow mask at (x & 1), or the low bits bitwise operations with constants read (x ^ 1), each case proved on its own.
A test is sized before it runs and charged to the pass-work budget; one that does not fit is not
started, and the node is asked again by a later call with more budget. NativeProver offers the
same checks to hosts that use the MBA module directly.
The phase asks about the largest fragment first: the question at the top of a fragment is asked over the fragment as it is, and only when that answer is not taken are the pieces asked, inner ones first, and the top again over them. A piece’s answer can hide what only the whole shows (a relation between two atoms that rewrites one factor of a product identity).
You can supply an MbaCacheStore to share answers across calls; MemoryCache is a
bounded in-memory implementation. The keys include the lowered input, solver and prover
IDs, trust settings and lowering version. Native solvers with and without basis sums use
different IDs, so a shared store cannot substitute one profile’s rendering for the other.
#![allow(unused)]
fn main() {
use std::sync::Arc;
use bitwright::engine::{Engine, Strategy};
use bitwright::mba::{MbaConfig, MbaTrust, MemoryCache, SignatureSolver};
use bitwright::{Context, ParseOptions, Width};
let config = MbaConfig::default().with_trust(
MbaTrust::default(), // the default: only evidence bitwright checks itself
);
let engine = Engine::builder()
.builtin()
.strategy(Strategy::deobfuscate().with_mba(config))
.mba_solver(Arc::new(SignatureSolver)) // linear MBA only, and fast
.mba_cache(Arc::new(MemoryCache::new(4096)))
.build()?;
let mut cx = Context::new();
let e = cx.parse(
"3 * (x & ~y) + 2 * (~x & y) + 5 * (x & y) - (x | y)",
&ParseOptions::width(Width::W64),
)?;
let out = engine.run(&mut cx, &[e], Default::default())?;
assert!(out.stats.mba.calls + out.stats.mba.cache_hits > 0);
// 2·x + y + (x & y): the same function of x and y at every bit.
assert_eq!(cx.display(out.roots[0].expr).to_string(), "(x & y) + (x << 1) + y");
Ok::<(), Box<dyn std::error::Error>>(())
}
NormalFormSolver is bitwright’s own solver beyond linear MBA. It reads bitwise functions
exactly at every width, one truth table per bit class (the positions every constant read by a
bitwise operator treats alike), so constants inside bitwise operators are no obstacle:
(x ^ 0x10) + 2·(x & 0x10) is x + 0x10, and 3·(x & 0x55) + 3·(x & 0xaa) is 3·(x & 0xff).
Products of bitwise terms are multiplied out symbolically, so they cancel exactly:
(x & y)·(x | y) + (x & ~y)·(~x & y) is x·y, 2^63·(x·x + x) is 0 at 64 bits, and a sum that
is a product comes out as one (x·(x & y) + y·(x & y) − (x & y)² is (x | y)·(x & y)).
Subterms it cannot see through become atoms: arithmetic under a bitwise operator (unless it is
secretly a bitwise function), right shifts and casts. Atoms with equal normal forms are one atom,
so ((x ^ y) + 2·(x & y)) & z is (x + y) & z and ((x + y) & z) + ((x + y) & ~z) is x + y.
A bitwise operation with a constant that reads only low bits of a polynomial that are known is
arithmetic again, so (x + y)·(−2·(z & 1) | 1)² is x + y; and an atom’s definition that also
appears outside it is replaced by the atom, so p + x + (x ^ 4) − ((x ^ 4) & p), with p any
polynomial, is x + ((x ^ 4) | p).
Forms are also rendered as sums of two bitwise functions (in forms that share subterms, so
−6·~(x | (y | z)) and the majority (y & z) | (x & (y | z)) share y | z) or three, as a
bitwise function times an odd constant, group by group when their atoms fall apart, with a
bitwise function peeled off, and partly factored, so an obfuscation’s pieces come back as
written: a 33-node obfuscation of (d·a | (a ^ d)) + (a ^ (a + a)) from the QSynth dataset
comes back as exactly that. Atoms that depend on each other are seen through where a certificate
proves it: ((y + 1) & (~y + ~y)) | y | x is x | y, and −(x & −x) is x | −x.
A normal form over at most three atoms is also looked up in a precomputed table of the
smallest expressions, so products the input has multiplied out come back: x·y + x + y + 1 is
~x·~y, and x² + 2·x·y + y² is (x + y)². A form from the table is used only when a
certificate proves it; one that no certificate can decide is returned, if at all, as a
sampled answer (NfOptions::synthesis turns the table off). With the default trust settings
the engine requests no redundant backend proof of an exact rendering; the gate checks it.
MbaConfig::budget bounds the solver’s work in steps for normalization, rendering and
certificate evaluation. An exhausted rendering still costs the work it did. A question
the engine could not settle within budget can be retried later. The solver remembers its
recent answers (NfOptions::memo), which
saves time when the engine asks again and never changes an answer. It is the default solver
(the command line’s simplify uses it too); SignatureSolver answers linear MBA only, at a
fraction of the cost on code that is not obfuscated. Of the 76,080 expressions of CoBRA’s MBA datasets, 75,737 have a ground
truth that agrees with their input: it brings 75,665 of them (99.9 %) to the ground truth’s size
or less, 21,564 smaller, and leaves the rest a few nodes larger (it writes only what it proves
at every input).
CoBRA itself reaches 85.0 % of them. See compare/ in the repository.
#![allow(unused)]
fn main() {
use bitwright::engine::{Engine, Strategy};
use bitwright::mba::MbaConfig;
use bitwright::{Context, ParseOptions, Width};
// The default solver and trust: `NormalFormSolver`, bitwright's own evidence only.
let engine = Engine::builder()
.builtin()
.strategy(Strategy::deobfuscate().with_mba(MbaConfig::default()))
.build()?;
let mut cx = Context::new();
let e = cx.parse("3 * (x & 0x55) + 3 * (x & 0xaa)", &ParseOptions::width(Width::W32))?;
let out = engine.simplify(&mut cx, e)?;
assert_eq!(cx.display(out.expr).to_string(), "(x & 255) * 3");
Ok::<(), Box<dyn std::error::Error>>(())
}
A host can plug in a solver of its own through MbaSolver. ThreadedSolver wraps any solver
with a hard wall-clock deadline per question (a late answer is abandoned and never cached).
Trusting backend certificates means trusting the backend, so it is off by default: answers are
accepted only on bitwright’s own certificates, which cover the fragments above, or on the proof
of an EquivalenceProver the host supplies for the rest. A host that trusts its backend turns
backend_certificates on.
Beyond MBA
Obfuscation rarely comes in one kind. The rest of the library handles what an obfuscator combines with MBA, all in the same run:
- Opaque predicates. A condition whose value follows from the known bits or the ranges of
its operands is folded by the facts, so the dead arm of a branch or a
selectgoes (see Facts and proofs). So is one of number theory, decided by residues: modulo powers of two (x² ≠ 7y² − 1,x·(x + 1)even, an odd square 1 modulo 8) and, where the arithmetic cannot wrap, modulo the divisors of its remainders ((a² + 1) mod 3 ≠ 0for a byte or a shorta). A test of low bits in such a disguise becomes the plain test ((x² & 7) == 1isxodd). - Encoded constants. Multiplications by an odd constant and its inverse, complements that cancel and sums that add up to a constant fold in the linear and rule passes.
- Lifted flags. Sign, overflow, carry and zero flags spelled out bit by bit, and the flags of a floating-point compare, combine back into the one comparison a branch tests.
- Hash checks. A comparison of an invertible keyed mix with a constant becomes one of the key with the preimage (see Invertibility).
- Path conditions. Under assumptions, what the branches taken so far imply is used too, and each result names the assumptions it relied on.
- One value, several spellings (opt in with
strategy.phases.push(Phase::Classes), featureprove). Prover escalation enables this stage; ordinary simplification skips its cost. Every pass recognizes what it solves by form, so two spellings of one value (a parity aspopcntand as a xor of bits, a flag a lifter computed twice,select(c, a, b)besideselect(!c, b, a)) are two unrelated inputs to it. Once the rounds converge, the nodes whose values agree at fixed points, or agree up to a complement, a negation, or a constant added or xored, are proved equal to the smallest of them and written as that relation of it, and the rounds run again; the result is kept where it is smaller. A merged guard is one node, so cases split on it wherever it occurs. - A guard by what it computes (the same stage). A 1-bit value that reads at most 20 bits
of its inputs (the bits the demanded-bits analysis says reach it) is evaluated at all of
them; one that is constant, or true (or false) at a single value of them, becomes that
constant or the equality of those bits with that value. A keyed hash of a byte compared
with a constant, a subset sum of a field’s bits against a target and an MBA over it are
then one spelling,
trunc<8>(x) == 55ort == 0x5a4d, whatever the obfuscator wrote.
#![allow(unused)]
fn main() {
use bitwright::engine::{Engine, Strategy};
use bitwright::mba::MbaConfig;
use bitwright::{Context, ParseOptions, Width};
let engine = Engine::builder()
.builtin()
.strategy(Strategy::deobfuscate().with_mba(MbaConfig::default()))
.build()?;
let mut cx = Context::new();
// An always-true predicate picks an MBA of `x + y` over a decoy, and the choice is multiplied
// by 7 and by 7's inverse modulo 256.
let e = cx.parse(
"select(((x | 1) & 1) == 1, (x ^ y) + 2 * (x & y), x * 0x34) * 7 * 0xb7",
&ParseOptions::width(Width::W8),
)?;
let out = engine.simplify(&mut cx, e)?;
assert_eq!(cx.display(out.expr).to_string(), "x + y");
Ok::<(), Box<dyn std::error::Error>>(())
}
Examples has one section for each of them.
Values by cases
Branch-free code selects a value with arithmetic: a flag times a difference, a mask, a
select hidden in an MBA. Such a value is no constant, and the condition that moves it is
often a needle (a tag against its label, a vendor string, a status code) that no sample of the
inputs meets. cases::decompose simplifies the value, then splits it on the small 1-bit
conditions it contains: each condition replaced by true and by false, each side simplified
and split again, until the leaves are constants or nothing more splits. The tree is exact
(each leaf is the value wherever its path of conditions holds, and the paths partition the
inputs), so Case::to_expr is equal to the value, and Case::values lists the constants a
fully split value takes. A two-way branch, a guarded constant and a chain of case labels all
come out as trees with constant leaves. The conditions of the few selects nearest the value
are split on whatever their size: a check no search decides, a hash of an input or a subset sum
of its bits compared with a constant, becomes the guard of a tree whose leaves are the two
values it chooses between. The prover reports such a check of a question it does not decide as
Unknown::Guarded (see Checking).
#![allow(unused)]
fn main() {
use bitwright::cases::{self, Case};
use bitwright::engine::Engine;
use bitwright::{Context, ParseOptions, Width};
let mut cx = Context::new();
let o = ParseOptions::width(Width::W64);
let e = cx.parse(
"select(trunc<8>(k) == 3, 0x1000, select(trunc<8>(k) == 9, 0x2000, 0x3000)) + 8",
&o,
)?;
let d = cases::decompose(&mut cx, &Engine::standard(), e, None, &cases::Config::default())?;
let values: Vec<u64> = d.cases.values(&cx).unwrap().iter().map(|v| v.to_u64().unwrap()).collect();
assert_eq!(values, [0x1008, 0x2008, 0x3008]);
let Case::Split { guard, .. } = &d.cases else { panic!("a split") };
assert_eq!(cx.display(*guard).to_string(), "trunc<8>(k) == 3");
Ok::<(), Box<dyn std::error::Error>>(())
}
The prover reads questions the same way (Solving): a question its search leaves open, or whose circuit is too large, is split into these cases, and one fails where a search of its few path conditions finds a model.
Synthesis (feature prove)
What no normal form or rule reduces can still have a small equal: synth::synthesize searches
for one, whatever its shape. It enumerates expressions over the input’s variables, the
constants it mentions and a few others (0, 1, all ones, the width less one, the sign bit), by
size, keeping one expression per behavior on a set of sample points; one that behaves like the
input everywhere sampled is proved equal by the native prover, and a counterexample becomes a
sample and the search starts over. An answer is always proved, and always smaller (as a DAG)
than the input. The search is bounded (7 nodes, 4 variables, 64 bits by default), so it suits
the small residue a simplification leaves, not a whole function. Each proof has a budget of SAT
conflicts (Config::conflicts) and of propagations (Config::propagations, unlimited by
default; it bounds a proof’s time more closely); synth::synthesize_report also returns the
candidate, equal at every sample, whose proof it left undecided (Report::unproved).
bitwright simplify --synth runs it on the simplifier’s result (--synth-conflicts,
--synth-propagations).
#![allow(unused)]
fn main() {
use bitwright::engine::Engine;
use bitwright::synth::{Config, synthesize};
use bitwright::{Context, ParseOptions, Width};
let mut cx = Context::new();
let e = cx.parse("((x + y) & 1) ^ (x & 1)", &ParseOptions::width(Width::W32))?;
// The simplifier moves the mask outward; parity reasoning is the synthesizer's.
let out = Engine::standard().simplify(&mut cx, e)?;
assert_eq!(cx.display(out.expr).to_string(), "(x + y ^ x) & 1");
let s = synthesize(&mut cx, out.expr, &Config::default())?.unwrap();
assert_eq!(cx.display(s).to_string(), "y & 1");
Ok::<(), Box<dyn std::error::Error>>(())
}