angr — Analysis and Coordination

Project

angr.project.register_default_engine(loader_backend, engine, arch='any')

Register the default SimuVEX engine to be used with a given CLE backend. Usually this is the SimEngineVEX, but if you’re operating on something that isn’t going to be lifted to VEX, you’ll need to make sure the desired engine is registered here.

Parameters:
  • loader_backend – The loader backend (a type)
  • type (engine) – The engine to use for the loader backend (a type)
Returns:

angr.project.get_default_engine(loader_backend, arch='any')

Get some sort of sane default for a given loader and/or arch. Can be set with register_default_engine() :param loader_backend: :param arch: :return:

class angr.project.Project(thing, default_analysis_mode=None, ignore_functions=None, use_sim_procedures=True, exclude_sim_procedures_func=None, exclude_sim_procedures_list=(), arch=None, simos=None, load_options=None, translation_cache=True, support_selfmodifying_code=False)

This is the main class of the angr module. It is meant to contain a set of binaries and the relationships between them, and perform analyses on them.

Variables:
  • analyses – The available analyses.
  • entry – The program entrypoint.
  • factory – Provides access to important analysis elements such as path groups and symbolic execution results.
  • filename – The filename of the executable.
  • loader – The program loader.
  • surveyor – The available surveyors.
Parameters:

thing – The path to the main executable object to analyze, or a CLE Loader object.

The following parameters are optional.

Parameters:
  • default_analysis_mode – The mode of analysis to use by default. Defaults to ‘symbolic’.
  • ignore_functions – A list of function names that, when imported from shared libraries, should never be stepped into in analysis (calls will return an unconstrained value).
  • use_sim_procedure – Whether to replace resolved dependencies for which simprocedures are available with said simprocedures.
  • exclude_sim_procedures_func – A function that, when passed a function name, returns whether or not to wrap it with a simprocedure.
  • exclude_sim_procedures_list – A list of functions to not wrap with simprocedures.
  • arch – The target architecture (auto-detected otherwise).
  • simos – a SimOS class to use for this project.
  • load_options – a dict of keyword arguments to the CLE loader. See CLE’s docs.
  • translation_cache – If True, cache translated basic blocks rather than re-translating them.
  • support_selfmodifying_code (bool) – Whether we support self-modifying code. When enabled, Project.sim_block() will try to read code from the current state instead of the original memory regions.

A sample load_options value could be:

{ 'auto_load_libs': False,
  'skip_libs': 'ld.so.2',
  'lib_opts': {
    'libc.so.6': {
    'custom_base_addr': 0x55555400
    }
  }
}
hook(addr, hook, length=0, kwargs=None)

Hook a section of code with a custom function. This is used internally to provide symbolic summaries of library functions, and can be used to instrument execution or to modify control flow.

Parameters:
  • addr – The address to hook.
  • hook – A angr.project.Hook describing a procedure to run at the given address. You may also pass in a SimProcedure class or a function directly and it will be wrapped in a Hook object for you.
  • length – If you provide a function for the hook, this is the number of bytes that will be skipped by executing the hook by default.
  • kwargs – If you provide a SimProcedure for the hook, these are the keyword arguments that will be passed to the procedure’s run method eventually.
is_hooked(addr)

Returns True if addr is hooked.

Parameters:addr – An address.
Returns:True if addr is hooked, False otherwise.
is_symbol_hooked(symbol_name)

Check if a symbol is already hooked.

Parameters:symbol_name (str) – Name of the symbol.
Returns:True if the symbol can be resolved and is hooked, False otherwise.
Return type:bool
hooked_symbol_addr(symbol_name)

Check if a symbol is hooked or not, and if it is hooked, return the address of the symbol.

Parameters:symbol_name (str) – Name of the symbol.
Returns:Address of the symbol if it is hooked, None otherwise.
Return type:int or None
unhook(addr)

Remove a hook.

Parameters:addr – The address of the hook.
hooked_by(addr)

Returns the current hook for addr.

Parameters:addr – An address.
Returns:None if the address is not hooked.
hook_symbol(symbol_name, obj, kwargs=None)

Resolve a dependency in a binary. Uses the “externs object” (project._extern_obj) to allocate an address for a new symbol in the binary, and then tells the loader to reperform the relocation process, taking into account the new symbol.

Parameters:
  • symbol_name – The name of the dependency to resolve.
  • obj – The thing with which to satisfy the dependency. May be a python integer or anything that may be passed to project.hook().
  • length – If you provide a function for the hook, this is the number of bytes that will be skipped by executing the hook by default.
  • kwargs – If you provide a SimProcedure for the hook, these are the keyword arguments that will be passed to the procedure’s run method eventually.
Returns:

The address of the new symbol.

Return type:

int

hook_symbol_batch(hooks)

Hook many symbols at once.

Parameters:provisions (dict) – A mapping from symbol name to hook
class angr.project.Hook(procedure, cc=None, **kwargs)

An object describing an action to be taken at a given address instead of executing binary code. An instance of this class may be passed to angr.Project.hook along with the address at which to hook.

More specifically, a hook is a wrapper for a SimProcedure, a simuvex object that contains a lot of logic for how to mutate a state in common ways. The SimProcedure base class is subclassed to produce a SimProcedure that may be used for hooking. If the SimProcedure class is too heavy for your use case, there is a class method wrap on this class that can be used to wrap a simple function into a SimProcedure, and then further into a Hook directly.

This class is a bit of a hack to deal with the fact that SimProcedures need to hold state but having them do so makes them not thread-safe.

Parameters:
  • procedure – The class of the procedure to use
  • cc – The calling convention to use
  • kwargs – Any additional keyword arguments will be eventually passed to the run method of the procedure on its execution, via the sim_kwargs SimProcedure constructor parameter.
instantiate(*args, **kwargs)
Parameters:arch – The architecture to use for this procedure

The following parameters are optional:

Parameters:
  • symbolic_return – Whether the procedure’s return value should be stubbed into a single symbolic variable constratined to the real return value
  • returns – Whether the procedure should return to its caller afterwards
  • is_syscall – Whether this procedure is a syscall
  • num_args – The number of arguments this procedure should extract
  • display_name – The name to use when displaying this procedure
  • convention – The SimCC to use for this procedure
  • sim_kwargs – Additional keyword arguments to be passed to run()
  • is_function – Whether this procedure emulates a function
classmethod wrap(length=0)

Call this function to return a decorator you can use to turn a function into a Hook. This specific kind of hook is called a “User Hook”.

For example:

>>> @Hook.wrap(length=5)
>>> def set_rax(state):
>>>     state.regs.rax = 1
>>>
>>> project.hook(0x1234, set_rax)

The function may modify the state in any way it sees fit. In order to produce successors from a user hook, you have two options.

  1. Return nothing. In this case, execution will resume at length bytes after the hook address.

  2. Return a list of successor states. Each of the states should have the following attributes set:

    • state.scratch.guard: a symbolic boolean describing the condition necessary for this successor to be taken. A shortcut to the symbolic True value is state.se.true.
    • state.scratch.jumpkind: The type of the jump to be taken, as a VEX enum string. This will usually be Ijk_Boring, which signifies an ordinary jump or branch.

Factory

class angr.factory.AngrObjectFactory(project, default_engine, procedure_engine, engines)

This factory provides access to important analysis elements.

successors(state, addr=None, jumpkind=None, inline=False, default_engine=False, engines=None, **kwargs)

Perform execution using any applicable engine. Enumerate the current engines and use the first one that works. Return a SimSuccessors object classifying the results of the run.

Parameters:
  • state – The state to analyze
  • addr – optional, an address to execute at instead of the state’s ip
  • jumpkind – optional, the jumpkind of the previous exit
  • inline – This is an inline execution. Do not bother copying the state.
  • default_engine – Whether we should only attempt to use the default engine (usually VEX)
  • engines – A list of engines to try to use, instead of the default.

Additional keyword arguments will be passed directly into each engine’s process method.

blank_state(**kwargs)

Returns a mostly-uninitialized state object. All parameters are optional.

Parameters:
  • addr – The address the state should start at instead of the entry point.
  • initial_prefix – If this is provided, all symbolic registers will hold symbolic values with names prefixed by this string.
  • fs – A dictionary of file names with associated preset SimFile objects.
  • concrete_fs – bool describing whether the host filesystem should be consulted when opening files.
  • chroot – A path to use as a fake root directory, Behaves similarly to a real chroot. Used only when concrete_fs is set to True.
  • kwargs – Any additional keyword args will be passed to the SimState constructor.
Returns:

The blank state.

Return type:

simuvex.s_state.SimState

entry_state(**kwargs)

Returns a state object representing the program at its entry point. All parameters are optional.

Parameters:
  • addr – The address the state should start at instead of the entry point.
  • initial_prefix – If this is provided, all symbolic registers will hold symbolic values with names prefixed by this string.
  • fs – a dictionary of file names with associated preset SimFile objects.
  • concrete_fs – boolean describing whether the host filesystem should be consulted when opening files.
  • chroot – a path to use as a fake root directory, behaves similar to a real chroot. used only when concrete_fs is set to True.
  • argc – a custom value to use for the program’s argc. May be either an int or a bitvector. If not provided, defaults to the length of args.
  • args – a list of values to use as the program’s argv. May be mixed strings and bitvectors.
  • env – a dictionary to use as the environment for the program. Both keys and values may be mixed strings and bitvectors.
Returns:

The entry state.

Return type:

simuvex.s_state.SimState

full_init_state(**kwargs)

Very much like entry_state(), except that instead of starting execution at the program entry point, execution begins at a special SimProcedure that plays the role of the dynamic loader, calling each of the initializer functions that should be called before execution reaches the entry point.

Parameters:
  • addr – The address the state should start at instead of the entry point.
  • initial_prefix – If this is provided, all symbolic registers will hold symbolic values with names prefixed by this string.
  • fs – a dictionary of file names with associated preset SimFile objects.
  • concrete_fs – boolean describing whether the host filesystem should be consulted when opening files.
  • chroot – a path to use as a fake root directory, behaves similar to a real chroot. used only when concrete_fs is set to True.
  • argc – a custom value to use for the program’s argc. May be either an int or a bitvector. If not provided, defaults to the length of args.
  • args – a list of values to use as arguments to the program. May be mixed strings and bitvectors.
  • env – a dictionary to use as the environment for the program. Both keys and values may be mixed strings and bitvectors.
Returns:

The fully initialized state.

Return type:

simuvex.s_state.SimState

call_state(addr, *args, **kwargs)

Returns a state object initialized to the start of a given function, as if it were called with given parameters.

Parameters:
  • addr – The address the state should start at instead of the entry point.
  • args – Any additional positional arguments will be used as arguments to the function call.

The following parametrs are optional.

Parameters:
  • base_state – Use this SimState as the base for the new state instead of a blank state.
  • cc – Optionally provide a SimCC object to use a specific calling convention.
  • ret_addr – Use this address as the function’s return target.
  • stack_base – An optional pointer to use as the top of the stack, circa the function entry point
  • alloc_base – An optional pointer to use as the place to put excess argument data
  • grow_like_stack – When allocating data at alloc_base, whether to allocate at decreasing addresses
  • toc – The address of the table of contents for ppc64
  • initial_prefix – If this is provided, all symbolic registers will hold symbolic values with names prefixed by this string.
  • fs – A dictionary of file names with associated preset SimFile objects.
  • concrete_fs – bool describing whether the host filesystem should be consulted when opening files.
  • chroot – A path to use as a fake root directory, Behaves similarly to a real chroot. Used only when concrete_fs is set to True.
  • kwargs – Any additional keyword args will be passed to the SimState constructor.
Returns:

The state at the beginning of the function.

Return type:

simuvex.s_state.SimState

The idea here is that you can provide almost any kind of python type in args and it’ll be translated to a binary format to be placed into simulated memory. Lists (representing arrays) must be entirely elements of the same type and size, while tuples (representing structs) can be elements of any type and size. If you’d like there to be a pointer to a given value, wrap the value in a SimCC.PointerWrapper. Any value that can’t fit in a register will be automatically put in a PointerWrapper.

If stack_base is not provided, the current stack pointer will be used, and it will be updated. If alloc_base is not provided, the current stack pointer will be used, and it will be updated. You might not like the results if you provide stack_base but not alloc_base.

grow_like_stack controls the behavior of allocating data at alloc_base. When data from args needs to be wrapped in a pointer, the pointer needs to point somewhere, so that data is dumped into memory at alloc_base. If you set alloc_base to point to somewhere other than the stack, set grow_like_stack to False so that sequencial allocations happen at increasing addresses.

path(state=None, **kwargs)

Constructs a new path.

Parameters:state – Optional - The state to start the new path at. If not provided, an entry_state() will be constructed using any additional keyword arguments provided.
Returns:The new path.
Return type:angr.path.Path
path_group(thing=None, **kwargs)

Constructs a new path group.

Parameters:
  • thing – Optional - What to put in the new path group’s active stash.
  • kwargs – Any additional keyword arguments will be passed to the PathGroup constructor
Returns:

The new path group

Return type:

angr.path_group.PathGroup

Many different types can be passed to this method:

  • If nothing is passed in, the path group is seeded with a path containing a state initialized for the program entry point, i.e. entry_state().
  • If a simuvex.s_state.SimState is passed in, the path group is seeded with a path wrapping that state.
  • If a angr.path.Path is passed in, the path group is seeded with that path.
  • If a list is passed in, the list must contain only SimStates and Paths, each SimState will be wrapped in a Path, and the whole list will be used to seed the path group.
callable(addr, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None)

A Callable is a representation of a function in the binary that can be interacted with like a native python function.

Parameters:
  • addr – The address of the function to use
  • concrete_only – Throw an exception if the execution splits into multiple paths
  • perform_merge – Merge all result states into one at the end (only relevant if concrete_only=False)
  • base_state – The state from which to do these runs
  • toc – The address of the table of contents for ppc64
  • cc – The SimCC to use for a calling convention
Returns:

A Callable object that can be used as a interface for executing guest code like a python function.

Return type:

angr.surveyors.caller.Callable

cc(args=None, ret_val=None, sp_delta=None, func_ty=None)

Return a SimCC (calling convention) parametrized for this project and, optionally, a given function.

Parameters:
  • args – A list of argument storage locations, as SimFunctionArguments.
  • ret_val – The return value storage location, as a SimFunctionArgument.
  • sp_delta – Does this even matter??
  • func_ty – The protoype for the given function, as a SimType.

Relevant subclasses of SimFunctionArgument are SimRegArg and SimStackArg, and shortcuts to them can be found on this cc object.

For stack arguments, offsets are relative to the stack pointer on function entry.

cc_from_arg_kinds(fp_args, ret_fp=None, sizes=None, sp_delta=None, func_ty=None)

Get a SimCC (calling convention) that will extract floating-point/integral args correctly.

Parameters:
  • arch – The Archinfo arch for this CC
  • fp_args – A list, with one entry for each argument the function can take. True if the argument is fp, false if it is integral.
  • ret_fp – True if the return value for the function is fp.
  • sizes – Optional: A list, with one entry for each argument the function can take. Each entry is the size of the corresponding argument in bytes.
  • sp_delta – The amount the stack pointer changes over the course of this function - CURRENTLY UNUSED
Parmm func_ty:

A SimType for the function itself

Paths & Path Groups

class angr.path.Path(project, state, path=None, strong_reference=False)

A Path represents a sequence of basic blocks for an execution of the program.

Variables:
  • name – A string to identify the path.
  • state – The state of the program.
  • strong_reference – Whether or not to keep a strong reference to the previous state in path_history

:

step(throw=None, **run_args)

Step a path forward. Optionally takes any argument applicable to project.factory.successors.

Parameters:
  • jumpkind – the jumpkind of the previous exit.
  • address (addr) – to execute at instead of the state’s ip.
  • whitelist – a list of stmt indexes to which to confine execution.
  • last_stmt – a statement index at which to stop execution.
  • thumb – whether the block should be lifted in ARM’s THUMB mode.
  • backup_state – a state to read bytes from instead of using project memory.
  • opt_level – the VEX optimization level to use.
  • insn_bytes – a string of bytes to use for the block instead of #the project.
  • size – the maximum size of the block, in bytes.
  • num_inst – the maximum number of instructions.
  • traceflags – traceflags to be passed to VEX. Default: 0
  • whether or not to keep a strong reference to the previous state. Default (strong_reference) – False
Returns:

An array of paths for the possible successors.

clear()

This function clear the execution status.

After calling this if you call step(), successors will be recomputed. If you changed something into path state you probably want to call this method.

branch_causes()

Returns the variables that have caused this path to branch.

Returns:A list of tuples of (basic block address, jmp instruction address, set(variables))
divergence_addr(other)

Returns the basic block at which the paths diverged.

Parameters:other – The other Path.
Returns:The address of the basic block.
detect_loops(n=None)

Returns the current loop iteration that a path is on.

Parameters:n – The minimum number of iterations to check for.
Returns:The number of the loop iteration it’s in.
merge(other_paths, common_history)

Returns a merger of this path with all the paths in other_paths.

Parameters:
  • other_paths – list of paths to merge together with self
  • common_history – a PathHistory node shared by all the paths. Must be provided; causes merging to be more efficient, and actions and such are merged.
Returns:

the merged Path

Return type:

Path

filter_actions(block_addr=None, block_stmt=None, insn_addr=None, read_from=None, write_to=None)

Filter self.actions based on some common parameters.

Parameters:
  • block_addr – Only return actions generated in blocks starting at this address.
  • block_stmt – Only return actions generated in the nth statement of each block.
  • insn_addr – Only return actions generated in the assembly instruction at this address.
  • read_from – Only return actions that perform a read from the specified location.
  • write_to – Only return actions that perform a write to the specified location.

Notes: If IR optimization is turned on, reads and writes may not occur in the instruction they originally came from. Most commonly, If a register is read from twice in the same block, the second read will not happen, instead reusing the temp the value is already stored in.

Valid values for read_from and write_to are the string literals ‘reg’ or ‘mem’ (matching any read or write to registers or memory, respectively), any string (representing a read or write to the named register), and any integer (representing a read or write to the memory at this address).

class angr.path.ErroredPath(error, traceback, *args, **kwargs)

ErroredPath is used for paths that have encountered and error in their symbolic execution. This kind of path cannot be stepped further.

Variables:error – The error that was encountered.
class angr.path_group.PathGroup(project, active_paths=None, stashes=None, hierarchy=None, veritesting=None, veritesting_options=None, immutable=None, resilience=None, save_unconstrained=None, save_unsat=None, threads=None)

Path groups are the future.

Path groups allow you to wrangle multiple paths in a slick way. Paths are organized into “stashes”, which you can step forward, filter, merge, and move around as you wish. This allows you to, for example, step two different stashes of paths at different rates, then merge them together.

Stashes can be accessed as attributes (i.e. pg.active). A mulpyplexed stash can be retrieved by prepending the name with mp_ (e.g., pg.mp_active).

Note that you shouldn’t usually be constructing path groups directly - there is a convenient shortcuts for creating path groups in Project.factory: see angr.factory.AngrObjectFactory.

Multithreading your search can be useful in constraint-solving-intensive paths. Indeed, Python cannot multithread due to its GIL, but z3, written in C, can.

The most important methods you should look at are step, explore, and use_tech.

Parameters:project (angr.project.Project) – A Project instance.

The following parameters are optional.

Parameters:
  • active_paths – Active paths to seed the “active” stash with.
  • stashes – A dictionary to use as the stash store.
  • hierarchy – A PathHierarchy object to use to track path reachability.
  • immutable – If True, all operations will return a new PathGroup. Otherwise (default), all operations will modify the PathGroup (and return it, for consistency and chaining).
  • threads – the number of worker threads to concurrently analyze states (useful in z3-intensive paths).
mulpyplex(*stashes)

Mulpyplex across several stashes.

Parameters:stashes – the stashes to mulpyplex
Returns:a mulpyplexed list of paths from the stashes in question, in the specified order
apply(path_func=None, stash_func=None, stash=None)

Applies a given function to a given stash.

Parameters:
  • path_func – A function to apply to every path. Should take a path and return a path. The returned path will take the place of the old path. If the function doesn’t return a path, the old path will be used. If the function returns a list of paths, they will replace the original paths.
  • stash_func

    A function to apply to the whole stash. Should take a list of paths and return a list of paths. The resulting list will replace the stash.

    If both path_func and stash_func are provided path_func is applied first, then stash_func is applied on the results.

Returns:

The resulting PathGroup.

Return type:

PathGroup

split(stash_splitter=None, stash_ranker=None, path_ranker=None, limit=None, from_stash=None, to_stash=None)

Split a stash of paths. The stash from_stash will be split into two stashes depending on the other options passed in. If to_stash is provided, the second stash will be written there.

stash_splitter overrides stash_ranker, which in turn overrides path_ranker. If no functions are provided, the paths are simply split according to the limit.

The sort done with path_ranker is ascending.

Parameters:
  • stash_splitter – A function that should take a list of paths and return a tuple of two lists (the two resulting stashes).
  • stash_ranker – A function that should take a list of paths and return a sorted list of paths. This list will then be split according to “limit”.
  • path_ranker – An alternative to stash_splitter. Paths will be sorted with outputs of this function. used as a key. The first “limit” of them will be kept, the rest split off.
  • limit – For use with path_ranker. The number of paths to keep. Default: 8
  • from_stash – The stash to split (default: ‘active’)
  • to_stash – The stash to write to (default: ‘stashed’)
Returns:

The resulting PathGroup.

Return type:

PathGroup

step(n=None, selector_func=None, step_func=None, stash=None, successor_func=None, until=None, check_func=None, **kwargs)

Step a stash of paths forward, i.e. run angr.path.Path.step() on each of the individual paths in a stash and categorize the successors appropriately.

The parameters to this function allow you to control everything about the stepping and categorization process.

Parameters:
  • stash – The name of the stash to step (default: ‘active’)
  • n – The number of times to step (default: 1 if “until” is not provided)
  • selector_func – If provided, should be a function that takes a Path and returns a boolean. If True, the path will be stepped. Otherwise, it will be kept as-is.
  • step_func – If provided, should be a function that takes a PathGroup and returns a PathGroup. Will be called with the PathGroup at every step. Note that this function should not actually perform any stepping - it is meant to be a maintenance function called after each step.
  • successor_func – If provided, should be a function that takes a path and return its successors. Otherwise, Path.successors will be used.
  • until – If provided, should be a function that takes a PathGroup and returns True or False. Stepping will terminate when it is True.
  • check_func – If provided, this function will be called to decide whether the current path is errored or not. Otherwise, Path.errored will be used.

Additionally, you can pass in any of the following keyword args for project.factory.sim_run:

Parameters:
  • jumpkind – The jumpkind of the previous exit
  • addr – An address to execute at instead of the state’s ip.
  • stmt_whitelist – A list of stmt indexes to which to confine execution.
  • last_stmt – A statement index at which to stop execution.
  • thumb – Whether the block should be lifted in ARM’s THUMB mode.
  • backup_state – A state to read bytes from instead of using project memory.
  • opt_level – The VEX optimization level to use.
  • insn_bytes – A string of bytes to use for the block instead of the project.
  • size – The maximum size of the block, in bytes.
  • num_inst – The maximum number of instructions.
  • traceflags – traceflags to be passed to VEX. Default: 0
Returns:

The resulting PathGroup.

Return type:

PathGroup

prune(filter_func=None, from_stash=None, to_stash=None)

Prune unsatisfiable paths from a stash. This function will move all unsatisfiable or errored paths in the given stash into a different stash.

Parameters:
  • filter_func – Only prune paths that match this filter.
  • from_stash – Prune paths from this stash. (default: ‘active’)
  • to_stash – Put pruned paths in this stash. (default: ‘pruned’)
Returns:

The resulting PathGroup.

Return type:

PathGroup

move(from_stash, to_stash, filter_func=None)

Move paths from one stash to another.

Parameters:
  • from_stash – Take matching paths from this stash.
  • to_stash – Put matching paths into this stash.
  • filter_func – Stash paths that match this filter. Should be a function that takes a path and returns True or False. Default: stash all paths
Returns:

The resulting PathGroup.

Return type:

PathGroup

stash(filter_func=None, from_stash=None, to_stash=None)

Stash some paths. This is an alias for move(), with defaults for the stashes.

Parameters:
  • filter_func – Stash paths that match this filter. Should be a function. that takes a path and returns True or False. (default: stash all paths)
  • from_stash – Take matching paths from this stash. (default: ‘active’)
  • to_stash – Put matching paths into this stash. (default: ‘stashed’)
Returns:

The resulting PathGroup

Return type:

PathGroup

drop(filter_func=None, stash=None)

Drops paths from a stash. This is an alias for move(), with defaults for the stashes.

Parameters:
  • filter_func – Drop paths that match this filter. Should be a function that takes a path and returns True or False. (default: drop all paths)
  • stash – Drop matching paths from this stash. (default: ‘active’)
Returns:

The resulting PathGroup

Return type:

PathGroup

unstash(filter_func=None, to_stash=None, from_stash=None)

Unstash some paths. This is an alias for move(), with defaults for the stashes.

Parameters:
  • filter_func – Unstash paths that match this filter. Should be a function that takes a path and returns True or False. (default: unstash all paths)
  • from_stash – take matching paths from this stash. (default: ‘stashed’)
  • to_stash – put matching paths into this stash. (default: ‘active’)
Returns:

The resulting PathGroup.

Return type:

PathGroup

merge(merge_func=None, stash=None)

Merge the states in a given stash.

Parameters:
  • stash – The stash (default: ‘active’)
  • merge_func – If provided, instead of using path.merge, call this function with the paths as the argument. Should return the merged path.
Returns:

The result PathGroup.

Return type:

PathGroup

use_technique(tech)

Use an exploration technique with this path group. Techniques can be found in angr.exploration_techniques.

Parameters:tech – An ExplorationTechnique object that contains code to modify this path group’s behavior
stash_not_addr(addr, from_stash=None, to_stash=None)

Stash all paths not at address addr from stash from_stash to stash to_stash.

stash_addr(addr, from_stash=None, to_stash=None)

Stash all paths at address addr from stash from_stash to stash to_stash.

stash_addr_past(addr, from_stash=None, to_stash=None)

Stash all paths containg address addr in their backtrace from stash from_stash to stash to_stash.

stash_not_addr_past(addr, from_stash=None, to_stash=None)

Stash all paths not containg address addr in their backtrace from stash from_stash to stash to_stash.

stash_all(from_stash=None, to_stash=None)

Stash all paths from stash from_stash to stash to_stash.

unstash_addr(addr, from_stash=None, to_stash=None)

Unstash all paths at address addr.

unstash_addr_past(addr, from_stash=None, to_stash=None)

Unstash all paths containing address addr in their backtrace.

unstash_not_addr(addr, from_stash=None, to_stash=None)

Unstash all paths not at address addr.

unstash_not_addr_past(addr, from_stash=None, to_stash=None)

Unstash all paths not containing address addr in their backtrace.

unstash_all(from_stash=None, to_stash=None)

Unstash all paths.

explore(stash=None, n=None, find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, step_func=None)

Tick stash “stash” forward (up to “n” times or until “num_find” paths are found), looking for condition “find”, avoiding condition “avoid”. Stores found paths into “find_stash’ and avoided paths into “avoid_stash”.

The “find” and “avoid” parameters may be any of:

  • An address to find
  • A set or list of addresses to find
  • A function that takes a path and returns whether or not it matches.

If an angr CFG is passed in as the “cfg” parameter and “find” is either a number or a list or a set, then any paths which cannot possibly reach a success state without going through a failure state will be preemptively avoided.

run(stash=None, n=None, step_func=None)

Run until the path group has reached a completed state, according to the current exploration techniques.

TODO: step_func doesn’t work with veritesting, since veritesting replaces the default step logic.

Parameters:
  • stash – Operate on this stash
  • n – Step at most this many times
  • step_func – If provided, should be a function that takes a PathGroup and returns a new PathGroup. Will be called with the current PathGroup at every step.
Returns:

The resulting PathGroup.

Return type:

PathGroup

class angr.exploration_techniques.ExplorationTechnique

An otiegnqwvk is a set of hooks for path groups that assists in the implementation of new techniques in symbolic exploration.

TODO: choose actual name for the functionality (techniques? something?)

Any number of these methods may be overridden by a subclass. To use an exploration technique, call pg.use_technique.

setup(pg)

Perform any initialization on this path group you might need to do.

step_path(path)

Perform the process of stepping a path forward.

If the stepping fails, return None to fall back to a default stepping procedure. Otherwise, return a tuple of lists: successors, unconstrained, unsat, pruned, errored

step(pg, stash, **kwargs)

Step this stash of this path group forward.

Return the stepped path group.

filter(path)

Perform filtering on a path.

If the path should not be filtered, return None. If the path should be filtered, return the name of the stash to move the path to. If you want to modify the path before filtering it, return a tuple of the stash to move the path to and the modified path.

complete(pg)

Return whether or not this path group has reached a “completed” state, i.e. pathgroup.run() should halt.

class angr.exploration_techniques.dfs.DFS

Depth-first search.

Will only keep one path active at a time, any others will be stashed in the ‘deferred’ stash. When we run out of active paths to step, we take the longest one from deferred and continue.

class angr.exploration_techniques.explorer.Explorer(find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False)

Search for up to “num_find” paths that satisfy condition “find”, avoiding condition “avoid”. Stashes found paths into “find_stash’ and avoided paths into “avoid_stash”.

The “find” and “avoid” parameters may be any of:

  • An address to find
  • A set or list of addresses to find
  • A function that takes a path and returns whether or not it matches.

If an angr CFG is passed in as the “cfg” parameter and “find” is either a number or a list or a set, then any paths which cannot possibly reach a success state without going through a failure state will be preemptively avoided.

If either the “find” or “avoid” parameter is a function returning a boolean, and a path triggers both conditions, it will be added to the find stash, unless “avoid_priority” is set to True.

class angr.exploration_techniques.looplimiter.LoopLimiter(count=5, discard_stash='spinning')

Limit the number of loops a path may go through. Paths that exceed the loop limit are moved to a discard stash.

Note that this uses the default detect_loops method from Path, which approximates loop counts by counting the number of times each basic block is executed in a given stack frame.

class angr.exploration_techniques.threading.Threading(threads=8)

Enable multithreading.

This is only useful in paths where a lot of time is taken inside z3, doing constraint solving. This is because of python’s GIL, which says that only one thread at a time may be executing python code.

class angr.exploration_techniques.veritesting.Veritesting(**options)

Enable veritesting. This technique, described in a paper[1] from CMU, attempts to address the problem of state explosions in loops by performing smart merging.

[1] https://users.ece.cmu.edu/~aavgerin/papers/veritesting-icse-2014.pdf

Knowledge Base

Representing the artifacts of a project.

class angr.knowledge_base.KnowledgeBase(project, obj)

Represents a “model” of knowledge about an artifact.

Contains things like a CFG, data references, etc.

class angr.knowledge.function.Function(function_manager, addr, name=None, syscall=False)

A representation of a function and various information about it.

Function constructor

Parameters:
  • addr – The address of the function.
  • name – (Optional) The name of the function.
  • syscall – (Optional) Whether this function is a syscall or not.
blocks

An iterator of all local blocks in the current function.

Returns:angr.lifter.Block instances.
block_addrs

An iterator of all local block addresses in the current function.

Returns:block addresses.
block_addrs_set

Return a set of block addresses for a better performance of inclusion tests.

Returns:A set of block addresses.
Return type:set
operations

All of the operations that are done by this functions.

code_constants

All of the constants that are used by this functions’s code.

string_references(minimum_length=2, vex_only=False)

All of the constant string references used by this function.

Parameters:
  • minimum_length – The minimum length of strings to find (default is 1)
  • vex_only – Only analyze VEX IR, don’t interpret the entry state to detect additional constants.
Returns:

A list of tuples of (address, string) where is address is the location of the string in memory.

local_runtime_values

Tries to find all runtime values of this function which do not come from inputs. These values are generated by starting from a blank state and reanalyzing the basic blocks once each. Function calls are skipped, and back edges are never taken so these values are often unreliable, This function is good at finding simple constant addresses which the function will use or calculate.

Returns:a set of constants
runtime_values

All of the concrete values used by this function at runtime (i.e., including passed-in arguments and global values).

binary

Get the object this function belongs to. :return: The object this function belongs to.

mark_nonreturning_calls_endpoints()

Iterate through all call edges in transition graph. For each call a non-returning function, mark the source basic block as an endpoint.

This method should only be executed once all functions are recovered and analyzed by CFG recovery, so we know whether each function returns or not.

Returns:None
get_call_sites()

Gets a list of all the basic blocks that end in calls.

Returns:A list of the addresses of the blocks that end in calls.
get_call_target(callsite_addr)

Get the target of a call.

Parameters:callsite_addr – The address of a basic block that ends in a call.
Returns:The target of said call, or None if callsite_addr is not a callsite.
get_call_return(callsite_addr)

Get the hypothetical return address of a call.

Parameters:callsite_addr – The address of the basic block that ends in a call.
Returns:The likely return target of said call, or None if callsite_addr is not a callsite.
graph

Return a local transition graph that only contain nodes in current function.

subgraph(ins_addrs)

Generate a sub control flow graph of instruction addresses based on self.graph

Parameters:ins_addrs (iterable) – A collection of instruction addresses that should be included in the subgraph.
Returns:A subgraph.
Return type:networkx.DiGraph
instruction_size(insn_addr)

Get the size of the instruction specified by insn_addr.

Parameters:insn_addr (int) – Address of the instruction
Returns:Size of the instruction in bytes, or None if the instruction is not found.
Return type:int
dbg_print()

Returns a representation of the list of basic blocks in this function.

dbg_draw(filename)

Draw the graph and save it to a PNG file.

normalize()

Make sure all basic blocks in the transition graph of this function do not overlap. You will end up with a CFG that IDA Pro generates.

This method does not touch the CFG result. You may call CFG{Accurate, Fast}.normalize() for that matter.

Returns:None
class angr.knowledge.function_manager.FunctionDict(backref, *args, **kwargs)

FunctionDict is a dict where the keys are function starting addresses and map to the associated Function.

class angr.knowledge.function_manager.FunctionManager(kb)

This is a function boundaries management tool. It takes in intermediate results during CFG generation, and manages a function map of the binary.

function(addr=None, name=None, create=False, syscall=False, plt=None)

Get a function object from the function manager.

Pass either addr or name with the appropriate values.

Parameters:
  • addr (int) – Address of the function.
  • name (str) – Name of the function.
  • create (bool) – Whether to create the function or not if the function does not exist.
  • syscall (bool) – True to create the function as a syscall, False otherwise.
  • or None plt (bool) – True to find the PLT stub, False to find a non-PLT stub, None to disable this restriction.
Returns:

The Function instance, or None if the function is not found and create is False.

Return type:

Function or None

Analysis

class angr.analysis.Analyses(p)

This class contains functions for all the registered and runnable analyses,

Creates an Analyses object

Variables:p – A project
class angr.analysis.Analysis

This class represents an analysis on the program.

Variables:
  • project – The project for this analysis.
  • kb (KnowledgeBase) – The knowledgebase object.
  • _progress_callback (callable) – A callback function for receiving the progress of this analysis. It only takes one argument, which is a float number from 0.0 to 100.0 indicating the current progress.
  • _show_progressbar (bool) – If a progressbar should be shown during the analysis. It’s independent from _progress_callback.
  • _progressbar (progressbar.ProgressBar) – The progress bar object.
class angr.annocfg.AnnotatedCFG(project, cfg=None, detect_loops=False)

AnnotatedCFG is a control flow graph with statement whitelists and exit whitelists to describe a slice of the program.

Constructor.

Parameters:
  • project – The angr Project instance
  • cfg – Control flow graph. Only used when path prioritizer is used.
  • detect_loops – Only used when path prioritizer is used.
from_digraph(digraph)

Initialize this AnnotatedCFG object with a networkx.DiGraph consisting of the following form of nodes:

Tuples like (block address, statement ID)

Those nodes are connected by edges indicating the execution flow.

Parameters:digraph – A networkx.DiGraph object
add_loop(loop_tuple)

A loop tuple contains a series of IRSB addresses that form a loop. Ideally it always starts with the first IRSB that we meet during the execution.

get_whitelisted_statements(addr)
Returns:True if all statements are whitelisted
dbg_print_irsb(irsb_addr, project=None)

Pretty-print an IRSB with whitelist information

keep_path(path)

Given a path, returns True if the path should be kept, False if it should be cut.

filter_path(path)

Used for debugging.

Parameters:path – A Path instance
Returns:True/False
path_priority(path)

Given a path, returns the path priority. A lower number means a higher priority.

successor_func(path)

Callback routine that takes in a path, and returns all feasible successors to path group. This callback routine should be passed to the keyword argument “successor_func” of PathGroup.step().

Parameters:path – A Path instance.
Returns:A list of all feasible Path successors.
class angr.blade.Blade(graph, dst_run, dst_stmt_idx, direction='backward', project=None, cfg=None, ignore_sp=False, ignore_bp=False, ignored_regs=None, max_level=3)

Blade is a light-weight program slicer that works with networkx DiGraph containing CFGNodes. It is meant to be used in angr for small or on-the-fly analyses.

Parameters:
  • graph (networkx.DiGraph) – A graph representing the control flow graph. Note that it does not take angr.analyses.CFGAccurate or angr.analyses.CFGFast.
  • dst_run (int) – An address specifying the target SimRun.
  • dst_stmt_idx (int) – The target statement index. -1 means executing until the last statement.
  • direction (str) – ‘backward’ or ‘forward’ slicing. Forward slicing is not yet supported.
  • project (angr.Project) – The project instance.
  • cfg (angr.analyses.CFGBase) – the CFG instance. It will be made mandatory later.
  • ignore_sp (bool) – Whether the stack pointer should be ignored in dependency tracking. Any dependency from/to stack pointers will be ignored if this options is True.
  • ignore_bp (bool) – Whether the base pointer should be ignored or not.
  • max_level (int) – The maximum number of blocks that we trace back for.
Returns:

None

class angr.analyses.backward_slice.BackwardSlice(cfg, cdg, ddg, targets=None, cfg_node=None, stmt_id=None, control_flow_slice=False, same_function=False, no_construct=False)

Represents a backward slice of the program.

Create a backward slice from a specific statement based on provided control flow graph (CFG), control dependence graph (CDG), and data dependence graph (DDG).

The data dependence graph can be either CFG-based, or Value-set analysis based. A CFG-based DDG is much faster to generate, but it only reflects those states while generating the CFG, and it is neither sound nor accurate. The VSA based DDG (called VSA_DDG) is based on static analysis, which gives you a much better result.

Parameters:
  • cfg – The control flow graph.
  • cdg – The control dependence graph.
  • ddg – The data dependence graph.
  • targets – A list of “target” that specify targets of the backward slices. Each target can be a tuple in form of (cfg_node, stmt_idx), or a CodeLocation instance.
  • cfg_node – Deprecated. The target CFGNode to reach. It should exist in the CFG.
  • stmt_id – Deprecated. The target statement to reach.
  • control_flow_slice – True/False, indicates whether we should slice only based on CFG. Sometimes when acquiring DDG is difficult or impossible, you can just create a slice on your CFG. Well, if you don’t even have a CFG, then...
  • no_construct – Only used for testing and debugging to easily create a BackwardSlice object.
dbg_repr(max_display=10)

Debugging output of this slice.

Parameters:max_display – The maximum number of SimRun slices to show.
Returns:A string representation.
dbg_repr_run(run_addr)

Debugging output of a single SimRun slice.

Parameters:run_addr – Address of the SimRun.
Returns:A string representation.
annotated_cfg(start_point=None)

Returns an AnnotatedCFG based on slicing result.

Query in taint graph to check if a specific taint will taint the IP in the future or not. The taint is specified with the tuple (simrun_addr, stmt_idx, taint_type).

Parameters:
  • simrun_addr – Address of the SimRun.
  • stmt_idx – Statement ID.
  • taint_type – Type of the taint, might be one of the following: ‘reg’, ‘tmp’, ‘mem’.
  • simrun_whitelist – A list of SimRun addresses that are whitelisted, i.e. the tainted exit will be ignored if it is in those SimRuns.
Returns:

True/False

is_taint_impacting_stack_pointers(simrun_addr, stmt_idx, taint_type, simrun_whitelist=None)

Query in taint graph to check if a specific taint will taint the stack pointer in the future or not. The taint is specified with the tuple (simrun_addr, stmt_idx, taint_type).

Parameters:
  • simrun_addr – Address of the SimRun.
  • stmt_idx – Statement ID.
  • taint_type – Type of the taint, might be one of the following: ‘reg’, ‘tmp’, ‘mem’.
  • simrun_whitelist – A list of SimRun addresses that are whitelisted.
Returns:

True/False.

angr.analyses.bindiff.differing_constants(block_a, block_b)

Compares two basic blocks and finds all the constants that differ from the first block to the second.

Parameters:
  • block_a – The first block to compare.
  • block_b – The second block to compare.
Returns:

Returns a list of differing constants in the form of ConstantChange, which has the offset in the block and the respective constants.

class angr.analyses.bindiff.FunctionDiff(function_a, function_b, bindiff=None)

This class computes the a diff between two functions.

Parameters:
  • function_a – The first angr Function object to diff.
  • function_b – The second angr Function object.
  • bindiff – An optional Bindiff object. Used for some extra normalization during basic block comparison.
probably_identical

returns – Whether or not these two functions are identical.

identical_blocks

returns – A list of block matches which appear to be identical

differing_blocks

returns – A list of block matches which appear to differ

blocks_with_differing_constants

return – A list of block matches which appear to differ

static get_normalized_block(addr, function)
Parameters:
  • addr – Where to start the normalized block.
  • function – A function containing the block address.
Returns:

A normalized basic block.

block_similarity(block_a, block_b)
Parameters:
  • block_a – The first block address.
  • block_b – The second block address.
Returns:

The similarity of the basic blocks, normalized for the base address of the block and function call addresses.

blocks_probably_identical(block_a, block_b, check_constants=False)
Parameters:
  • block_a – The first block address.
  • block_b – The second block address.
  • check_constants – Whether or not to require matching constants in blocks.
Returns:

Whether or not the blocks appear to be identical.

class angr.analyses.bindiff.BinDiff(other_project, enable_advanced_backward_slicing=False, cfg_a=None, cfg_b=None)

This class computes the a diff between two binaries represented by angr Projects

Parameters:other_project – The second project to diff
functions_probably_identical(func_a_addr, func_b_addr, check_consts=False)

Compare two functions and return True if they appear identical.

Parameters:
  • func_a_addr – The address of the first function (in the first binary).
  • func_b_addr – The address of the second function (in the second binary).
Returns:

Whether or not the functions appear to be identical.

identical_functions

returns – A list of function matches that appear to be identical

differing_functions

returns – A list of function matches that appear to differ

differing_functions_with_consts()
Returns:A list of function matches that appear to differ including just by constants
differing_blocks

returns – A list of block matches that appear to differ

identical_blocks

return A list of all block matches that appear to be identical

blocks_with_differing_constants

return – A dict of block matches with differing constants to the tuple of constants

get_function_diff(function_addr_a, function_addr_b)
Parameters:
  • function_addr_a – The address of the first function (in the first binary)
  • function_addr_b – The address of the second function (in the second binary)
Returns:

the FunctionDiff of the two functions

class angr.analyses.boyscout.BoyScout(cookiesize=1)

Try to determine the architecture and endieness of a binary blob

class angr.analyses.cdg.TemporaryNode(label)

A temporary node.

Used as the start node and end node in post-dominator tree generation. Also used in some test cases.

class angr.analyses.cdg.ContainerNode(obj)

A container node.

Only used in post-dominator tree generation. We did this so we can set the index property without modifying the original object.

class angr.analyses.cdg.CDG(cfg, start=None, no_construct=False)

Implements a control dependence graph.

Constructor.

Parameters:
  • cfg – The control flow graph upon which this control dependence graph will build
  • start – The starting point to begin constructing the control dependence graph
  • no_construct – Skip the construction step. Only used in unit-testing.
get_post_dominators()

Return the post-dom tree

get_dependants(run)

Return a list of nodes that are control dependent on the given node in the control dependence graph

get_guardians(run)

Return a list of nodes on whom the specific node is control dependent in the control dependence graph

class angr.analyses.cfg_accurate.CFGAccurate(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None)

This class represents a control-flow graph.

All parameters are optional.

Parameters:
  • context_sensitivity_level – The level of context-sensitivity of this CFG (see documentation for further details). It ranges from 0 to infinity. Default 1.
  • avoid_runs – A list of runs to avoid.
  • enable_function_hints – Whether to use function hints (constants that might be used as exit targets) or not.
  • call_depth – How deep in the call stack to trace.
  • call_tracing_filter – Filter to apply on a given path and jumpkind to determine if it should be skipped when call_depth is reached.
  • initial_state – An initial state to use to begin analysis.
  • starts (iterable) – A collection of starting points to begin analysis. It can contain the following three different types of entries: an address specified as an integer, a 2-tuple that includes an integer address and a jumpkind, or a SimState instance. Unsupported entries in starts will lead to an AngrCFGError being raised.
  • keep_state – Whether to keep the SimStates for each CFGNode.
  • enable_advanced_backward_slicing – Whether to enable an intensive technique for resolving direct jumps
  • enable_symbolic_back_traversal – Whether to enable an intensive technique for resolving indirect jumps
  • additional_edges – A dict mapping addresses of basic blocks to addresses of successors to manually include and analyze forward from.
  • no_construct (bool) – Skip the construction procedure. Only used in unit-testing.
  • normalize (bool) – If the CFG as well as all Function graphs should be normalized or not.
  • max_iterations (int) – The maximum number of iterations that each basic block should be “executed”. 1 by default. Larger numbers of iterations are usually required for complex analyses like loop analysis.
  • address_whitelist (iterable) – A list of allowed addresses. Any basic blocks outside of this collection of addresses will be ignored.
  • base_graph (networkx.DiGraph) – A basic control flow graph to follow. Each node inside this graph must have the following properties: addr and size. CFG recovery will strictly follow nodes and edges shown in the graph, and discard any contorl flow that does not follow an existing edge in the base graph. For example, you can pass in a Function local transition graph as the base graph, and CFGAccurate will traverse nodes and edges and extract useful information.
  • iropt_level (int) – The optimization level of VEX IR (0, 1, 2). The default level will be used if iropt_level is None.
  • max_steps (int) – The maximum number of basic blocks to recover forthe longest path from each start before pausing the recovery procedure.
copy()

Make a copy of the CFG.

Returns:A copy of the CFG instance.
Return type:angr.analyses.CFG
resume(starts=None, max_steps=None)

Resume a paused or terminated control flow graph recovery.

Parameters:
  • starts (iterable) – A collection of new starts to resume from. If starts is None, we will resume CFG recovery from where it was paused before.
  • max_steps (int) – The maximum number of blocks on the longest path starting from each start before pausing the recovery.
Returns:

None

remove_cycles()

Forces graph to become acyclic, removes all loop back edges and edges between overlapped loop headers and their successors.

downsize()

Remove saved states from all CFGNodes to reduce memory usage.

Returns:None
unroll_loops(max_loop_unrolling_times)

Unroll loops for each function. The resulting CFG may still contain loops due to recursion, function calls, etc.

Parameters:max_loop_unrolling_times (int) – The maximum iterations of unrolling.
Returns:None
force_unroll_loops(max_loop_unrolling_times)

Unroll loops globally. The resulting CFG does not contain any loop, but this method is slow on large graphs.

Parameters:max_loop_unrolling_times (int) – The maximum iterations of unrolling.
Returns:None
immediate_dominators(start, target_graph=None)

Get all immediate dominators of sub graph from given node upwards.

Parameters:
  • start (str) – id of the node to navigate forwards from.
  • target_graph (networkx.classes.digraph.DiGraph) – graph to analyse, default is self.graph.
Returns:

each node of graph as index values, with element as respective node’s immediate dominator.

Return type:

dict

immediate_postdominators(end, target_graph=None)

Get all immediate postdominators of sub graph from given node upwards.

Parameters:
  • start (str) – id of the node to navigate forwards from.
  • target_graph (networkx.classes.digraph.DiGraph) – graph to analyse, default is self.graph.
Returns:

each node of graph as index values, with element as respective node’s immediate dominator.

Return type:

dict

remove_fakerets()

Get rid of fake returns (i.e., Ijk_FakeRet edges) from this CFG

Returns:None
get_topological_order(cfg_node)

Get the topological order of a CFG Node.

Parameters:cfg_node – A CFGNode instance.
Returns:An integer representing its order, or None if the CFGNode does not exist in the graph.
get_subgraph(starting_node, block_addresses)

Get a sub-graph out of a bunch of basic block addresses.

Parameters:
  • starting_node (CFGNode) – The beginning of the subgraph
  • block_addresses (iterable) – A collection of block addresses that should be included in the subgraph if there is a path between starting_node and a CFGNode with the specified address, and all nodes on the path should also be included in the subgraph.
Returns:

A new CFG that only contain the specific subgraph.

Return type:

CFGAccurate

get_function_subgraph(start, max_call_depth=None)

Get a sub-graph of a certain function.

Parameters:
  • start – The function start. Currently it should be an integer.
  • max_call_depth – Call depth limit. None indicates no limit.
Returns:

A CFG instance which is a sub-graph of self.graph

unresolvables

Get those SimRuns that have non-resolvable exits.

Returns:A set of SimRuns
Return type:set
deadends

Get all CFGNodes that has an out-degree of 0

Returns:A list of CFGNode instances
Return type:list
class angr.analyses.cfg_base.CFGBase(sort, context_sensitivity_level, normalize=False, binary=None, force_segment=False, iropt_level=None)

The base class for control flow graphs.

make_copy(copy_to)

Copy self attributes to the new object.

Parameters:copy_to (CFGBase) – The target to copy to.
Returns:None
generate_index()

Generate an index of all nodes in the graph in order to speed up get_any_node() with anyaddr=True.

Returns:None
get_predecessors(cfgnode, excluding_fakeret=True, jumpkind=None)

Get predecessors of a node in the control flow graph.

Parameters:
  • cfgnode (CFGNode) – The node.
  • excluding_fakeret (bool) – True if you want to exclude all predecessors that is connected to the node with a fakeret edge.
  • or None jumpkind (str) – Only return predecessors with the specified jumpkind. This argument will be ignored if set to None.
Returns:

A list of predecessors

Return type:

list

get_successors(basic_block, excluding_fakeret=True, jumpkind=None)

Get successors of a node in the control flow graph.

Parameters:
  • cfgnode (CFGNode) – The node.
  • excluding_fakeret (bool) – True if you want to exclude all successors that is connected to the node with a fakeret edge.
  • or None jumpkind (str) – Only return successors with the specified jumpkind. This argument will be ignored if set to None.
Returns:

A list of successors

Return type:

list

get_all_predecessors(cfgnode)

Get all predecessors of a specific node on the control flow graph.

Parameters:cfgnode (CFGNode) – The CFGNode object
Returns:A list of predecessors in the CFG
Return type:list
get_node(block_id)

Get a single node from node key.

Parameters:block_id (BlockID) – Block ID of the node.
Returns:The CFGNode
Return type:CFGNode
get_any_node(addr, is_syscall=None, anyaddr=False)

Get an arbitrary CFGNode (without considering their contexts) from our graph.

Parameters:
  • addr (int) – Address of the beginning of the basic block. Set anyaddr to True to support arbitrary address.
  • is_syscall (bool) – Whether you want to get the syscall node or any other node. This is due to the fact that syscall SimProcedures have the same address as the targer it returns to. None means get either, True means get a syscall node, False means get something that isn’t a syscall node.
  • anyaddr (bool) – If anyaddr is True, then addr doesn’t have to be the beginning address of a basic block. By default the entire graph.nodes() will be iterated, and the first node containing the specific address is returned, which is slow. If you need to do many such queries, you may first call generate_index() to create some indices that may speed up the query.
Returns:

A CFGNode if there is any that satisfies given conditions, or None otherwise

irsb_from_node(cfg_node)

Create an IRSB from a CFGNode object.

get_any_irsb(addr)

Returns an IRSB of a certain address. If there are many IRSBs with the same address in CFG, return an arbitrary one. You should never assume this method returns a specific IRSB.

Parameters:addr (int) – Address of the IRSB to get.
Returns:An arbitrary IRSB located at addr.
Return type:simuvex.IRSB
get_all_nodes(addr, is_syscall=None, anyaddr=False)

Get all CFGNodes whose address is the specified one.

Parameters:
  • addr – Address of the node
  • is_syscall – True returns the syscall node, False returns the normal CFGNode, None returns both
Returns:

all CFGNodes

nodes_iter()

An iterator of all nodes in the graph.

Returns:The iterator.
Return type:iterator
get_all_irsbs(addr)

Returns all IRSBs of a certain address, without considering contexts.

get_branching_nodes()

Returns all nodes that has an out degree >= 2

get_exit_stmt_idx(src_block, dst_block)

Get the corresponding exit statement ID for control flow to reach destination block from source block. The exit statement ID was put on the edge when creating the CFG. Note that there must be a direct edge between the two blocks, otherwise an exception will be raised.

Returns:The exit statement ID
normalize()

Normalize the CFG, making sure that there are no overlapping basic blocks.

Note that this method will not alter transition graphs of each function in self.kb.functions. You may call normalize() on each Function object to normalize their transition graphs.

Returns:None
remove_function_alignments()

Remove all function alignments.

Returns:None
make_functions()

Revisit the entire control flow graph, create Function instances accordingly, and correctly put blocks into each function.

Although Function objects are crated during the CFG recovery, they are neither sound nor accurate. With a pre-constructed CFG, this method rebuilds all functions bearing the following rules:

  • A block may only belong to one function.
  • Small functions lying inside the startpoint and the endpoint of another function will be merged with the other function
  • Tail call optimizations are detected.
  • PLT stubs are aligned by 16.
Returns:None
class angr.analyses.cfg_fast.Segment(start, end, sort)

Representing a memory block. This is not the “Segment” in ELF memory model

Parameters:
  • start (int) – Start address.
  • end (int) – End address.
  • sort (str) – Type of the segment, can be code, data, etc.
Returns:

None

size

Calculate the size of the Segment.

Returns:Size of the Segment.
Return type:int
copy()

Make a copy of the Segment.

Returns:A copy of the Segment instance.
Return type:angr.analyses.cfg_fast.Segment
class angr.analyses.cfg_fast.SegmentList

SegmentList describes a series of segmented memory blocks. You may query whether an address belongs to any of the blocks or not, and obtain the exact block(segment) that the address belongs to.

next_free_pos(address)

Returns the next free position with respect to an address, including that address itself

Parameters:address – The address to begin the search with (including itself)
Returns:The next free position
is_occupied(address)

Check if an address belongs to any segment

Parameters:address – The address to check
Returns:True if this address belongs to a segment, False otherwise
occupied_by_sort(address)

Check if an address belongs to any segment, and if yes, returns the sort of the segment

Parameters:address (int) – The address to check
Returns:Sort of the segment that occupies this address
Return type:str
occupy(address, size, sort)

Include a block, specified by (address, size), in this segment list.

Parameters:
  • address (int) – The starting address of the block.
  • size (int) – Size of the block.
  • sort (str) – Type of the block.
Returns:

None

copy()

Make a copy of the SegmentList.

Returns:A copy of the SegmentList instance.
Return type:angr.analyses.cfg_fast.SegmentList
occupied_size

The sum of sizes of all blocks

Returns:An integer
has_blocks

Returns if this segment list has any block or not. !is_empty

Returns:True if it’s not empty, False otherwise
class angr.analyses.cfg_fast.FunctionReturn(callee_func_addr, caller_func_addr, call_site_addr, return_to)

FunctionReturn describes a function call in a specific location and its return location. Hashable and equatable

class angr.analyses.cfg_fast.MemoryData(address, size, sort, irsb, irsb_addr, stmt, stmt_idx, pointer_addr=None, max_size=None, insn_addr=None)

MemoryData describes the syntactic contents of single address of memory along with a set of references to this address (when not from previous instruction).

copy()

Make a copy of the MemoryData.

Returns:A copy of the MemoryData instance.
Return type:angr.analyses.cfg_fast.MemoryData
add_ref(irsb_addr, stmt_idx, insn_addr)

Add a reference from code to this memory data.

Parameters:
  • irsb_addr (int) – Address of the basic block.
  • stmt_idx (int) – ID of the statement referencing this data entry.
  • insn_addr (int) – Address of the instruction referencing this data entry.
Returns:

None

class angr.analyses.cfg_fast.CFGJob(addr, func_addr, jumpkind, ret_target=None, last_addr=None, src_node=None, src_ins_addr=None, src_stmt_idx=None, returning_source=None, syscall=False)

Defines a job to work on during the CFG recovery

class angr.analyses.cfg_fast.CFGFast(binary=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_complete_scan=True, indirect_jump_target_limit=100000, collect_data_references=False, extra_cross_references=False, normalize=False, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, start=None, end=None, **extra_arch_options)

We find functions inside the given binary, and build a control-flow graph in very fast manners: instead of simulating program executions, keeping track of states, and performing expensive data-flow analysis, CFGFast will only perform light-weight analyses combined with some heuristics, and with some strong assumptions.

In order to identify as many functions as possible, and as accurate as possible, the following operation sequence is followed:

# Active scanning

  • If the binary has “function symbols” (TODO: this term is not accurate enough), they are starting points of
    the code scanning
  • If the binary does not have any “function symbol”, we will first perform a function prologue scanning on the
    entire binary, and start from those places that look like function beginnings
  • Otherwise, the binary’s entry point will be the starting point for scanning

# Passive scanning

  • After all active scans are done, we will go through the whole image and scan all code pieces

Due to the nature of those techniques that are used here, a base address is often not required to use this analysis routine. However, with a correct base address, CFG recovery will almost always yield a much better result. A custom analysis, called GirlScout, is specifically made to recover the base address of a binary blob. After the base address is determined, you may want to reload the binary with the new base address by creating a new Project object, and then re-recover the CFG.

Parameters:
  • binary – The binary to recover CFG on. By default the main binary is used.
  • regions (iterable) – A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.
  • pickle_intermediate_results (bool) – If we want to store the intermediate results or not.
  • symbols (bool) – Get function beginnings from symbols in the binary.
  • function_prologues (bool) – Scan the binary for function prologues, and use those positions as function beginnings
  • resolve_indirect_jumps (bool) – Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.
  • force_segment (bool) – Force CFGFast to rely on binary segments instead of sections.
  • force_complete_scan (bool) – Perform a complete scan on the binary and maximize the number of identified code blocks.
  • collect_data_references (bool) – If CFGFast should collect data references from individual basic blocks or not.
  • extra_cross_references (bool) – True if we should collect data references for all places in the program that access each memory data entry, which requires more memory, and is noticeably slower. Setting it to False means each memory data entry has at most one reference (which is the initial one).
  • normalize (bool) – Normalize the CFG as well as all function graphs after CFG recovery.
  • function_starts (list) – A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.
  • extra_memory_regions (list) – A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.
  • start (int) – (Deprecated) The beginning address of CFG recovery.
  • end (int) – (Deprecated) The end address of CFG recovery.
  • arch_options (CFGArchOptions) – Architecture-specific options.
  • extra_arch_options (dict) – Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

Parameters:
  • progress_callback – Specify a callback function to get the progress during CFG recovery.
  • show_progressbar (bool) – Should CFGFast show a progressbar during CFG recovery or not.
Returns:

None

functions

A collection of all functions in current CFG via FunctionManager

Returns:FunctionManager with all functions
Return type:angr.knowedge.function_manager.FunctionManager
generate_code_cover()

Generate a list of all recovered basic blocks.

class angr.analyses.cfg_node.CFGNode(addr, size, cfg, callstack=None, input_state=None, simprocedure_name=None, syscall_name=None, looping_times=0, no_ret=False, is_syscall=False, syscall=None, function_address=None, final_states=None, block_id=None, irsb=None, instruction_addrs=None, depth=None, callstack_key=None)

This class stands for each single node in CFG.

Note: simprocedure_name is not used to recreate the SimProcedure object. It’s only there for better __repr__.

downsize()

Drop saved states.

class angr.analyses.code_location.CodeLocation(block_addr, stmt_idx, sim_procedure=None, ins_addr=None, **kwargs)

Stands for a specific program point by specifying basic block address and statement ID (for IRSBs), or SimProcedure name (for SimProcedures).

Constructor.

Parameters:
  • block_addr (int) – Address of the block
  • stmt_idx (int) – Statement ID. None for SimProcedures
  • sim_procedure (class) – The corresponding SimProcedure class.
  • ins_addr (int) – The instruction address. Optional.
  • kwargs – Optional arguments, will be stored, but not used in __eq__ or __hash__.
class angr.analyses.ddg.ProgramVariable(variable, location, initial=False)

Describes a variable in the program at a specific location.

Variables:
  • variable (SimVariable) – The variable.
  • location (CodeLocation) – Location of the variable.
class angr.analyses.ddg.LiveDefinitions

A collection of live definitions with some handy interfaces for definition killing and lookups.

Constructor.

branch()

Create a branch of the current live definition collection.

Returns:A new LiveDefinition instance.
Return type:LiveDefinitions
copy()

Make a hard copy of self.

Returns:A new LiveDefinition instance.
Return type:LiveDefinitions
add_def(variable, location, size_threshold=32)

Add a new definition of variable.

Parameters:
  • variable (SimVariable) – The variable being defined.
  • location (CodeLocation) – Location of the varaible being defined.
  • size_threshold (int) – The maximum bytes to consider for the variable.
Returns:

True if the definition was new, False otherwise

Return type:

bool

add_defs(variable, locations, size_threshold=32)

Add a collection of new definitions of a variable.

Parameters:
  • variable (SimVariable) – The variable being defined.
  • locations (iterable) – A collection of locations where the variable was defined.
  • size_threshold (int) – The maximum bytes to consider for the variable.
Returns:

True if any of the definition was new, False otherwise

Return type:

bool

kill_def(variable, location, size_threshold=32)

Add a new definition for variable and kill all previous definitions.

Parameters:
  • variable (SimVariable) – The variable to kill.
  • location (CodeLocation) – The location where this variable is defined.
  • size_threshold (int) – The maximum bytes to consider for the variable.
Returns:

None

lookup_defs(variable, size_threshold=32)

Find all definitions of the varaible

Parameters:
  • variable (SimVariable) – The variable to lookup for.
  • size_threshold (int) – The maximum bytes to consider for the variable. For example, if the variable is 100 byte long, only the first size_threshold bytes are considered.
Returns:

A set of code locations where the variable is defined.

Return type:

set

iteritems()

An iterator that returns all live definitions.

Returns:The iterator.
Return type:iter
itervariables()

An iterator that returns all live variables.

Returns:The iterator.
Return type:iter
class angr.analyses.ddg.DDG(cfg, start=None, call_depth=None)

This is a fast data dependence graph directly generated from our CFG analysis result. The only reason for its existence is the speed. There is zero guarantee for being sound or accurate. You are supposed to use it only when you want to track the simplest data dependence, and you do not care about soundness or accuracy.

For a better data dependence graph, please consider performing a better static analysis first (like Value-set Analysis), and then construct a dependence graph on top of the analysis result (for example, the VFG in angr).

Also note that since we are using states from CFG, any improvement in analysis performed on CFG (like a points-to analysis) will directly benefit the DDG.

Parameters:
  • cfg – Control flow graph. Please make sure each node has an associated state with it. You may want to generate your CFG with keep_state=True.
  • start – An address, Specifies where we start the generation of this data dependence graph.
  • call_depth – None or integers. A non-negative integer specifies how deep we would like to track in the call tree. None disables call_depth limit.
graph

returns – A networkx DiGraph instance representing the dependence relations between statements. :rtype: networkx.DiGraph

data_graph

Get the data dependence graph.

Returns:A networkx DiGraph instance representing data dependence.
Return type:networkx.DiGraph
simplified_data_graph

return

pp()

Pretty printing.

dbg_repr()

Representation for debugging.

get_predecessors(code_location)

Returns all predecessors of the code location.

Parameters:code_location – A CodeLocation instance.
Returns:A list of all predecessors.
function_dependency_graph(func)

Get a dependency graph for the function func.

Parameters:func – The Function object in CFG.function_manager.
Returns:A networkx.DiGraph instance.
data_sub_graph(pv, simplified=True, killing_edges=False, excluding_types=None)

Get a subgraph from the data graph or the simplified data graph that starts from node pv.

Parameters:
  • pv (ProgramVariable) – The starting point of the subgraph.
  • simplified (bool) – When True, the simplified data graph is used, otherwise the data graph is used.
  • killing_edges (bool) – Are killing edges included or not.
  • excluding_types (iterable) – Excluding edges whose types are among those excluded types.
Returns:

A subgraph.

Return type:

networkx.MultiDiGraph

find_definitions(variable, simplified_graph=True)

Find all definitions of the given variable.

Parameters:
  • variable (SimVariable) –
  • simplified_graph (bool) – True if you just want to search in the simplified graph instead of the normal graph. Usually the simplified graph suffices for finding definitions of register or memory variables.
Returns:

A collection of all variable definitions to the specific variable.

Return type:

list

find_consumers(var_def, simplified_graph=True)

Find all consumers to the specified variable definition.

Parameters:
  • var_def (ProgramVariable) – The variable definition.
  • simplified_graph (bool) – True if we want to search in the simplified graph, False otherwise.
Returns:

A collection of all consumers to the specified variable definition.

Return type:

list

find_killers(var_def, simplified_graph=True)

Find all killers to the specified variable definition.

Parameters:
  • var_def (ProgramVariable) – The variable definition.
  • simplified_graph (bool) – True if we want to search in the simplified graph, False otherwise.
Returns:

A collection of all killers to the specified variable definition.

Return type:

list

find_sources(var_def, simplified_graph=True)

Find all sources to the specified variable definition.

Parameters:
  • var_def (ProgramVariable) – The variable definition.
  • simplified_graph (bool) – True if we want to search in the simplified graph, False otherwise.
Returns:

A collection of all sources to the specified variable definition.

Return type:

list

class angr.analyses.forward_analysis.EntryInfo(key, entry)

Stores information for each entry

entry

Get the latest available entry.

Returns:The latest available entry.
add_entry(entry, merged=False, widened=False)

Appended a new entry to this EntryInfo node. :param entry: The new entry to append :param bool merged: Whether it is a merged entry or not. :param bool widened: Whether it is a widened entry or not.

class angr.analyses.forward_analysis.ForwardAnalysis(order_entries=False, allow_merging=False, allow_widening=False, status_callback=None)

This is my very first attempt to build a static forward analysis framework that can serve as the base of multiple static analyses in angr, including CFG analysis, VFG analysis, DDG, etc.

In short, ForwardAnalysis performs a forward data-flow analysis by traversing the CFG (or the binary if a CFG is not available) and generating a graph with nodes linked with each program point (usually per basic-block, or SimRun in angr terms). A node on the graph stores analysis-specific information. For more information about nodes, take a look at the implementation of CFGNode.

Feel free to discuss with me (Fish) if you have any suggestion or complaint!

Constructor

Parameters:
  • order_entries (bool) – If all entries should be ordered or not.
  • allow_merging (bool) – If entry merging is allowed.
  • allow_widening (bool) – If entry widening is allowed.
Returns:

None

should_abort

Should the analysis be terminated. :return: True/False

abort()

Abort the analysis :return: None

class angr.analyses.girlscout.GirlScout(binary=None, start=None, end=None, pickle_intermediate_results=False, perform_full_code_scan=False)

We find functions inside the given binary, try to decide the base address if needed, and build a control-flow graph on top of that to see if there is an entry or not. Obviously if the binary is not loaded as a blob (not using Blob as its backend), GirlScout will not try to determine the base address.

It’s also optional to perform a full code scan of the binary to show where all codes are. By default we don’t scan the entire binary since it’s time consuming.

You probably need a BoyScout to determine the possible architecture and endianess of your binary blob.

genenare_callmap_sif(filepath)

Generate a sif file from the call map

generate_code_cover()

Generate a list of all recovered basic blocks.

class angr.analyses.loopfinder.LoopFinder(functions=None, normalize=True)

Extracts all the loops from all the functions in a binary.

class angr.analyses.veritesting.CallTracingFilter(project, depth, blacklist=None)

Filter to apply during CFG creation on a given path and jumpkind to determine if it should be skipped at a certain depth

filter(call_target_state, jumpkind)

The call will be skipped if it returns True.

Parameters:
  • call_target_state – The new state of the call target.
  • jumpkind – The Jumpkind of this call.
Returns:

True if we want to skip this call, False otherwise.

class angr.analyses.veritesting.Veritesting(input_path, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None, path_callback=None)

An exploration technique made for condensing chunks of code to single (nested) if-then-else constraints via CFG accurate to conduct Static Symbolic Execution SSE (conversion to single constraint)

SSE stands for Static Symbolic Execution, and we also implemented an extended version of Veritesting (Avgerinos, Thanassis, et al, ICSE 2014).

Parameters:
  • input_path – The initial path to begin the execution with.
  • boundaries – Addresses where execution should stop.
  • loop_unrolling_limit – The maximum times that Veritesting should unroll a loop for.
  • enable_function_inlining – Whether we should enable function inlining and syscall inlining.
  • terminator – A callback function that takes a path as parameter. Veritesting will terminate if this function returns True.
  • deviation_filter – A callback function that takes a path as parameter. Veritesting will put the path into “deviated” stash if this function returns True.
  • path_callback – A callback function that takes a path as parameter. Veritesting will call this function on every single path after their next_run is created.
is_path_errored(path)

Returns true if the path has errored, most recent jump was error/signal, or if exeception caught on step forward

param Path path: The Path instance to test returns bool: True if path instance has errored

generate_successors(path, path_group)

Gets the successors to the current path by step, saves copy of path and finally stashes new unconstrained paths to path_group

param PathGroup path_group: PathGroup to used to stash param Path path: current path to step on from returns [Path]: List of sucession paths

is_path_overbound(path)

Filter out all paths that run out of boundaries or loop too many times.

param Path path: Path instance to check returns bool: True if outside of mem/loop_ctr boundary

class angr.analyses.vfg.VFGJob(*args, **kwargs)

An EntryWrapper that contains vfg local variables

class angr.analyses.vfg.AnalysisTask

An analysis task describes a task that should be done before popping this task out of the task stack and discard it.

class angr.analyses.vfg.FunctionAnalysis(function_address, return_address)

Analyze a function, generate fix-point states from all endpoints of that function, and then merge them to one state.

class angr.analyses.vfg.CallAnalysis(address, return_address, function_analysis_tasks=None)

Analyze a call by analyze all functions this call might be calling, collect all final states generated by analyzing those functions, and merge them into one state.

class angr.analyses.vfg.VFGNode(addr, key, state=None)

A descriptor of nodes in a Value-Flow Graph

Constructor.

Parameters:
  • addr (int) –
  • key (BlockID) –
  • state (simuvex.SimState) –
append_state(s, is_widened_state=False)

Appended a new state to this VFGNode. :param s: The new state to append :param is_widened_state: Whether it is a widened state or not.

class angr.analyses.vfg.VFG(cfg=None, context_sensitivity_level=2, start=None, function_start=None, interfunction_level=0, initial_state=None, avoid_runs=None, remove_options=None, timeout=None, max_iterations_before_widening=8, max_iterations=40, widening_interval=3, final_state_callback=None, status_callback=None, record_function_final_states=False)

This class represents a control-flow graph with static analysis result.

Perform abstract interpretation analysis starting from the given function address. The output is an invariant at the beginning (or the end) of each basic block.

Steps:

  • Generate a CFG first if CFG is not provided.
  • Identify all merge points (denote the set of merge points as Pw) in the CFG.
  • Cut those loop back edges (can be derived from Pw) so that we gain an acyclic CFG.
  • Identify all variables that are 1) from memory loading 2) from initial values, or 3) phi functions. Denote
    the set of those variables as S_{var}.
  • Start real AI analysis and try to compute a fix point of each merge point. Perform widening/narrowing only on
    variables in S_{var}.
Parameters:
  • cfg – The control-flow graph to base this analysis on. If none is provided, we will construct a CFGAccurate.
  • context_sensitivity_level – The level of context-sensitivity of this VFG. It ranges from 0 to infinity. Default 2.
  • function_start – The address of the function to analyze.
  • interfunction_level – The level of interfunction-ness to be
  • initial_state – A state to use as the initial one
  • avoid_runs – A list of runs to avoid
  • remove_options – State options to remove from the initial state. It only works when initial_state is None
  • timeout (int) –
get_any_node(addr)

Get any VFG node corresponding to the basic block at @addr. Note that depending on the context sensitivity level, there might be multiple nodes corresponding to different contexts. This function will return the first one it encounters, which might not be what you want.

get_paths(begin, end)

Get all the simple paths between @begin and @end. Returns: a list of angr.Path instances.

class angr.analyses.vsa_ddg.DefUseChain(def_loc, use_loc, variable)

Stand for a def-use chain. it is generated by the DDG itself.

Constructor.

Parameters:
  • def_loc
  • use_loc
  • variable
Returns:

class angr.analyses.vsa_ddg.VSA_DDG(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)

A Data dependency graph based on VSA states. That means we don’t (and shouldn’t) expect any symbolic expressions.

Constructor.

Parameters:
  • vfg – An already constructed VFG. If not specified, a new VFG will be created with other specified parameters. vfg and start_addr cannot both be unspecified.
  • start_addr – The address where to start the analysis (typically, a function’s entry point).
  • interfunction_level – See VFG analysis.
  • context_sensitivity_level – See VFG analysis.
  • keep_data – Whether we keep set of addresses as edges in the graph, or just the cardinality of the sets, which can be used as a “weight”.
get_predecessors(code_location)

Returns all predecessors of code_location.

Parameters:code_location – A CodeLocation instance.
Returns:A list of all predecessors.
get_all_nodes(simrun_addr, stmt_idx)

Get all DDG nodes matching the given basic block address and statement index.

SimOS

Manage OS-level configuration.

class angr.simos.SyscallEntry(name, pseudo_addr, simproc, supported=True)

Describes a syscall.

Variables:
  • name (str) – Name of the syscall.
  • pseudo_addr (int) – The pseudo address assigned to this syscall.
  • simproc – The SimProcedure class for handling this syscall.
  • supported (bool) – True if this syscall is defined and has a SimProcedure implemented, False otherwise.

Constructor.

Parameters:
  • name (str) – Syscall name.
  • pseudo_addr (int) – The pseudo address assigned to this syscall.
  • simproc – The SimProcedure for handling this syscall.
  • supported (bool) – True if this syscall is defined and there is a SimProcedure implemented for it.
class angr.simos.SyscallTable(max_syscall_number=None, unknown_syscall_number=None)

Represents a syscall table.

Variables:
  • max_syscall_number (int) – The maximum syscall number of all supported syscalls in the platform.
  • unknown_syscall_number (int) – The syscall number of the “unknown” syscall used for unsupported syscalls.

Constructor.

Parameters:
  • or None max_syscall_number (int) – The maximum syscall number of all supported syscalls in the platform.
  • unknown_syscall_number (int) – The syscall number to use for unknown/undefined syscalls.
max_syscall

Get the maximum syscall number, or None if the syscall table is empty and max_syscall_number is not set..

Returns:The syscall number.
Return type:int or None
unknown_syscall

Get the “unknown” syscall entry.

Returns:The syscall entry for unknown syscalls.
Return type:SyscallEntry
clear()

Clear all defined syscalls.

Returns:None
supports(syscall_number)

Check if the syscall number is defined and supported.

Parameters:syscall_number (int) – The number of syscall to check.
Returns:True if the syscall number is defined and supported by angr, False otherwise
Return type:bool
get_by_addr(addr)

Get a syscall by the pseudo address.

Parameters:addr (int) – The pseudo address assigned to the syscall.
Returns:The syscall instance if the pseudo address is assigned to a syscall, or None otherwise.
Return type:SyscallEntry or None
class angr.simos.SimOS(project, name=None)

A class describing OS/arch-level configuration.

syscall_info(state)

Get information about the syscall that is about to be called. Note that symbolic syscalls are not supported - the syscall number must have only one solution.

Parameters:state (simuvex.s_state.SimState) – the program state.
Returns:A tuple of (cc, syscall_addr, syscall_name, syscall_class)
Return type:tuple
handle_syscall(state)

Handle a state whose immediate preceding jumpkind is syscall by creating a new SimRun. Note that symbolic syscalls are not supported - the syscall number must have only one solution.

Parameters:state (simuvex.s_state.SimState) – the program state.
Returns:an instanciated, but not executed SimProcedure for this syscall
Return type:simuvex.s_procedure.SimProcedure
configure_project()

Configure the project to set up global settings (like SimProcedures).

state_blank(addr=None, initial_prefix=None, stack_size=8388608, **kwargs)

Initialize a blank state.

All parameters are optional.

Parameters:
  • addr – The execution start address.
  • initial_prefix
Returns:

The initialized SimState.

Return type:

simuvex.SimState

prepare_call_state(calling_state, initial_state=None, preserve_registers=(), preserve_memory=())

This function prepares a state that is executing a call instruction. If given an initial_state, it copies over all of the critical registers to it from the calling_state. Otherwise, it prepares the calling_state for action.

This is mostly used to create minimalistic for CFG generation. Some ABIs, such as MIPS PIE and x86 PIE, require certain information to be maintained in certain registers. For example, for PIE MIPS, this function transfer t9, gp, and ra to the new state.

prepare_function_symbol(symbol_name)

Prepare the address space with the data necessary to perform relocations pointing to the given symbol

class angr.simos.SimLinux(*args, **kwargs)

OS-specific configuration for *nix-y OSes.

prepare_function_symbol(symbol_name)

Prepare the address space with the data necessary to perform relocations pointing to the given symbol.

Surveyors

Do not use surveyors. They are a legacy interface.

class angr.surveyor.Surveyor(project, start=None, max_active=None, max_concurrency=None, pickle_paths=None, save_deadends=None, enable_veritesting=False, veritesting_options=None, keep_pruned=None)

The surveyor class eases the implementation of symbolic analyses. This provides a base upon which analyses can be implemented.

Surveyors provide at least the following members:

Variables:
  • active – The paths that are still active in the analysis.
  • deadended – The paths that are still active in the analysis.
  • spilled – The paths that are still active in the analysis.
  • errored – The paths that have at least one error-state exit.
  • pruned – The paths that were pruned because their ancestors were unsat.
  • unconstrained – The paths that have a successor with an unconstrained instruction pointer.

A Surveryor has the following overloadable properties:

Variables:
  • done – returns True if the analysis is done (by default, this is when self.active is empty).
  • run – runs a loop of tick()ing and spill()ing until self.done is True.
  • tick – ticks all paths forward. The default implementation calls tick_path() on every path.

A Surveyor has the following overloadable functions :

tick_path() moves a provided path forward, returning a set of new paths.

spill() spills all paths, in-place. The default implementation first calls spill_path() on every path, then spill_paths() on the resulting sequence, then keeps the rest.

spill_path() returns a spilled sequence of paths from a provided sequence of paths.

An analysis can overload either the specific sub-portions of surveyor (i.e, the tick_path and spill_path functions) or bigger and bigger pieces to implement more and more customizeable analyses.

Creates the Surveyor.

Parameters:
  • project – the angr.Project to analyze.
  • start – a path (or set of paths) to start the analysis from
  • max_active – the maximum number of paths to explore at a time
  • max_concurrency – the maximum number of worker threads
  • pickle_paths – pickle spilled paths to save memory
  • save_deadends – save deadended paths
  • enable_veritesting – use static symbolic execution to speed up exploration
  • veritesting_options – special options to be passed to Veritesting
  • keep_pruned – keep pruned unsat states
pre_tick()

Provided for analyses to use for pre-tick actions.

post_tick()

Provided for analyses to use for pre-tick actions.

step()

Takes one step in the analysis (called by run()).

run(n=None)

Runs the analysis through completion (until done() returns True) or, if n is provided, n times.

Parameters:n – the maximum number of ticks
Returns:itself for chaining
done

True if the analysis is done.

tick()

Takes one step in the analysis. Typically, this moves all active paths forward.

Returns:itself, for chaining
tick_path(p)

Ticks a single path forward. Returns a sequence of successor paths.

prune()

Prune unsat paths.

filter_path(p)

Returns True if the given path should be kept in the analysis, False otherwise.

filter_paths(paths)

Given a list of paths, returns filters them and returns the rest.

path_comparator(a, b)

This function should compare paths a and b, to determine which should have a higher priority in the analysis. It’s used as the cmp argument to sort.

prioritize_paths(paths)

This function is called to sort a list of paths, to prioritize the analysis of paths. Should return a list of paths, with higher- priority paths first.

spill_paths(active, spilled)

Called with the currently active and spilled paths to spill some paths. Should return the new active and spilled paths.

spill()

Spills/unspills paths, in-place.

suspend_path(p)

Suspends and returns a state.

Parameters:p – the path
Returns:the path
class angr.surveyors.caller.Callable(project, addr, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None)

Callable is a representation of a function in the binary that can be interacted with like a native python function.

If you set perform_merge=True (the default), the result will be returned to you, and you can get the result state with callable.result_state.

Otherwise, you can get the resulting path group (immutable) at callable.result_path_group.

Parameters:
  • project – The project to operate on
  • addr – The address of the function to use

The following parameters are optional:

Parameters:
  • concrete_only – Throw an exception if the execution splits into multiple paths
  • perform_merge – Merge all result states into one at the end (only relevant if concrete_only=False)
  • base_state – The state from which to do these runs
  • toc – The address of the table of contents for ppc64
  • cc – The SimCC to use for a calling convention
set_base_state(state)

Swap out the state you’d like to use to perform the call :param state: The state to use to perform the call

class angr.surveyors.caller.Caller(project, addr, args=(), start=None, num_find=None, concrete_only=False, **kwargs)

Caller is a surveyor that executes functions to see what they do.

Parameters:
  • project – the project
  • addr – the address to start calling at
  • args – a tuple of arguments. Any members that are None will be replaced with symbolic expressions with a length of the architecture’s bitwidth.
  • start – a path (or set of paths) to start from
  • num_find – find at least this many returns from the function
  • concrete_only – Throw an exception if the execution splits into multiple paths
map_se(func, *args, **kwargs)

Maps the state.se.”func” function for all the return address states. This is a generator.

Parameters:
  • func – the function name, used as getattr(p.state.se, func). Normally any_n_int or any_n_str
  • runs – the maximum number of runs to execute
  • solutions – check only returns with this value as a possible solution
  • sort – sort the result before yielding it

Other args and **kwargs are passed to the called state.se. function.

yields (r, func_return) for each state.

map_func(func, runs=None, solution=None)

Calls func(return_value, args_tuple, path) for each function return. This is a generator.

Parameters:
  • func – the function to call
  • runs – the maximum number of runs to execute
  • solutions – check only returns with this value as a possible solution

yields the return values of func

iter_returns(runs=None, solution=None)

Yields (return_value, path) for every return. This is a generator.

Parameters:
  • runs – the maximum number of runs to execute
  • solutions – check only returns with this value as a possible solution
class angr.surveyors.escaper.Escaper(project, loop_addresses, start=None, max_concurrency=None, max_active=None, pickle_paths=None, loop_iterations=0, iteration_depth=100, unconstrain_memory=True, unconstrain_registers=True)

Escaper implements loop escaping!

normal - any found normal paths from the loop forced - forced paths from the loop, if a normal wasn’t found

Creates an Escaper. Most options are for Surveyor (separate docs).

Parameters:
  • loop_addresses – the addresses of all the basic blocks in the loop, to know the instructions to which the analysis should be restricted
  • loop_iterations – the number of times to run the loop before escaping
  • iteration_depth – the maximum depth (in SimRuns) of a path through the loop
unconstrain_loop(constrained_entry)

Unconstrains an exit to the loop header by looping one more time and replacing all modified variables with unconstrained versions.

tick()

Makes one run through the loop.

class angr.surveyors.executor.Executor(project, start, final_addr=None, pickle_paths=None, max_run=50000)

This class handles pure concrete execution related issues. No state splitting is ever allowed.

class angr.surveyors.explorer.Explorer(project, start=None, max_concurrency=None, max_active=None, pickle_paths=None, find=None, avoid=None, restrict=None, min_depth=0, max_depth=None, max_repeats=10000000, num_find=1, num_avoid=None, num_deviate=1, num_loop=None, cfg=None, enable_veritesting=None, veritesting_options=None, keep_pruned=None)

Explorer implements a symbolic exploration engine!

WARNING: Explorers are not really maintained - Use path_group instead when possible

found - paths where the target addresses have been found. avoided - paths where the to-avoid addresses have been found. deviating - paths that deviate from the restricted-to addresses. looping - paths that were detected as looping.

Explores the path space until a block containing a specified address is found.

Parameters:project

The following parameters are optional :

Parameters:
  • start
  • max_concurrency
  • max_active
  • pickle_paths
  • find – A tuple containing the addresses to search for.
  • avoid – A tuple containing the addresses to avoid.
  • restrict – A tuple containing the addresses to restrict the analysis to (avoid all others).
  • min_depth – The minimum number of SimRuns in the resulting path.
  • max_depth – The maximum number of SimRuns in the resulting path.
  • num_find – The minimum number of paths to find. (default: 1)
  • num_avoid – The minimum number of paths to avoid. (default: infinite)
  • num_deviate – The minimum number of paths to deviate. (default: infinite)
  • num_loop – The minimum number of paths to loop (default: infinite)
  • cfg – A CFG to use to cut any paths that have no chance of going to the target.
  • enable_veritesting – Whether Veritesting should be enabled or not.
  • veritesting_options – Options that should be passed to Veritesting.
class angr.surveyors.slicecutor.Slicecutor(project, annotated_cfg, start=None, targets=None, max_concurrency=None, max_active=None, max_loop_iterations=None, pickle_paths=None, merge_countdown=10)

The Slicecutor is a surveyor that executes provided code slices.