angr.analyses.decompiler

class angr.analyses.decompiler.AILSimplifier

Bases: Analysis

Perform function-level simplifications.

__init__(func, func_graph, ail_manager, remove_dead_memdefs=False, stackarg_offset_manager=None, unify_variables=False, gp=None, narrow_expressions=False, fold_expressions=True, only_consts=False, fold_callexprs_into_conditions=False, use_callee_saved_regs_at_return=True, rewrite_ccalls=True, rename_ccalls=True, rewrite_dirty=True, removed_vvar_ids=None, arg_vvars=None, avoid_vvar_ids=None, secondary_stackvars=None, remove_dead_assignments=True)
Parameters:
class angr.analyses.decompiler.BaseStructuredCodeGenerator

Bases: object

__init__(flavor=None, notes=None, expr_comments=None, stmt_comments=None, const_formats=None)
static adjust_mapping_positions(offset, pos_to_node, pos_to_addr, addr_to_pos)

Adjust positions in the mappings to account for the notes that are prepended to the text.

Parameters:
  • offset (int) – The length of the notes to prepend.

  • pos_to_node (PositionMapping) – The position to node mapping.

  • pos_to_addr (PositionMapping) – The position to address mapping.

  • addr_to_pos (InstructionMapping) – The address to position mapping.

Return type:

tuple[PositionMapping, PositionMapping, InstructionMapping]

Returns:

Adjusted mappings.

reapply_options(options)
regenerate_text()
Return type:

None

reload_variable_types()
Return type:

None

next_ident(key)
Return type:

str

Parameters:

key (str)

reset_ident_counters()
Return type:

None

next_node_idx()
Return type:

int

class angr.analyses.decompiler.BlockSimplifier

Bases: object

Simplify an AIL block.

Deliberately not an Analysis: it is instantiated once per block, hundreds of times per decompilation, so it skips the analysis-factory ceremony. Instantiate it directly with the project as the first argument; exceptions always propagate.

__init__(project, block, ail_manager, func_addr=None, stack_pointer_tracker=None, peephole_optimizations=None, preserve_vvar_ids=None, type_hints=None, cached_propagator=None, peephole_bundle=None, graph_defs=None)
Parameters:
static replace_and_build(block, replacements, ail_manager, replace_assignment_dsts=False, replace_loads=False, gp=None, replace_registers=True, max_expr_depth=13, max_stmt_size=20000)
Return type:

tuple[bool, Block]

Parameters:
class angr.analyses.decompiler.CStructuredCodeGenerator

Bases: BaseStructuredCodeGenerator, Analysis, Serializable

__init__(func, sequence, indent=0, cfg=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False, min_data_addr=4194304, notes=None, display_notes=True, max_str_len=None, prettify_thiscall=False, cstyle_void_param=True, indent_size=4, variable_map=None, stl_accessor_calls=False, func_prototype=None)
Parameters:
reapply_options(options)
cleanup()

Remove existing rendering results.

regenerate_text()

Re-render text and re-generate all sorts of mapping information.

Return type:

None

render_text(cfunc)
Return type:

RenderResult

Parameters:

cfunc (CFunction)

render_notes()

Render decompilation notes.

Return type:

str

Returns:

A string containing all notes.

reload_variable_types()
Return type:

None

default_simtype_from_bits(n, signed=True)
Return type:

SimType

Parameters:
variables_unify(v1, v2)
Return type:

bool

Parameters:
ERRNO_LOCATION_FUNCS = frozenset({'__errno', '__errno_location', '__error', '_errno'})

The libc functions that return &errno. errno is a macro that dereferences one of them, so it never survives into a binary as a symbol; what reaches decompilation is *(__errno_location()), which is both correct and unreadable.

class angr.analyses.decompiler.CallSiteMaker

Bases: object

Add calling convention, declaration, and args to a call site.

__init__(project, block, *, ail_manager, reaching_definitions=None, stack_pointer_tracker=None, x87_call_ftop=None, flavor=Flavors.DEFAULT_FLAVOR)
Parameters:
class angr.analyses.decompiler.Clinic

Bases: Analysis, Serializable

A Clinic deals with AILments: it lifts a function to AIL and runs the decompiler’s simplification pipeline on it.

AIL graphs exposed after a DECOMPILE-mode run:

  • cc_graph: the graph at the end of Clinic’s own simplification, frozen as a copy before region identification. Serialized; available on both live and cached-and-reloaded clinics.

  • graph: cc_graph further transformed by the decompiler’s graph-simplification passes, region identification, and region-simplification passes — the final graph. Serialized; available on both live and cached-and-reloaded clinics.

  • unoptimized_graph: a copy taken before the first structure-altering optimization pass; use it for an exact instruction-to-AIL mapping. Only built (and serialized) with Decompiler(save_unoptimized_graph=True); otherwise it is None on both live and cached-and-reloaded clinics.

  • _ail_graph / _init_ail_graph: pipeline internals; never serialized.

CROSS_INSN_OPT_MIN_BLOCK_SIZE = 99

lift a block with cross-insn-opt only when it contains at least this many bytes

CROSS_INSN_OPT_MIN_LARGE_BLOCK_COUNT = 400

…and only in functions with at least this many such blocks

CROSS_INSN_OPT_MAX_BINOP_COUNT = 3

…and it has fewer BinOps than this in total

CROSS_INSN_OPT_MIN_STRIDE_REPEATS = 30

…and only when the block contains this many consecutive repeating byte strides

CROSS_INSN_OPT_MAX_STRIDE = 4

longest byte stride when looking for repeating patterns

__init__(func, remove_dead_memdefs=False, exception_edges=False, sp_tracker_track_memory=True, fold_expressions=True, fold_callexprs_into_conditions=False, insert_labels=True, optimization_passes=None, cfg=None, peephole_optimizations=None, must_struct=None, reset_variable_names=False, rewrite_ites_to_diamonds=True, rewrite_ites_to_diamond_max_cases=15, cache=None, mode=ClinicMode.DECOMPILE, sp_shift=0, inline_functions=None, inlined_counts=None, inlining_parents=None, vvar_id_start=0, optimization_scratch=None, desired_variables=None, force_loop_single_exit=True, refine_loops_with_single_successor=False, expose_loop_head_backedges=False, force_single_loop_entry=False, typehoon_cls=<class 'angr.analyses.typehoon.typehoon.Typehoon'>, max_ail_statements=1000000, max_type_constraints=100000, type_constraint_set_degradation_threshold=150, ail_graph=None, arg_vvars=None, start_stage=ClinicStage.INITIALIZATION, end_stage=None, skip_stages=(), notes=None, static_vvars=None, static_buffers=None, flatten_args=False, constrain_callee_prototypes=False, upgrade_hidden_ptrarg_to_retval=False, semvar_naming=True, flavor=Flavors.DEFAULT_FLAVOR, variable_map=None, save_unoptimized_graph=False, known_patterns=None, recognize_known_patterns=True)
Parameters:
decompiled_prototype: SimTypeFunction | None

the prototype that this function was decompiled against.

block(addr, size)

Get the converted block at the given specific address with the given size.

Parameters:
Returns:

dbg_repr()
Returns:

calculate_stack_depth()
copy_graph(graph=None)
Return type:

DiGraph

MAX_CALLEE_CLEANUP_SUBSET_CANDIDATES = 4
block_lifted_with_cross_insn_opt(block_addr, block_size)
Return type:

bool

Parameters:
  • block_addr (int)

  • block_size (int)

static repeating_stride_run(data, max_stride)

The longest run of consecutive repetitions of up to max_stride bytes in data.

Return type:

int

Parameters:
static binop_count(block)

The number of binary operations across all statements of block.

Return type:

int

Parameters:

block (Block)

parse_variable_addr(addr)
Return type:

tuple[Any, Any]

Parameters:

addr (Expression)

new_block_addr()

Return a block address that does not conflict with any existing blocks.

Return type:

int

Returns:

The block address.

static remove_empty_nodes(graph)
Return type:

DiGraph

Parameters:

graph (DiGraph)

constrain_callee_prototypes()

Constrain the types of callee function arguments based on facts that are observed at call sites. Note that this function will change the prototypes of (callee) functions in the knowledge base, which means it may affect the decompilation output of the current function if it is decompiled again.

resolve_peephole_optimizations()

Retry resolving peephole-optimization names that were unresolvable at parse time (their defining module may have been imported since). Resolved classes move into peephole_optimizations; names that still do not resolve stay in unresolvable_peephole_optimizations.

Return type:

None

classmethod parse_from_cmessage(cmsg, *, project=None, kb=None, function=None, cfg=None, **kwargs)

Bypasses Clinic.__init__() (which runs the analysis) and reconstructs the instance directly. Runtime back-references — project / kb / function / _cfg — come from kwargs.

Only the state consumed by the decompiler’s cache-reuse path and by post-decompilation consumers (cc_graph, graph, optionally unoptimized_graph) is serialized; regenerable and runtime-only state is restored to its default here. If function is None and kb is provided, the function is resolved by address from the cmessage.

class angr.analyses.decompiler.ClinicMode

Bases: Enum

Analysis mode for Clinic.

DECOMPILE = 1
COLLECT_DATA_REFS = 2
class angr.analyses.decompiler.DecompilationCache

Bases: Serializable

Caches key data structures that can be used later for refining decompilation results, such as retyping variables.

__init__(addr)
parameters: dict[str, Any]
version: str
timestamp: int
addr
cfg: CFGModel | None
type_constraints: dict[TypeVariable, set[TypeConstraint]]
arg_vvars: dict
func_typevar: TypeVariable | None
var_to_typevar: dict
stackvar_max_sizes: dict
stack_offset_typevars: dict
codegen: BaseStructuredCodeGenerator | None
clinic: Clinic | None
variable_map: VariableMap | None
ite_exprs: set[tuple[int, Expression]]
binop_operators: dict[OpDescriptor, str]
errors: list[str]
function_summary: str | None
notes: dict[str, DecompilationNote]
max_tv_id: int
go_sigs_version: int | None
go_sigs_deps: dict[str, int] | None
property local_types
classmethod parse_from_cmessage(cmsg, *, project=None, kb=None, function=None, cfg=None, **_)

Parse a DecompilationCache from a cmessage. Runtime back-references (project, kb, function, cfg) are passed through to the embedded Clinic / codegen parsers so the parsed cache is functional for cache-hit validity checks. Decompilation variables live on kb.dec_variables.

class angr.analyses.decompiler.Decompiler

Bases: Analysis

The decompiler analysis.

Run this on a Function object for which a normalized CFG has been constructed. The fully processed output can be found in result.codegen.text

AIL graphs exposed on the result (both on a fresh run and on a cache hit, including caches reloaded from angrdb or the runtime-db spill):

  • ail_graph (= clinic.cc_graph): the simplified graph before region identification.

  • clinic.graph: the final graph after region identification and region simplification.

  • unoptimized_ail_graph (= clinic.unoptimized_graph): a snapshot before the first structure-altering optimization pass; use it for an exact instruction-to-AIL mapping. Only built when save_unoptimized_graph=True is passed; otherwise this attribute is None on both fresh runs and cache hits.

Complexity guard: pathologically large functions (e.g. packer filler that linear disassembly turns into thousands of blocks) can keep the pipeline busy indefinitely, so two size limits are checked before the expensive work starts. max_function_blocks (default 50000, DEFAULT_MAX_FUNCTION_BLOCKS) bounds the number of CFG basic blocks and is checked before any AIL is built; max_ail_statements (default 1000000, DEFAULT_MAX_AIL_STATEMENTS) bounds the number of AIL statements and is checked right after the AIL graph is built. Both are ~10x the largest function in angr’s test binary corpus. Either limit can be changed through the decompilation option of the same name, and setting one to 0 disables it. When a limit is exceeded, decompilation stops with an AngrDecompilationComplexityError naming the limit and the actual size: with fail_fast=True it is raised, otherwise it is recorded in self.errors (and in kb.decompilations[...].errors) and exposed as complexity_error, and codegen stays None.

The optimization passes come from preset (a name or a DecompilationPreset), or from an explicit optimization_passes list when no preset is given. disable_opts drops individual passes from the preset’s list, which is how a caller asks for “this preset, minus that one pass” without restating it.

__init__(func, cfg=None, options=None, preset=None, optimization_passes=None, disable_opts=None, sp_tracker_track_memory=True, peephole_optimizations=None, vars_must_struct=None, flavor=Flavors.DEFAULT_FLAVOR, expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=False, inline_functions=None, desired_variables=None, update_memory_data=True, want_full_graph=False, generate_code=True, use_cache=True, update_cache=True, expr_collapse_depth=16, clinic_graph=None, clinic_arg_vvars=None, clinic_start_stage=None, clinic_end_stage=None, clinic_skip_stages=(), static_vvars=None, static_buffers=None, codegen_cls=<class 'angr.analyses.decompiler.structured_codegen.c.CStructuredCodeGenerator'>, save_unoptimized_graph=False, go_sigs_rerun=True)
Parameters:
property complexity_error: AngrDecompilationComplexityError | None

The complexity-limit violation that aborted this decompilation, or None if no limit was exceeded. Inspect limit_name, limit, and actual on it to decide whether to raise the limit or skip the function.

reflow_variable_types(cache)

Re-run type inference on an existing variable recovery result, then rerun codegen to generate new results.

Returns:

Parameters:

cache (DecompilationCache)

find_data_references_and_update_memory_data(seq_node)
Parameters:

seq_node (SequenceNode)

transform_graph_from_ssa(ail_graph)

Translate an SSA AIL graph out of SSA form. This is useful for producing a non-SSA AIL graph for displaying in angr management.

Parameters:

ail_graph (DiGraph) – The AIL graph to transform out of SSA form.

Return type:

DiGraph

Returns:

The translated AIL graph.

transform_seqnode_from_ssa(seq_node)
Return type:

SequenceNode

Parameters:

seq_node (SequenceNode)

llm_refine()

Use the configured LLM to suggest improved variable names, function names, and variable types. Returns True if any changes were made.

Return type:

bool

llm_suggest_variable_names(llm_client=None, code_text=None, raise_exc=False)

Ask the LLM to suggest better variable names for the decompiled code. Returns True if any variables were renamed.

Parameters:
  • raise_exc (bool) – If True, exceptions from the LLM call are propagated to the caller. If False (default), exceptions are caught and the method returns False.

  • code_text (str | None)

Return type:

bool

llm_suggest_function_name(llm_client=None, code_text=None, raise_exc=False)

Ask the LLM to suggest a better function name. Only suggests rename for auto-generated names (starting with sub_ or fcn.). Returns True if the function was renamed.

Parameters:
  • raise_exc (bool) – If True, exceptions from the LLM call are propagated to the caller.

  • code_text (str | None)

Return type:

bool

llm_suggest_variable_types(llm_client=None, code_text=None, raise_exc=False)

Ask the LLM to suggest better C types for variables. Returns True if any variable types were changed.

Parameters:
  • raise_exc (bool) – If True, exceptions from the LLM call are propagated to the caller.

  • code_text (str | None)

Return type:

bool

llm_summarize_function(llm_client=None, code_text=None, raise_exc=False)

Ask the LLM to produce a natural-language summary of what the decompiled function does. The summary is stored in the DecompilationCache and returned.

Returns the summary string, or None if summarization failed.

Parameters:
  • raise_exc (bool) – If True, exceptions from the LLM call are propagated to the caller.

  • code_text (str | None)

Return type:

str | None

static options_to_params(options)

Convert decompilation options to a dict of params.

Parameters:

options (list[tuple[DecompilationOption, Any]]) – The decompilation options.

Return type:

dict[str, Any]

Returns:

A dict of keyword arguments.

class angr.analyses.decompiler.GraphDephication

Bases: DephicationBase

GraphDephication removes phi expressions from an AIL graph, essentially transforms a partial-SSA form of AIL graph to a normal AIL graph.

__init__(func, ail_graph, vvar_to_vvar_mapping=None, rewrite=False, variable_map=None)
Parameters:
  • func (Function | str) – The subject of the analysis: a function, or a single basic block

  • ail_graph – The AIL graph to transform.

  • vvar_to_vvar_mapping (dict[int, int] | None)

  • rewrite (bool)

  • variable_map (VariableMap | None)

class angr.analyses.decompiler.ImportSourceCode

Bases: BaseStructuredCodeGenerator, Analysis

__init__(function, flavor='source', source_root=None, encoding='utf-8')
regenerate_text()
class angr.analyses.decompiler.KnownPattern

Bases: object

A known code idiom, described declaratively.

Variables:
  • name (str) – Identifier, e.g. "std_string_length".

  • display_name (str) – Human-readable name, e.g. "std::string::length".

  • call_name (str) – Target name of the synthesized Call.

  • pattern (PatternExpr | PatternStmt | PGraphPat) – The structural pattern to match.

  • params (tuple[PatternParam, ...]) – Ordered parameters; their captures become the call arguments, in order.

  • returnty (str | CppRef | None) – Return type of the synthesized call.

  • returnty_factory (Callable[[Arch, dict[str, int]], SimType | None] | None) – Optional callable building a call-site-specific return type from the values of the constant extra_args captures (e.g. CONTAINING_RECORD returns a pointer to a record whose layout depends on the matched field offset). Falls back to returnty when it returns None or when the constant values are unavailable.

  • extra_args (tuple[str, ...]) – Names of (typically constant) captures appended to the call arguments after params.

  • arches (tuple[str, ...] | None) – Allowed archinfo.Arch.name values; None = any.

  • platforms (tuple[str, ...] | None) – Allowed OS names (project.simos.name, lowercased); None = any.

  • where (Callable[[dict[str, Expression]], bool] | None) – Optional cross-capture predicate evaluated on the bindings after a structural match.

  • collapse_capture (str | None) – Optional capture name identifying the idiom that a match belongs to: within one function, matches binding it to the same virtual variable all describe one source-level idiom, and only the one with the largest collapse_max_capture constant is kept. The compiler folds CONTAINING_RECORD’s subtraction into every field displacement, so one source idiom otherwise emits a call per field, each naming a different (and mostly wrong) record base.

  • collapse_max_capture (str | None) – Capture whose constant value orders the collapsing; required when collapse_capture is set.

  • binary_guard (Callable[[Project], bool] | None) – Optional predicate on the Project; the pattern is only used when it returns True (e.g. require C++ evidence for STL patterns to avoid false positives on plain C binaries).

  • default_enabled (bool) – Whether the pattern is used when the caller does not explicitly select patterns. Generic patterns prone to false positives should set this False.

name: str
display_name: str
call_name: str
pattern: PatternExpr | PatternStmt | PGraphPat
params: tuple[PatternParam, ...]
returnty: str | CppRef | None = None
returnty_factory: Callable[[Arch, dict[str, int]], SimType | None] | None = None
extra_args: tuple[str, ...] = ()
arches: tuple[str, ...] | None = None
platforms: tuple[str, ...] | None = None
where: Callable[[dict[str, Expression]], bool] | None = None
collapse_capture: str | None = None
collapse_max_capture: str | None = None
binary_guard: Callable[[Project], bool] | None = None
default_enabled: bool = True
suppressed_by: tuple[str, str, str] | None = None

Drop a match of this pattern when a pattern whose name matches the regex matched on the same object: (name regex, my capture, their capture). The two captures must bind .likes()-equal expressions. This is how a generic accessor yields to a specific one on the same base: a bare Load(s + 8) is std::string::length on a string and _M_finish on a vector, and the vector’s other fields say which. Judged against every match of the suppressing family, selected or not, so it cannot interact with largest-match selection.

claims_only: bool = False

Match only to claim a base for suppressed_by purposes; never outlined, never rewritten, never reported. For shapes that identify an object beyond doubt but are not worth naming: a vector’s capacity check says “this is a vector” and nothing a reader wants a call for.

pure_calls: frozenset[str] = frozenset({})

Callees this pattern reads through PCallResult whose only effect is their result: once the pattern has consumed that result and nothing else does, the call goes too. Naming a callee in a pattern is already a claim about what it computes; this is the claim that it computes nothing else. __ctype_b_loc returns a table pointer, and a bare __ctype_b_loc(); left behind after isspace(c) is noise.

applicable(arch_name, platform)
Return type:

bool

Parameters:
  • arch_name (str)

  • platform (str | None)

const_args_of_call(call)

Recover the extra_args constant values from a synthesized call’s trailing arguments. Returns None when the call does not carry them.

Return type:

dict[str, int] | None

Parameters:

call (Call)

prototype(arch, const_args=None)

Build the synthesized call’s prototype. const_args (the values of the constant extra_args captures, see const_args_of_call()) enables call-site-specific return types via returnty_factory. Returns None if any declared type fails to resolve.

Return type:

SimTypeFunction | None

Parameters:
__init__(name, display_name, call_name, pattern, params, returnty=None, returnty_factory=None, extra_args=(), arches=None, platforms=None, where=None, collapse_capture=None, collapse_max_capture=None, binary_guard=None, default_enabled=True, suppressed_by=None, claims_only=False, pure_calls=frozenset({}))
Parameters:
Return type:

None

class angr.analyses.decompiler.KnownPatternFinder

Bases: Analysis

Finds occurrences of KnownPatterns in a Clinic AIL graph.

The graph to match on is the final (SSA-form) Clinic graph, i.e. decompiler.ail_graph / clinic.cc_graph. Matches are reported in self.matches; outline() turns a match into a synthesized call by invoking the Outliner analysis on a copy of the graph.

MAX_REMOTE_CHASE_DEPTH = 6
__init__(func, ail_graph, patterns=None, chase_defs=True, chase_remote_defs=True, skip_conversions=True, vvar_id_start=48879, block_addr_start=2864381952, ail_manager=None, force_patterns=None)

patterns may be pattern templates (KnownPatternTemplate) and/or already-concrete KnownPatterns; templates are instantiated for this binary’s PatternContext. When None, the registry is used, filtered down to the templates that are enabled for this target: default-on ones, ones named by force_patterns, and ones whose gate opens (see gating).

force_patterns is the user’s force-enable selection, "all" or an iterable of template names / call names, and is only consulted when patterns is None (an explicit pattern list is already a selection).

Parameters:
call_target_names(call)

Public face of _resolve_call_target(), for the outliner’s clean-up of calls a pattern declared pure.

Return type:

frozenset[str]

Parameters:

call (Call)

apply_matches(matches, ail_graph)

Apply as many of matches as possible, batching where it matters.

Applying one match at a time is fine until several of them interleave in one block, which is exactly what consecutive field swaps do:

t1 = x->b; t2 = y->b; y->b = t1; x->b = t2;

^ the next field’s load sits in this one’s gap

Rewrite the first and the second’s statements have moved; rewrite it anyway and the third now has an opaque call sitting in its gap, which no disjointness test will let it move across. So the void statement-span matches of a block, which the finder has already checked do not conflict, are spliced in together, against the statement indices they were found at. Everything else keeps the one-at-a-time path.

Returns the new graph and the ids of the matches that were applied.

Return type:

tuple[DiGraph, set[int]]

Parameters:
outline(match, ail_graph=None)

Outline one match: split the anchor block so the matched span forms its own block, invoke the Outliner analysis on it, and rewrite the synthesized callsite into the pattern’s call. Operates on (and returns) a copy; neither self._graph nor ail_graph is mutated.

Return type:

OutlineResult

Parameters:
MAX_LIFTED_EXPR_NODES = 8

Node budget for a lifted parameter expression; see _is_liftable.

outline_at(location, pattern, ail_graph)

Find pattern at location ((block_addr, block_idx) or (block_addr, block_idx, stmt_idx)) in ail_graph and outline it.

Return type:

OutlineResult

Parameters:
class angr.analyses.decompiler.KnownPatternMatch

Bases: object

One occurrence of a KnownPattern in an AIL graph.

For expression-level matches, the boundary is consumed_stmt_idxs (statements wholly owned by the match, e.g. chased definitions) plus expr_path (the location of the matched sub-expression inside the anchor statement). For statement-sequence matches, stmt_span holds the ordered matched statement indices (the anchor is the first) and matched_expr is None.

duplicated_stmt_idxs holds chased definitions that are copied into the outlined region instead of moved: the originals stay where they are (other code still uses them) and the copies make the pattern’s captured values the region’s live-ins. It is always disjoint from consumed_stmt_idxs.

recomputed_defs does the same for definitions that live in another block (a CSE’d value, possibly reaching the anchor through a phi): the expression is pure, so the region recomputes it from the captured operands.

pattern: KnownPattern
block_loc: tuple[int, int]
anchor_stmt_idx: int
expr_path: tuple[tuple[str, int | None], ...]
consumed_stmt_idxs: frozenset[int]
captures: dict[str, Expression]
matched_expr: Expression | None
duplicated_stmt_idxs: frozenset[int] = frozenset({})
recomputed_defs: tuple[tuple[int, Expression], ...] = ()
base_aliases: tuple[tuple[int, int, int], ...] = ()
stmt_span: tuple[int, ...] | None = None
block_map: dict[str, tuple[int, int]] | None = None
consumed_by_block: dict[tuple[int, int], frozenset[int]] | None = None
frontier_locs: frozenset[tuple[int, int]] | None = None
__init__(pattern, block_loc, anchor_stmt_idx, expr_path, consumed_stmt_idxs, captures, matched_expr, duplicated_stmt_idxs=frozenset({}), recomputed_defs=(), base_aliases=(), stmt_span=None, block_map=None, consumed_by_block=None, frontier_locs=None)
Parameters:
Return type:

None

class angr.analyses.decompiler.RegionIdentifier

Bases: Analysis

A region is a single-entry-single-exit subgraph of control flow. The region identifier recursively identifies the smallest possible regions within a function graph and creates a RegionOverlay object whose nodes are either Blocks or RegionOverlays.

Note, that the analysis may modify the graph in-place. If you want to keep the original graph, set the update_graph parameter to False.

__init__(func, cond_proc=None, graph=None, ail_manager=None, update_graph=True, largest_successor_tree_outside_loop=True, force_loop_single_exit=True, refine_loops_with_single_successor=False, expose_loop_head_backedges=False, force_single_loop_entry=False, entry_node_addr=None)
Parameters:
test_reducibility()
Return type:

bool

class angr.analyses.decompiler.RegionOverlay

Bases: Generic[T]

A single-entry region marked over the complete graph held by an OverlayManager. The region tree is built out of RegionOverlay objects (RegionIdentifier emits them) and they are the only region type the decompiler uses.

Overlays form a tree (nested, never overlapping). An overlay’s members are either complete-graph nodes it owns directly or child overlays. The region graph and the region graph-with-successors are derived on demand from the complete graph by quotienting child overlays into single nodes; successors are likewise derived from edges that cross the region boundary, so they can never go stale.

Read-only API (head, graph, graph_with_successors, successors, cyclic, addr) mirrors the region container consumers expect; graph/graph_with_successors/successors are lazy zero-copy views.

Mutation verbs:

  • true structural changes (add_node, remove_node, add_edge, detach_edge, replace_nodes) pass through to the complete graph, so the effects are immediately visible to all enclosing regions;

  • hide_edge removes an edge from this overlay’s views only (the old “remove it from region graphs but keep the parent edge” pattern);

  • finalize(result_node) collapses a fully-structured region into a single node of its parent;

  • dissolve() merges an unsuccessfully-structured region back into its parent.

__init__(mgr, head, cyclic, cyclic_ancestor=False, parent=None)
Parameters:
head
cyclic
cyclic_ancestor
parent
children: list[RegionOverlay]
edge_marks: defaultdict[str, set[tuple[Tx[T], Tx[T]]]]
replacement
property addr
property manager: OverlayManager[T]
property members: set[Tx[T]]
ancestors()

All overlays enclosing this one, including this one itself.

Return type:

set[RegionOverlay]

underlying_nodes()

All complete-graph nodes inside this region (including nodes of nested regions).

Return type:

set[T]

create_subregion(head, members, cyclic, cyclic_ancestor=False)

Carve a new child overlay out of this overlay. members must be a subset of this overlay’s members (complete-graph nodes owned by this overlay and/or existing child overlays); head must be one of them.

Return type:

RegionOverlay[T]

Parameters:
  • head (Tx[T])

  • members (Iterable)

  • cyclic (bool)

  • cyclic_ancestor (bool)

representative(node)

The node standing for a complete-graph node in this overlay’s with-successors view.

Return type:

Tx[T] | None

Parameters:

node (T)

successor_nodes()

The derived successor set of this region: representatives of all complete-graph nodes targeted by edges leaving the region.

Return type:

set[Tx[T]]

view_graph(full=False, include_marked=False, blacklisted_edges=frozenset({}))

A zero-copy, networkx-compatible view of this region (see RegionOverlayGraph).

Return type:

RegionOverlayGraph[T]

Parameters:
view()

The region graph (members only): a zero-copy networkx-compatible view; treat it as read-only.

Return type:

RegionOverlayGraph[T]

view_with_successors()

The region graph including successor nodes: a zero-copy view; treat it as read-only.

Return type:

RegionOverlayGraph[T]

property raw_graph: RegionOverlayGraph[T]

The member view including marked edges (the old graph with cyclic_refinement_outgoing attrs present).

property raw_graph_with_successors: RegionOverlayGraph[T]

The with-successors view including marked edges.

property graph: networkx.DiGraph[Tx[T]]
property graph_with_successors: networkx.DiGraph[Tx[T]]
property successors: set[Tx[T]]
property full_graph: None
complete_graph_entry_count(node)

The number of edges entering a node in the complete graph, counted over every region. For a region object, the entries of its head from outside the region (its own back edges do not count).

Return type:

int

Parameters:

node (Tx[T])

external_entry_count(node)

The number of edges entering a node (a successor of this region) from nodes that are not under this region: the entries it keeps once every edge from this region to it has been virtualized.

Return type:

int

Parameters:

node (Tx[T])

add_node(node)

Insert a new node into the complete graph as a direct member of this region.

Return type:

None

remove_node(node, absorbed_into=None, absorb_out_edges=True)

Remove a node. If node is a member (or a member overlay’s node), it is removed from the complete graph for real. If it is a successor of this region, the removal is interpreted as hiding all edges from this region to it (the successor belongs to an enclosing region and must survive).

When the node’s content has been absorbed into another node during structuring, pass that node as absorbed_into: in-edges from outside this region (e.g. abnormal loop entries) are then rewired to it instead of being dropped, so enclosing regions keep their entry edges. With absorb_out_edges (the default), out-edges crossing the region boundary (e.g. loop exits) are rewired to it as well, so the complete graph never loses the region’s exit flow; pass False only when the caller re-establishes every successor edge explicitly.

Return type:

None

Parameters:
  • node (Tx[T])

  • absorbed_into (Tx[T] | None)

  • absorb_out_edges (bool)

hide_edge_to_successor(succ)
Return type:

None

underlying_edge_pairs(src, dst)
Return type:

list[tuple[Tx[T], Tx[T]]]

Parameters:
  • src (Tx[T])

  • dst (Tx[T])

add_edge(src, dst, **data)

Add a real edge to the complete graph. Overlay endpoints are resolved to underlying nodes: the destination resolves to its entry (head chain); overlay sources are not supported. Endpoints that are not in the complete graph yet become members of this region (mirroring networkx’s implicit node creation).

Return type:

None

Parameters:
  • src (Tx[T])

  • dst (Tx[T])

detach_raw_edge(u, v)

Remove exactly one complete-graph edge. Unlike detach_edge, other edges between the view nodes representing u and v are kept (e.g. a block that jumps both to a loop’s entry and into its body).

Return type:

None

Parameters:
  • u (T)

  • v (T)

detach_edge(src, dst)

Remove an edge from the complete graph for real (e.g., when the edge has been virtualized into a goto). Overlay endpoints remove all underlying edges between the two node sets.

Return type:

None

Parameters:
  • src (Tx[T])

  • dst (Tx[T])

mark_edge(src, dst, **attrs)

Mark a view-level edge (e.g. cyclic_refinement_outgoing) so RegionOverlayGraph hides it by default. Marks live in overlay state, never reach the complete graph, and are remapped/cleared with the region.

Return type:

None

Parameters:
  • src (Tx[T])

  • dst (Tx[T])

absorb_successor_into(succ, new_node)

Absorb a successor node into a structured member node in this region’s with-successors view only (the successor still belongs to an enclosing region): the successor’s view out-edges are re-attached to the member node as view-only extra edges, then the successor disappears from this region’s views.

Return type:

None

Parameters:
  • succ (Tx[T])

  • new_node (Tx[T])

drop_edge_marks_from(node, key)

Clear marks on all out-edges of a node (the new_node after a replace), undoably.

Return type:

None

Parameters:
remove_edge_with_successors_only(src, dst)

Hide an edge from the with-successors view only, leaving the member view and the complete graph alone (a rare asymmetric bookkeeping pattern in Phoenix’s switch-case structuring).

Return type:

None

Parameters:
  • src (Tx[T])

  • dst (Tx[T])

successors_only_hidden_edges()

The view-level edges that remove_edge_with_successors_only() hid from the with-successors view.

Return type:

set[tuple[Tx[T], Tx[T]]]

hide_edge(src, dst)

Remove an edge from this overlay’s views only. Enclosing regions still see the underlying edge(s).

Return type:

None

Parameters:
  • src (Tx[T])

  • dst (Tx[T])

replace_nodes(old_node_0, new_node, old_node_1=None, self_loop=True)

Replace one or two member nodes with a new node, preserving and rewiring all underlying edges (including edges from/to nodes outside this region, which is how results become visible to enclosing regions).

Mirrors StructurerBase.replace_nodes, with one deliberate difference: in-edges of old_node_1 from outside this region are rewired to new_node instead of being dropped (they are entry edges owned by enclosing regions, e.g. abnormal loop entries).

Return type:

None

Parameters:
  • old_node_0 (Tx[T])

  • new_node (Tx[T])

  • old_node_1 (Tx[T] | None)

  • self_loop (bool)

snapshot_successors()

Capture this region’s structural successors and how many member edges reach each, taken before the region is structured. finalize() uses it to re-establish the region-to-successor edges that structuring removes when it refines the corresponding control-flow edges into breaks, and to tell successors whose every member edge was virtualized into a goto (see detach_edge()).

Return type:

dict[Tx[T], int]

finalize(result_node=None, succ_snapshot=None)

Collapse this fully-structured region into its parent: the region must consist of a single member node (the structuring result), which takes the region’s place among the parent’s members. Returns that node.

succ_snapshot (from snapshot_successors() before structuring) is used to re-establish the edges from result_node to the region’s successors: structuring may have removed the live control-flow edges (refining them into breaks), but the structured region still flows to those successors and enclosing regions must see that.

A successor whose every member edge was virtualized into a goto (detach_edge()) is a pure goto target and must NOT be reconnected. Consider a loop with two exits, where err is shared with other loops of the function:

    while (1) {
        if (s->bsLive >= 8) break;             // exit A: the loop successor
        if (s->strm->avail_in == 0) goto err;  // exit B: virtualized into a goto by cyclic refinement
        refill();
    }
    uc = take_bits();                          // A
    ...
err:
    retVal = BZ_DATA_ERROR;
    goto save_state_and_return;

The loop region has successors A and err. Cyclic refinement keeps A as the loop successor (a break) and turns the exit to err into a goto statement, removing that edge from the complete graph. Reconnecting err here would give the loop node two successors in the parent region, one real and one fictitious: the ITE schema finds no conditions on them, the sequence schema needs a single successor, and last-resort refinement keeps both edges because each target would be orphaned, so the parent region can never be structured. With only A reconnected, the loop node is sequenced with A as usual and err stays reachable through its gotos. Cyclic refinement never virtualizes an exit that is its target’s only entry in the complete graph: the region bails and dissolves into its parent, where the target is a member and the acyclic schemas structure it with the loop.

Parameters:
  • result_node (Tx[T] | None)

  • succ_snapshot (set[Tx[T]] | None)

collapse_to(result_node)

Collapse this region into its parent by replacing all of its member nodes with a single external result node (the structuring result). Used by structurers that compute their result without destructively reducing the complete graph (e.g. DreamStructurer): the region’s members are still present, so their crossing in/out edges are rewired onto result_node and the members are removed. Returns result_node.

This is the non-self-collapsing counterpart of finalize(); the legacy GraphRegion path called replace_region() for the same purpose.

Parameters:

result_node (RegionOverlay[T])

dissolve()

Merge this region back into its parent (the failure path of structuring): members are reparented, and edges hidden in this region stay hidden in the parent (matching how partially-structured region graphs were merged back before).

Return type:

None

class angr.analyses.decompiler.RegionSimplifier

Bases: Analysis

Simplifies a given region.

__init__(func, region, ail_manager, arg_vvars=None, simplify_switches=True, simplify_ifelse=True, variable_manager=None, loopctr_naming=True)
Parameters:
class angr.analyses.decompiler.SeqNodeDephication

Bases: DephicationBase

SeqNodeDephication removes phi expressions from a SequenceNode and its children. It also removes redundant variable assignments, e.g., vvar_2 = vvar_1 where both vvar_1 and vvar_2 are mapped to the same variable.

__init__(func, seq_node, vvar_to_vvar_mapping=None, rewrite=False, variable_map=None)
Parameters:
class angr.analyses.decompiler.Ssailification

Bases: Analysis

Ssailification (SSA-AIL-ification) transforms an AIL graph to its partial-SSA form.

__init__(func, ail_graph, entry=None, canonical_size=8, stack_pointer_tracker=None, func_addr=None, ail_manager=None, ssa_stackvars=False, ssa_tmps=False, func_args=None, rewrite_vvars=None, vvar_id_start=0, flavor=Flavors.DEFAULT_FLAVOR)
Parameters:
  • func (Function | str) – The subject of the analysis: a function, or a single basic block

  • ail_graph (networkx.DiGraph[Block]) – The AIL graph to transform.

  • canonical_size (int) – The sizes (in bytes) that objects with an UNKNOWN_SIZE are treated as for operations where sizes are necessary.

  • entry (Block | None)

  • func_addr (int | None)

  • ail_manager (Manager | None)

  • ssa_stackvars (bool)

  • ssa_tmps (bool)

  • func_args (set[VirtualVariable] | None)

  • rewrite_vvars (set[int] | None)

  • vvar_id_start (int)

  • flavor (str)

angr.analyses.decompiler.StructuredCodeGenerator

alias of CStructuredCodeGenerator

class angr.analyses.decompiler.VariableMap

Bases: object

A side container that maps the .idx of AIL Statement and Expression objects to variable-related information.

The following pieces of information are tracked:

  • variable (a SimVariable) and variable_offset (an int): the variable that an AIL atom resolves to, and the offset into that variable.

  • custom_string (a bool): whether a Const expression refers to a custom string.

  • reference_values (a dict mapping SimType to a value): reference values associated with a Const expression (e.g., custom strings).

  • reference_variable (a SimVariable) and reference_variable_offset (an int): the variable that a constant expression references, and the offset into it. These are siblings of variable / variable_offset that are specifically used for constants that reference global/extern variables.

  • prototype (a SimTypeFunction) and calling_convention (a SimCC): the call-site prototype and calling convention associated with an AIL Call expression. These used to live directly on the Call object; they are heavy, non-serializable Python references, so they are tracked here instead.

  • variant (an EnumVariant): the enum variant that a Rust Let expression binds.

  • returnty (a SimType): the return type of a Rust FunctionLikeMacro call.

Keys are the integer .idx values of AIL Statement/Expression objects. Because Clinic builds one ailment.Manager per invocation, .idx values are unique within a single Clinic. So a VariableMap is scoped to one Clinic instance and is stored in the corresponding DecompilationCache.

__init__()
variable(obj)
Return type:

SimVariable | None

Parameters:

obj (AILObject | int)

variable_offset(obj)
Return type:

int

Parameters:

obj (AILObject | int)

custom_string(obj)
Return type:

bool

Parameters:

obj (AILObject | int)

reference_values(obj)
Return type:

dict[SimType, Any] | None

Parameters:

obj (AILObject | int)

reference_variable(obj)
Return type:

SimVariable | None

Parameters:

obj (AILObject | int)

reference_variable_offset(obj)
Return type:

int

Parameters:

obj (AILObject | int)

has_variable(obj)
Return type:

bool

Parameters:

obj (AILObject | int)

prototype(obj)
Return type:

SimTypeFunction | None

Parameters:

obj (AILObject | int)

calling_convention(obj)
Return type:

SimCC | None

Parameters:

obj (AILObject | int)

variant(obj)
Return type:

Any

Parameters:

obj (AILObject | int)

returnty(obj)
Return type:

SimType | None

Parameters:

obj (AILObject | int)

set_variable(obj, variable, offset=0)

Set the variable information for an AIL atom. If variable is None, the variable information for this atom is cleared.

Return type:

None

Parameters:
set_variable_offset(obj, offset)
Return type:

None

Parameters:
  • obj (AILObject | int)

  • offset (int)

set_custom_string(obj, value=True)
Return type:

None

Parameters:
  • obj (AILObject | int)

  • value (bool)

set_reference_values(obj, reference_values)
Return type:

None

Parameters:
set_reference_variable(obj, variable, offset=0)

Set the reference variable information for an AIL atom. If variable is None, the reference variable information for this atom is cleared.

Return type:

None

Parameters:
set_prototype(obj, prototype)

Set the call-site prototype for an AIL Call. If prototype is None, the prototype information for this atom is cleared.

Return type:

None

Parameters:
set_calling_convention(obj, cc)

Set the calling convention for an AIL Call. If cc is None, the calling-convention information for this atom is cleared.

Return type:

None

Parameters:
  • obj (AILObject | int)

  • cc (SimCC | None)

set_variant(obj, variant)

Set the enum variant for a Rust Let expression. If variant is None, the variant information for this atom is cleared.

Return type:

None

Parameters:
  • obj (AILObject | int)

  • variant (Any)

set_returnty(obj, returnty)

Set the return type for a Rust FunctionLikeMacro call. If returnty is None, the return-type information for this atom is cleared.

Return type:

None

Parameters:
transfer(src, dst)

Copy all variable information associated with src to dst. Used when an AIL atom is deep-copied to a new .idx (e.g. during structuring/duplication) so that the new atom keeps the same variable association.

Return type:

None

Parameters:
to_json()

Serialize this VariableMap to a JSON-compatible object.

Variables are referenced by their .ident (reference-by-ident); they must be resolved back to SimVariable objects via a resolver in from_json().

Return type:

dict[str, Any]

classmethod from_json(data, resolve_variable)

Deserialize a VariableMap from a JSON-compatible object produced by to_json().

Parameters:
  • data (dict[str, Any]) – The JSON object.

  • resolve_variable (Callable[[str], SimVariable | None]) – A callable that maps a variable ident (str) to a SimVariable (or None if it cannot be resolved).

Return type:

VariableMap

Submodules

ail_simplifier

ailgraph_walker

block_io_finder

block_similarity

block_simplifier

block_walkers

callsite_maker

ccall_rewriters

clinic

condition_processor

counters

decompilation_cache

decompilation_options

decompiler

dephication

dirty_rewriters

edits

Knowledge-base edits for decompilation output: renaming, retyping, and commenting.

empty_node_remover

expression_narrower

goto_manager

ireg_resolver

jump_target_collector

jumptable_entry_condition_rewriter

known_patterns

Known code patterns: context-aware, declarative descriptions of library/macro idioms that compilers inline, plus machinery (KnownPatternFinder) to find them in Clinic AIL graphs and outline them back into calls.

label_collector

mixins

node_replacer

notes

optimization_pass_registry

Stable name resolution for decompiler optimization passes and peephole optimizations.

optimization_passes

pattern_match

Fuzzy repeated-code discovery for decompiled functions.

peephole_optimizations

presets

redundant_label_remover

region_identifier

region_overlay

region_simplifiers

region_walker

return_maker

semantic_naming

Semantic variable naming patterns for the decompiler.

seq_to_blocks

sequence_walker

ssailification

stack_item

stackarg_offset_manager

stl_field_accessors

Named accessors for fields of the C++ STL classes registered in the cpp::std SimTypeCollection.

structured_codegen

structurer_nodes

structuring

utils

variable_map

x87_fsw

Evaluation of integer expressions derived from an x87 CmpF result or an fxam classification.