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: object

Renders 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)
Parameters:
statement(stmt, cur_pos=None)
Return type:

str

Parameters:
bag(stmt, max_depth=8)
Return type:

Counter

Parameters:
static klass_of(shape)

Fold operator names in a shape string into operator classes, and variables of any category (VR, VS, …) into V: the same idiom keeps a value in a register in one copy and on the stack in another.

Return type:

str

Parameters:

shape (str)

class angr.analyses.decompiler.pattern_match.AlignParams

Bases: object

Knobs for the whole pipeline.

k: int = 4
window: int = 0
max_seed_multiplicity: int = 80
min_anchors: int = 4
max_gap: int = 30
band: int = 16
pad: int = 40
match: float = 3.0
klass_match: float = 1.0
mismatch: float = -2.0
gap_open: float = -4.0
gap_extend: float = -1.0
min_score: float = 40.0
min_identity: float = 0.5
min_size: int = 8
min_occurrences: int = 2
max_candidates: int = 4000
overlap_ratio: float = 0.5
allow_tandem: bool = False
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:
Return type:

None

class angr.analyses.decompiler.pattern_match.Alignment

Bases: object

One fuzzy match between two token ranges.

a: Interval
b: Interval
score: float
matched: int
columns: int
property identity: float
__init__(a, b, score, matched, columns)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.Checkpoint

Bases: object

Called from inside hot loops, as often as is convenient.

Every freq calls it looks at the clock, and at most once per interval seconds it sleeps for sleep seconds to let other threads take the GIL, as the CFG’s low-priority mode does, and then runs callback. 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)
Parameters:
low_priority
callback
freq
interval
sleep
class angr.analyses.decompiler.pattern_match.DedupResult

Bases: object

What PatternDeduplicator did.

graph: networkx.DiGraph[Block]
outlined: list[OutlinedRegion]
groups: list[MergeGroup]
skipped: list[tuple[Interval, str]]
property statements_removed: int

Statements actually moved out of the parent.

__init__(graph, outlined=<factory>, groups=<factory>, skipped=<factory>)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.ExactCore

Bases: object

A range on which several occurrences agree exactly on canonical shapes.

occurrences: list[Interval]
length: int
property support: int
property savings: int
__init__(occurrences, length)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.Fit

Bases: IntEnum

How well a node fits a shape. Ordered so min combines children.

NONE = 0
KLASS = 1
EXACT = 2
__new__(value)
class angr.analyses.decompiler.pattern_match.FuzzyPattern

Bases: object

A family of near-duplicate regions, plus the sub-ranges they share exactly.

cluster: PatternCluster
occurrences: list[PatternOccurrence]
cores: list[ExactCore]
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:
Return type:

None

class angr.analyses.decompiler.pattern_match.FuzzyPatternFinder

Bases: Analysis

Find 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. patterns holds the fuzzy families, which is what you want to understand a function. Each family also carries cores: 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; see AlignParams.

  • disjoint (bool) – Keep only a non-overlapping subset of families (what outlining needs). all_patterns always 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:
statements

how the statements of one occurrence may follow each other; see STATEMENTS_MODES

stream: TokenStream
all_patterns: list[FuzzyPattern]
patterns: list[FuzzyPattern]
summary(limit=20)

A human-readable report of what was found.

Return type:

str

Parameters:

limit (int)

class angr.analyses.decompiler.pattern_match.Interval

Bases: object

A half-open token range [start, end).

start: int
end: int
overlaps(other)
Return type:

bool

Parameters:

other (Interval)

overlap_len(other)
Return type:

int

Parameters:

other (Interval)

__init__(start, end)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.MergeGroup

Bases: object

Several outlined regions folded into one shared function.

name: str
members: list[OutlinedRegion]
lifted_const_indices: list[int]
property size: int
__init__(name, members, lifted_const_indices=<factory>)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.PatternCluster

Bases: object

A group of occurrences of one fuzzy pattern.

occurrences: list[Interval]
score: float
identity: float
alignments: list[Alignment]
property size: int
property savings: float

every occurrence but one disappears.

Type:

Tokens removed by outlining

spans()
Return type:

list[Interval]

__init__(occurrences, score, identity, alignments=<factory>)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.PatternDeduplicator

Bases: Analysis

Outline 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 from FuzzyPatternFinder.

  • 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:
summary()
Return type:

str

class angr.analyses.decompiler.pattern_match.PatternOccurrence

Bases: object

One occurrence of a discovered pattern, with its outlining verdict.

interval: Interval
region: Region
property outlinable: bool
property block_locs: list[tuple[int, int]]
__init__(interval, region)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.Region

Bases: object

An interval mapped onto AIL blocks, with its outlinability verdict.

interval: Interval
block_locs: list[tuple[int, int]]
src_loc: tuple[int, int]
frontier: set[tuple[int, int]]
head_split: int = 0
tail_split: int = 0
outlinable: bool = False
reason: str = ''
property needs_split: bool
__init__(interval, block_locs, src_loc, frontier=<factory>, head_split=0, tail_split=0, outlinable=False, reason='')
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.TemplateColumn

Bases: object

One leaf of the template and what it landed on.

token is the stream position, or None when the leaf was skipped. verified is None until verify() runs, then whether the node’s own structural match accepted the statement.

leaf: int
token: int | None
fit: Fit
verified: bool | None = None
__init__(leaf, token, fit, verified=None)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.TemplateMatch

Bases: object

One 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]
verified: bool | None = None

every required leaf passed its structural match

Type:

after verify()

captures: dict[str, object]

the capture bindings, by name

Type:

after verify()

property placed_leaves: int
__init__(interval, score, similarity, identity, columns, verified=None, captures=<factory>)
Parameters:
Return type:

None

class angr.analyses.decompiler.pattern_match.TokenLoc

Bases: object

Where a token came from.

block_addr: int
block_idx: int
stmt_idx: int
block_pos: int
ins_addr: int | None
property block_loc: tuple[int, int]
__init__(block_addr, block_idx, stmt_idx, block_pos, ins_addr)
Parameters:
  • block_addr (int)

  • block_idx (int)

  • stmt_idx (int)

  • block_pos (int)

  • ins_addr (int | None)

Return type:

None

class angr.analyses.decompiler.pattern_match.TokenStream

Bases: object

A linearized, canonicalized view of an AIL graph.

blocks: list[Block]
block_span: dict[tuple[int, int], tuple[int, int]]
locs: list[TokenLoc]
shapes: list[str]
klasses: list[str]
bags: list[Counter]
shape_ids: list[int]
klass_ids: list[int]
shape_vocab: list[str]
klass_vocab: list[str]
klass_of_shape: list[int]
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.

Return type:

list[tuple[int, int]]

Parameters:
covers_whole_block(start, end, block_loc)
Return type:

bool

Parameters:
addr_range(start, end)
Return type:

tuple[int | None, int | None]

Parameters:
__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. checkpoint is called from the alignment loops, where the time goes; see priority.Checkpoint. segment gives each token a segment number that no occurrence may cross out of, and glue the shape ids of unconditional jumps, which score nothing and cost nothing to skip.

Return type:

list[PatternCluster]

Parameters:
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.

Return type:

list[ExactCore]

Parameters:
angr.analyses.decompiler.pattern_match.find_template_occurrences(pattern, graph, entry, *, kb=None, params=None, ctx=None, checkpoint=None)

Tokenize graph, search it for pattern, and verify every hit.

Return type:

tuple[TokenStream, list[TemplateMatch]]

Parameters:
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.

Return type:

list[Block]

Parameters:
angr.analyses.decompiler.pattern_match.match_shape(node, tree)

How well node fits the shape tree of one token.

Return type:

Fit

Parameters:
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 region becomes block-aligned.

Returns the (src_loc, frontier) pair to hand to the Outliner. graph is mutated. With split_tail=False only 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.

Return type:

tuple[tuple[int, int], set[tuple[int, int]]]

Parameters:
angr.analyses.decompiler.pattern_match.parse_shape(shape)

"Asn(V,Add(V,C))" -> ("Asn", (("V", ()), ("Add", (("V", ()), ("C", ()))))).

Return type:

tuple[str, tuple[ShapeTree, ...]]

Parameters:

shape (str)

angr.analyses.decompiler.pattern_match.search(pattern, stream, params=None, checkpoint=None)

Every non-overlapping occurrence of pattern in stream scoring at least params.min_identity in similarity, best first. checkpoint is called from the alignment loops; see priority.Checkpoint.

The stream must come from tokenize_for_templates() (or an equivalent TEMPLATE_TOKENIZER configuration), or shapes will not line up with the template’s rendering.

Return type:

list[TemplateMatch]

Parameters:
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:

list[PatternCluster]

Parameters:
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:

str | None

Parameters:

node (PatternNode)

angr.analyses.decompiler.pattern_match.snap(stream, graph, interval, *, allow_split=True, entry_loc=None)

Map interval onto blocks and decide whether the Outliner can take it.

Return type:

Region

Parameters:
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 graph from entry and canonicalize every statement into a token.

skip_dephi leaves out the copies SSA destruction adds (tagged dephi): they appear after the stage the pattern pass runs at, so a pattern must not depend on them.

Return type:

TokenStream

Parameters:
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:

TokenStream

Parameters:
angr.analyses.decompiler.pattern_match.verify(match, pattern, stream, ctx=None, checkpoint=None)

Run every placed leaf’s structural match on 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:

Submodules

align

Fuzzy common-substring discovery over a token stream.

dedup

PatternDeduplicator: outline discovered patterns and merge the sound ones.

exact

Tier 2: maximal exactly shared sub-ranges inside a fuzzy family.

finder

FuzzyPatternFinder: discover fuzzy repeated code in a decompiled function.

priority

Keeping the pattern analyses from starving other threads, a GUI's in particular.

region

Turn a token interval into something Outliner accepts.

search(pattern, stream[, params, checkpoint])

Every non-overlapping occurrence of pattern in stream scoring at least params.min_identity in similarity, best first.

template

Bridge between pattern-DSL nodes and the tokenizer's shape alphabet.

tokenizer

Turn an AIL graph into a linear token stream suitable for string algorithms.