angr.analyses.decompiler.pattern_match¶
Fuzzy repeated-code discovery for decompiled functions.
Inlined duplicated code – obfuscator decryption stubs, expanded macros, copies
of an inlined helper – is almost never byte-identical: constants differ per
site and the optimizer reorders and reassociates around them. Exact matching
therefore finds nothing useful, which is why this package canonicalizes an AIL
graph into a token stream (tokenizer) and runs a sparse local
self-alignment over it (align) to recover the near-duplicate families.
Families alone cannot be merged: members that align at 90% still differ
somewhere. exact therefore extracts the sub-ranges on which a family
agrees exactly modulo constants, and dedup outlines those into a single
shared function with the differing constants lifted into parameters.
- class angr.analyses.decompiler.pattern_match.AILCanonicalizer
Bases:
objectRenders AIL statements into canonical shape strings.
- __init__(*, max_depth=5, keep_vvar_category=True, keep_sizes=True, const_mode='abstract', kb=None, block_pos=None, loader=None, skip_conversions=False)
- class angr.analyses.decompiler.pattern_match.AlignParams
Bases:
objectKnobs for the whole pipeline.
- min_votes: int = 5¶
a diagonal needs this many statements of the template voting for it to be aligned, or a quarter of the template’s concrete statements if that is fewer, so small templates are never pruned
- Type:
template search
- __init__(k=4, window=0, max_seed_multiplicity=80, min_anchors=4, max_gap=30, band=16, pad=40, match=3.0, klass_match=1.0, mismatch=-2.0, gap_open=-4.0, gap_extend=-1.0, min_score=40.0, min_identity=0.5, min_size=8, min_occurrences=2, max_candidates=4000, overlap_ratio=0.5, allow_tandem=False, min_votes=5)
- Parameters:
k (int)
window (int)
max_seed_multiplicity (int)
min_anchors (int)
max_gap (int)
band (int)
pad (int)
match (float)
klass_match (float)
mismatch (float)
gap_open (float)
gap_extend (float)
min_score (float)
min_identity (float)
min_size (int)
min_occurrences (int)
max_candidates (int)
overlap_ratio (float)
allow_tandem (bool)
min_votes (int)
- Return type:
None
- class angr.analyses.decompiler.pattern_match.Alignment
Bases:
objectOne fuzzy match between two token ranges.
- a: Interval
- b: Interval
- score: float
- matched: int
- columns: int
- property identity: float
- class angr.analyses.decompiler.pattern_match.Checkpoint
Bases:
objectCalled from inside hot loops, as often as is convenient.
Every
freqcalls it looks at the clock, and at most once perintervalseconds it sleeps forsleepseconds to let other threads take the GIL, as the CFG’s low-priority mode does, and then runscallback. The callback may raise to abort the analysis; a UI uses that to cancel.- __init__(low_priority=True, callback=None, freq=1, interval=0.02, sleep=0.001)
- low_priority
- callback
- freq
- interval
- sleep
- class angr.analyses.decompiler.pattern_match.DedupResult
Bases:
objectWhat
PatternDeduplicatordid.- graph: networkx.DiGraph[Block]
- outlined: list[OutlinedRegion]
- groups: list[MergeGroup]
- property statements_removed: int
Statements actually moved out of the parent.
- __init__(graph, outlined=<factory>, groups=<factory>, skipped=<factory>)
- Parameters:
graph (networkx.DiGraph[Block])
outlined (list[OutlinedRegion])
groups (list[MergeGroup])
- Return type:
None
- class angr.analyses.decompiler.pattern_match.ExactCore
Bases:
objectA range on which several occurrences agree exactly on canonical shapes.
- length: int
- property support: int
- property savings: int
- class angr.analyses.decompiler.pattern_match.Fit
Bases:
IntEnumHow well a node fits a shape. Ordered so
mincombines children.- NONE = 0¶
- KLASS = 1¶
- EXACT = 2¶
- __new__(value)
- class angr.analyses.decompiler.pattern_match.FuzzyPattern
Bases:
objectA family of near-duplicate regions, plus the sub-ranges they share exactly.
- cluster: PatternCluster
- occurrences: list[PatternOccurrence]
- core_occurrences: list[list[PatternOccurrence]]
- property identity: float
- property size: int
- property savings: float
- property sound_savings: int
Tokens removable without changing semantics, i.e. via the exact cores.
- property outlinable_occurrences: list[PatternOccurrence]
- __init__(cluster, occurrences, cores=<factory>, core_occurrences=<factory>)
- Parameters:
cluster (PatternCluster)
occurrences (list[PatternOccurrence])
core_occurrences (list[list[PatternOccurrence]])
- Return type:
None
- class angr.analyses.decompiler.pattern_match.FuzzyPatternFinder
Bases:
AnalysisFind fuzzy repeated code in an AIL graph.
Duplicated inlined code (obfuscator-generated decryption stubs, expanded macros, copies of an inlined helper) is rarely byte-identical: constants differ per site and optimizers reorder and reassociate. Exact matching finds nothing, so this analysis linearizes the graph into a canonical token stream and runs a sparse local self-alignment over it (see
align).Two tiers of result are produced.
patternsholds the fuzzy families, which is what you want to understand a function. Each family also carriescores: the sub-ranges its members agree on exactly, which is what you can soundly merge into a single shared function.- Parameters:
func (
Function) – The function being analyzed.ail_graph (networkx.DiGraph[Block]) – Its AIL graph, e.g.
Decompiler.ail_graph.params (
AlignParams|None) – Alignment knobs; seeAlignParams.disjoint (
bool) – Keep only a non-overlapping subset of families (what outlining needs).all_patternsalways has the full list.min_core_len (
int) – Shortest exact core worth reporting.resolve_calls (
bool) – Render call targets by callee name, which makes calls strong anchors for the aligner.
- __init__(func, ail_graph, *, params=None, disjoint=True, min_core_len=4, min_core_support=2, max_depth=5, const_mode='abstract', skip_labels=True, skip_phis=True, skip_dephi=True, resolve_calls=True, entry=None, low_priority=False, checkpoint=None, statements='any')
- Parameters:
func (Function)
ail_graph (networkx.DiGraph[Block])
params (AlignParams | None)
disjoint (bool)
min_core_len (int)
min_core_support (int)
max_depth (int)
const_mode (str)
skip_labels (bool)
skip_phis (bool)
skip_dephi (bool)
resolve_calls (bool)
entry (Block | None)
low_priority (bool)
checkpoint (Callable[[], None] | None)
statements (str)
- statements
how the statements of one occurrence may follow each other; see STATEMENTS_MODES
- stream: TokenStream
- all_patterns: list[FuzzyPattern]
- patterns: list[FuzzyPattern]
- class angr.analyses.decompiler.pattern_match.Interval
Bases:
objectA half-open token range
[start, end).- start: int
- end: int
- class angr.analyses.decompiler.pattern_match.MergeGroup
Bases:
objectSeveral outlined regions folded into one shared function.
- name: str
- members: list[OutlinedRegion]
- property size: int
- __init__(name, members, lifted_const_indices=<factory>)
- Parameters:
name (str)
members (list[OutlinedRegion])
- Return type:
None
- class angr.analyses.decompiler.pattern_match.PatternCluster
Bases:
objectA group of occurrences of one fuzzy pattern.
- score: float
- identity: float
- property size: int
- property savings: float
every occurrence but one disappears.
- Type:
Tokens removed by outlining
- class angr.analyses.decompiler.pattern_match.PatternDeduplicator
Bases:
AnalysisOutline fuzzy patterns out of a function and merge the provably equal ones.
- Parameters:
func (
Function) – The function being rewritten.ail_graph (networkx.DiGraph[Block]) – Its AIL graph. Not mutated; a copy is rewritten.
patterns (
list[FuzzyPattern]) – Patterns fromFuzzyPatternFinder.granularity (
str) –"core"(default, always mergeable) or"occurrence"(maximum bulk removal).merge (
bool) – Fold provably identical callees into one function.frontier_mode (
str) –"region"outlines exactly the discovered interval;"fallback"(default) additionally retries regions that are not single-entry by letting the Outliner derive its own frontier.max_auto_blocks (
int) – Bound, as a multiple of the region’s block count, on how large a derived frontier may grow.min_auto_ratio (
float) – Smallest fraction of the region a derived frontier may cover before the outline is judged unrelated to the pattern and rolled back.name_prefix (
str) – Prefix for synthesized function names.
- __init__(func, ail_graph, patterns, stream, *, granularity='core', merge=True, name_prefix='fuzzy', vvar_id_start=53248, block_addr_start=2882338816, const_param_stack_base=-65536, min_group_size=2, validate=True, frontier_mode='fallback', max_auto_blocks=3, min_auto_ratio=0.5)
- Parameters:
func (Function)
ail_graph (networkx.DiGraph[Block])
patterns (list[FuzzyPattern])
stream (TokenStream)
granularity (str)
merge (bool)
name_prefix (str)
vvar_id_start (int)
block_addr_start (int)
const_param_stack_base (int)
min_group_size (int)
validate (bool)
frontier_mode (str)
max_auto_blocks (int)
min_auto_ratio (float)
- summary()
- Return type:
- class angr.analyses.decompiler.pattern_match.PatternOccurrence
Bases:
objectOne occurrence of a discovered pattern, with its outlining verdict.
- interval: Interval
- region: Region
- property outlinable: bool
- class angr.analyses.decompiler.pattern_match.Region
Bases:
objectAn interval mapped onto AIL blocks, with its outlinability verdict.
- interval: Interval
- property needs_split: bool
- __init__(interval, block_locs, src_loc, frontier=<factory>, head_split=0, tail_split=0, outlinable=False, reason='')
- class angr.analyses.decompiler.pattern_match.TemplateColumn
Bases:
objectOne leaf of the template and what it landed on.
tokenis the stream position, or None when the leaf was skipped.verifiedis None untilverify()runs, then whether the node’s own structural match accepted the statement.- leaf: int
- fit: Fit
- class angr.analyses.decompiler.pattern_match.TemplateMatch
Bases:
objectOne occurrence of a template in a stream.
- interval: Interval
- score: float
- similarity: float
score over the best score the required leaves could reach, clamped to 1
- identity: float
fraction of required leaves that fit exactly
- columns: list[TemplateColumn]
- property placed_leaves: int
- class angr.analyses.decompiler.pattern_match.TokenLoc
Bases:
objectWhere a token came from.
- block_addr: int
- block_idx: int
- stmt_idx: int
- block_pos: int
- class angr.analyses.decompiler.pattern_match.TokenStream
Bases:
objectA linearized, canonicalized view of an AIL graph.
- blocks: list[Block]
- kb: KnowledgeBase | None = None¶
the knowledge base the callee names were resolved against, for a verifier to reuse
- block_locs_in(start, end)
Block locations touched by tokens
[start, end), in linearization order.
- covers_whole_block(start, end, block_loc)
- __init__(blocks, block_span, locs, shapes, klasses, bags, shape_ids, klass_ids, shape_vocab=<factory>, klass_vocab=<factory>, klass_of_shape=<factory>, kb=None)
- Parameters:
- Return type:
None
- angr.analyses.decompiler.pattern_match.discover(ids, klass_of_shape, params=None, checkpoint=None, segment=None, glue=frozenset({}))
Full pipeline: seed -> chain -> align -> cluster.
checkpointis called from the alignment loops, where the time goes; seepriority.Checkpoint.segmentgives each token a segment number that no occurrence may cross out of, andgluethe shape ids of unconditional jumps, which score nothing and cost nothing to skip.
- angr.analyses.decompiler.pattern_match.find_exact_cores(ids, occurrences, *, min_len=4, min_support=2, max_cores=32)
Greedily extract maximal exactly-shared cores from a fuzzy family.
- angr.analyses.decompiler.pattern_match.find_template_occurrences(pattern, graph, entry, *, kb=None, params=None, ctx=None, checkpoint=None)
Tokenize
graph, search it forpattern, and verify every hit.- Return type:
tuple[TokenStream,list[TemplateMatch]]- Parameters:
pattern (KnownPattern | dsl.PatternNode)
graph (networkx.DiGraph[Block])
entry (Block)
kb (KnowledgeBase | None)
params (AlignParams | None)
ctx (MatchCtx | None)
checkpoint (Callable[[], None] | None)
- angr.analyses.decompiler.pattern_match.linearize(graph, entry)
Reverse post-order from
entry, deterministic, with unreachable blocks appended.RPO keeps single-entry regions contiguous, which is what the Outliner needs. Successors are visited highest address first: the one visited first ends up last, so the body of an
if (err) { ...; return; }, usually the fall-through at the lower address, comes right after its condition instead of at the end of the function.
- angr.analyses.decompiler.pattern_match.match_shape(node, tree)
How well
nodefits the shapetreeof one token.
- angr.analyses.decompiler.pattern_match.materialize(graph, stream, region, block_addr_alloc, *, split_tail=True, idx_alloc=None)
Split the boundary blocks in place so
regionbecomes block-aligned.Returns the
(src_loc, frontier)pair to hand to the Outliner.graphis mutated. Withsplit_tail=Falseonly the head is split, which is what the caller wants when it intends to let the Outliner derive its own frontier: the tail boundary is then chosen by liveness, not by the interval.
- angr.analyses.decompiler.pattern_match.parse_shape(shape)
"Asn(V,Add(V,C))"->("Asn", (("V", ()), ("Add", (("V", ()), ("C", ()))))).
- angr.analyses.decompiler.pattern_match.search(pattern, stream, params=None, checkpoint=None)
Every non-overlapping occurrence of
patterninstreamscoring at leastparams.min_identityin similarity, best first.checkpointis called from the alignment loops; seepriority.Checkpoint.The stream must come from
tokenize_for_templates()(or an equivalentTEMPLATE_TOKENIZERconfiguration), or shapes will not line up with the template’s rendering.- Return type:
list[TemplateMatch]- Parameters:
pattern (KnownPattern | dsl.PatternNode)
stream (TokenStream)
params (AlignParams | None)
checkpoint (Callable[[], None] | None)
- angr.analyses.decompiler.pattern_match.select_disjoint(clusters, overlap_ratio=0.25)
Greedily pick the highest-savings clusters whose occurrences do not collide.
Repeat finding legitimately reports the same code at several granularities (the whole inlined region, and the hot loop inside it). Outlining needs one decision per token, so callers that want to rewrite the graph take this subset while keeping the full list for reporting.
- Return type:
- Parameters:
clusters (list[PatternCluster])
overlap_ratio (float)
- angr.analyses.decompiler.pattern_match.shape_of(node)
The shape a fully concrete node renders to, or None if it has a wildcard.
- Return type:
- Parameters:
node (PatternNode)
- angr.analyses.decompiler.pattern_match.snap(stream, graph, interval, *, allow_split=True, entry_loc=None)
Map
intervalonto blocks and decide whether the Outliner can take it.- Return type:
- Parameters:
stream (TokenStream)
graph (networkx.DiGraph[Block])
interval (Interval)
allow_split (bool)
entry_loc (Address | None)
- angr.analyses.decompiler.pattern_match.template_leaves(pattern)
The template’s leaf statements in stream order.
A statement sequence is already in order. A graph pattern is flattened the way the tokenizer linearizes a function, reverse post-order from the entry, so that a template lifted from a selection lines up with the stream that produced it.
- Return type:
list[PAssign|PStore|PCallStmt|PCondJump|PReturn|PAnyStmt]- Parameters:
pattern (KnownPattern | PatternNode)
- angr.analyses.decompiler.pattern_match.tokenize(graph, entry, *, kb=None, loader=None, max_depth=5, keep_vvar_category=True, keep_sizes=True, const_mode='abstract', skip_labels=False, skip_phis=False, compute_bags=False, skip_conversions=False, skip_dephi=False)
Linearize
graphfromentryand canonicalize every statement into a token.skip_dephileaves out the copies SSA destruction adds (taggeddephi): they appear after the stage the pattern pass runs at, so a pattern must not depend on them.
- angr.analyses.decompiler.pattern_match.tokenize_for_templates(graph, entry, *, kb=None, loader=None)
A stream a template can be searched in: the tokenizer under the template settings.
- Return type:
- Parameters:
graph (networkx.DiGraph[Block])
entry (Block)
kb (KnowledgeBase | None)
- angr.analyses.decompiler.pattern_match.verify(match, pattern, stream, ctx=None, checkpoint=None)
Run every placed leaf’s structural
matchon its statement, sharing one binding environment, and record the outcome on the match.Shapes erase constants, variable identity and sizes below the statement, so a leaf can fit a token’s shape while its
PConst(value=...)or a repeated capture name does not hold. A required leaf that fails leaves the match unverified; an optional one is merely noted on its column.- Return type:
TemplateMatch- Parameters:
match (TemplateMatch)
pattern (KnownPattern | dsl.PatternNode)
stream (TokenStream)
ctx (MatchCtx | None)
checkpoint (Callable[[], None] | None)
Submodules
Fuzzy common-substring discovery over a token stream. |
|
|
|
Tier 2: maximal exactly shared sub-ranges inside a fuzzy family. |
|
|
|
Keeping the pattern analyses from starving other threads, a GUI's in particular. |
|
Turn a token interval into something |
|
|
Every non-overlapping occurrence of |
Bridge between pattern-DSL nodes and the tokenizer's shape alphabet. |
|
Turn an AIL graph into a linear token stream suitable for string algorithms. |