API Reference

class angr.SimProcedure(project=None, cc=None, prototype=None, symbolic_return=None, returns=None, is_syscall=False, is_stub=False, num_args=None, display_name=None, library_name=None, is_function=None, **kwargs)[source]

Bases: object

A SimProcedure is a wonderful object which describes a procedure to run on a state.

You may subclass SimProcedure and override run(), replacing it with mutating self.state however you like, and then either returning a value or jumping away somehow.

A detailed discussion of programming SimProcedures may be found at https://docs.angr.io/extending-angr/simprocedures

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

  • library_name – The name of the library from which the function we’re emulating comes

  • cc – 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

The following class variables should be set if necessary when implementing a new SimProcedure:

Variables:
  • NO_RET – Set this to true if control flow will never return from this function

  • DYNAMIC_RET – Set this to true if whether the control flow returns from this function or not depends on the context (e.g., libc’s error() call). Must implement dynamic_returns() method.

  • ADDS_EXITS – Set this to true if you do any control flow other than returning

  • IS_FUNCTION – Does this procedure simulate a function? True by default

  • ARGS_MISMATCH – Does this procedure have a different list of arguments than what is provided in the function specification? This may happen when we manually extract arguments in the run() method of a SimProcedure. False by default.

  • local_vars – If you use self.call(), set this to a list of all the local variable names in your class. They will be restored on return.

The following instance variables are available when working with simprocedures from the inside or the outside:

Variables:
  • project – The associated angr project

  • arch – The associated architecture

  • addr – The linear address at which the procedure is executing

  • cc – The calling convention in use for engaging with the ABI

  • canonical – The canonical version of this SimProcedure. Procedures are deepcopied for many reasons, including to be able to store state related to a specific run and to be able to hook continuations.

  • kwargs – Any extra keyword arguments used to construct the procedure; will be passed to run

  • display_name – See the eponymous parameter

  • library_name – See the eponymous parameter

  • abi – If this is a syscall simprocedure, which ABI are we using to map the syscall numbers?

  • symbolic_return – See the eponymous parameter

  • syscall_number – If this procedure is a syscall, the number will be populated here.

  • returns – See eponymous parameter and NO_RET cvar

  • is_syscall – See eponymous parameter

  • is_function – See eponymous parameter and cvar

  • is_stub – See eponymous parameter

  • is_continuation – Whether this procedure is the original or a continuation resulting from self.call()

  • continuations – A mapping from name to each known continuation

  • run_func – The name of the function implementing the procedure. “run” by default, but different in continuations.

  • num_args – The number of arguments to the procedure. If not provided in the parameter, extracted from the definition of self.run

The following instance variables are only used in a copy of the procedure that is actually executing on a state:

Variables:
  • state – The SimState we should be mutating to perform the procedure

  • successors – The SimSuccessors associated with the current step

  • arguments – The function arguments, deserialized from the state

  • arg_session – The ArgSession that was used to parse arguments out of the state, in case you need it for varargs

  • use_state_arguments – Whether we’re using arguments extracted from the state or manually provided

  • ret_to – The current return address

  • ret_expr – The computed return value

  • call_ret_expr – The return value from having used self.call()

  • inhibit_autoret – Whether we should avoid automatically adding an exit for returning once the run function ends

  • arg_session – The ArgSession object that was used to extract the runtime argument values. Useful for if you want to extract variadic args.

__init__(project=None, cc=None, prototype=None, symbolic_return=None, returns=None, is_syscall=False, is_stub=False, num_args=None, display_name=None, library_name=None, is_function=None, **kwargs)[source]
state: SimState
execute(state, successors=None, arguments=None, ret_to=None)[source]

Call this method with a SimState and a SimSuccessors to execute the procedure.

Alternately, successors may be none if this is an inline call. In that case, you should provide arguments to the function.

make_continuation(name)[source]
NO_RET = False
DYNAMIC_RET = False
ADDS_EXITS = False
IS_FUNCTION = True
ARGS_MISMATCH = False
ALT_NAMES = None
local_vars: tuple[str, ...] = ()
run(*args, **kwargs)[source]

Implement the actual procedure here!

static_exits(blocks, **kwargs)[source]

Get new exits by performing static analysis and heuristics. This is a fast and best-effort approach to get new exits for scenarios where states are not available (e.g. when building a fast CFG).

Parameters:

blocks (list) – Blocks that are executed before reaching this SimProcedure.

Returns:

A list of dicts. Each dict should contain the following entries: ‘address’, ‘jumpkind’, and ‘namehint’.

Return type:

list

dynamic_returns(blocks, **kwargs)[source]

Determines if a call to this function returns or not by performing static analysis and heuristics.

Parameters:

blocks – Blocks that are executed before reaching this SimProcedure.

Return type:

bool

Returns:

True if the call returns, False otherwise.

property should_add_successors
set_args(args)[source]
va_arg(ty, index=None)[source]
inline_call(procedure, *arguments, **kwargs)[source]

Call another SimProcedure in-line to retrieve its return value. Returns an instance of the procedure with the ret_expr property set.

Parameters:
  • procedure – The class of the procedure to execute

  • arguments – Any additional positional args will be used as arguments to the procedure call

  • sim_kwargs – Any additional keyword args will be passed as sim_kwargs to the procedure constructor

fix_prototype_returnty(ret_size)[source]
ret(expr=None)[source]

Add an exit representing a return from this function. If this is not an inline call, grab a return address from the state and jump to it. If this is not an inline call, set a return expression with the calling convention.

call(addr, args, continue_at, cc=None, prototype=None, jumpkind='Ijk_Call')[source]

Add an exit representing calling another function via pointer.

Parameters:
  • addr – The address of the function to call

  • args – The list of arguments to call the function with

  • continue_at – Later, when the called function returns, execution of the current procedure will continue in the named method.

  • cc – Optional: use this calling convention for calling the new function. Default is to use the current convention.

  • prototype – Optional: The prototype to use for the call. Will default to all-ints.

jump(addr, jumpkind='Ijk_Boring')[source]

Add an exit representing jumping to an address.

exit(exit_code)[source]

Add an exit representing terminating the program.

ty_ptr(ty)[source]
property is_java
property argument_types
property return_type
class angr.BP(when='before', enabled=None, condition=None, action=None, **kwargs)[source]

Bases: object

A breakpoint.

__init__(when='before', enabled=None, condition=None, action=None, **kwargs)[source]
check(state, when)[source]

Checks state state to see if the breakpoint should fire.

Parameters:
  • state – The state.

  • when – Whether the check is happening before or after the event.

Returns:

A boolean representing whether the checkpoint should fire.

fire(state)[source]

Trigger the breakpoint.

Parameters:

state – The state.

class angr.SimStatePlugin[source]

Bases: object

This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They are intended to be used for things such as tracking open files, tracking heap details, and providing storage and persistence for SimProcedures.

STRONGREF_STATE = False
__init__()[source]
set_state(state)[source]

Sets a new state (for example, if the state has been branched)

set_strongref_state(state)[source]
copy(_memo)[source]

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

static memo(f)[source]

A decorator function you should apply to copy

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

classmethod register_default(name, xtr=None)[source]
init_state()[source]

Use this function to perform any initialization on the state at plugin-add time

class angr.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, engine=None, load_options=None, translation_cache=True, selfmodifying_code=False, support_selfmodifying_code=None, store_function=None, load_function=None, analyses_preset=None, concrete_target=None, eager_ifunc_resolution=None, **kwargs)[source]

Bases: object

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.

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

  • arch (Arch)

  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

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_procedures – 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.

  • engine – The SimEngine class to use for this project.

  • translation_cache (bool) – If True, cache translated basic blocks rather than re-translating them.

  • selfmodifying_code (bool) – Whether we aggressively support self-modifying code. When enabled, emulation will try to read code from the current state instead of the original memory, regardless of the current memory protections.

  • store_function – A function that defines how the Project should be stored. Default to pickling.

  • load_function – A function that defines how the Project should be loaded. Default to unpickling.

  • analyses_preset (angr.misc.PluginPreset) – The plugin preset for the analyses provider (i.e. Analyses instance).

  • load_options (dict[str, Any] | None)

  • support_selfmodifying_code (bool | None)

Any additional keyword arguments passed will be passed onto cle.Loader.

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.

  • storage – Dictionary of things that should be loaded/stored with the Project.

Parameters:
  • arch (Arch)

  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

__init__(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, engine=None, load_options=None, translation_cache=True, selfmodifying_code=False, support_selfmodifying_code=None, store_function=None, load_function=None, analyses_preset=None, concrete_target=None, eager_ifunc_resolution=None, **kwargs)[source]
Parameters:
  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

arch: Arch
property analyses: AnalysesHubWithDefault
hook(addr, hook=None, length=0, kwargs=None, replace=False)[source]

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.

When hook is not specified, it returns a function decorator that allows easy hooking. Usage:

# Assuming proj is an instance of angr.Project, we will add a custom hook at the entry
# point of the project.
@proj.hook(proj.entry)
def my_hook(state):
    print("Welcome to execution!")
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.

  • replace (bool | None) – Control the behavior on finding that the address is already hooked. If true, silently replace the hook. If false (default), warn and do not replace the hook. If none, warn and replace the hook.

is_hooked(addr)[source]

Returns True if addr is hooked.

Parameters:

addr – An address.

Return type:

bool

Returns:

True if addr is hooked, False otherwise.

hooked_by(addr)[source]

Returns the current hook for addr.

Parameters:

addr – An address.

Return type:

SimProcedure | None

Returns:

None if the address is not hooked.

unhook(addr)[source]

Remove a hook.

Parameters:

addr – The address of the hook.

hook_symbol(symbol_name, simproc, kwargs=None, replace=None)[source]

Resolve a dependency in a binary. Looks up the address of the given symbol, and then hooks that address. If the symbol was not available in the loaded libraries, this address may be provided by the CLE externs object.

Additionally, if instead of a symbol name you provide an address, some secret functionality will kick in and you will probably just hook that address, UNLESS you’re on powerpc64 ABIv1 or some yet-unknown scary ABI that has its function pointers point to something other than the actual functions, in which case it’ll do the right thing.

Parameters:
  • symbol_name – The name of the dependency to resolve.

  • simproc – The SimProcedure instance (or function) with which to hook the symbol

  • 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.

  • replace (Optional[bool]) – Control the behavior on finding that the address is already hooked. If true, silently replace the hook. If false, warn and do not replace the hook. If none (default), warn and replace the hook.

Returns:

The address of the new symbol.

Return type:

int

symbol_hooked_by(symbol_name)[source]

Return the SimProcedure, if it exists, for the given symbol name.

Parameters:

symbol_name (str) – Name of the symbol.

Return type:

SimProcedure | None

Returns:

None if the address is not hooked.

is_symbol_hooked(symbol_name)[source]

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

unhook_symbol(symbol_name)[source]

Remove the hook on a symbol. This function will fail if the symbol is provided by the extern object, as that would result in a state where analysis would be unable to cope with a call to this symbol.

rehook_symbol(new_address, symbol_name, stubs_on_sync)[source]

Move the hook for a symbol to a specific address :type new_address: :param new_address: the new address that will trigger the SimProc execution :type symbol_name: :param symbol_name: the name of the symbol (f.i. strcmp ) :return: None

execute(*args, **kwargs)[source]

This function is a symbolic execution helper in the simple style supported by triton and manticore. It designed to be run after setting up hooks (see Project.hook), in which the symbolic state can be checked.

This function can be run in three different ways:

  • When run with no parameters, this function begins symbolic execution from the entrypoint.

  • It can also be run with a “state” parameter specifying a SimState to begin symbolic execution from.

  • Finally, it can accept any arbitrary keyword arguments, which are all passed to project.factory.full_init_state.

If symbolic execution finishes, this function returns the resulting simulation manager.

terminate_execution()[source]

Terminates a symbolic execution that was started with Project.execute().

angr.load_shellcode(shellcode, arch, start_offset=0, load_address=0, thumb=False, **kwargs)[source]

Load a new project based on a snippet of assembly or bytecode.

Parameters:
  • shellcode (bytes | str) – The data to load, as either a bytestring of instructions or a string of assembly text

  • arch – The name of the arch to use, or an archinfo class

  • start_offset – The offset into the data to start analysis (default 0)

  • load_address – The address to place the data in memory (default 0)

  • thumb – Whether this is ARM Thumb shellcode

exception angr.AngrError[source]

Bases: Exception

exception angr.AngrRuntimeError[source]

Bases: RuntimeError

exception angr.AngrValueError[source]

Bases: AngrError, ValueError

exception angr.AngrLifterError[source]

Bases: AngrError

exception angr.AngrExitError[source]

Bases: AngrError

exception angr.AngrPathError[source]

Bases: AngrError

exception angr.AngrVaultError[source]

Bases: AngrError

exception angr.PathUnreachableError[source]

Bases: AngrPathError

exception angr.SimulationManagerError[source]

Bases: AngrError

exception angr.AngrInvalidArgumentError[source]

Bases: AngrError

exception angr.AngrSurveyorError[source]

Bases: AngrError

exception angr.AngrAnalysisError[source]

Bases: AngrError

exception angr.AngrBladeError[source]

Bases: AngrError

exception angr.AngrBladeSimProcError[source]

Bases: AngrBladeError

exception angr.AngrAnnotatedCFGError[source]

Bases: AngrError

exception angr.AngrBackwardSlicingError[source]

Bases: AngrError

exception angr.AngrCallableError[source]

Bases: AngrSurveyorError

exception angr.AngrCallableMultistateError[source]

Bases: AngrCallableError

exception angr.AngrSyscallError[source]

Bases: AngrError

exception angr.AngrSimOSError[source]

Bases: AngrError

exception angr.AngrAssemblyError[source]

Bases: AngrError

exception angr.AngrTypeError[source]

Bases: AngrError, TypeError

exception angr.AngrMissingTypeError[source]

Bases: AngrTypeError

exception angr.AngrIncongruencyError[source]

Bases: AngrAnalysisError

exception angr.AngrForwardAnalysisError[source]

Bases: AngrError

exception angr.AngrSkipJobNotice[source]

Bases: AngrForwardAnalysisError

exception angr.AngrDelayJobNotice[source]

Bases: AngrForwardAnalysisError

exception angr.AngrJobMergingFailureNotice[source]

Bases: AngrForwardAnalysisError

exception angr.AngrJobWideningFailureNotice[source]

Bases: AngrForwardAnalysisError

exception angr.AngrCFGError[source]

Bases: AngrError

exception angr.AngrVFGError[source]

Bases: AngrError

exception angr.AngrVFGRestartAnalysisNotice[source]

Bases: AngrVFGError

exception angr.AngrDataGraphError[source]

Bases: AngrAnalysisError

exception angr.AngrDDGError[source]

Bases: AngrAnalysisError

exception angr.AngrLoopAnalysisError[source]

Bases: AngrAnalysisError

exception angr.AngrExplorationTechniqueError[source]

Bases: AngrError

exception angr.AngrExplorerError[source]

Bases: AngrExplorationTechniqueError

exception angr.AngrDirectorError[source]

Bases: AngrExplorationTechniqueError

exception angr.AngrTracerError[source]

Bases: AngrExplorationTechniqueError

exception angr.AngrDBError[source]

Bases: AngrError

exception angr.AngrCorruptDBError[source]

Bases: AngrDBError

exception angr.AngrIncompatibleDBError[source]

Bases: AngrDBError

exception angr.TracerEnvironmentError[source]

Bases: AngrError

exception angr.SimError[source]

Bases: Exception

bbl_addr = None
stmt_idx = None
ins_addr = None
executed_instruction_count = None
guard = None
record_state(state)[source]
exception angr.SimStateError[source]

Bases: SimError

exception angr.SimMergeError[source]

Bases: SimStateError

exception angr.SimMemoryError[source]

Bases: SimStateError

exception angr.SimMemoryMissingError(missing_addr, missing_size, *args)[source]

Bases: SimMemoryError

__init__(missing_addr, missing_size, *args)[source]
exception angr.SimAbstractMemoryError[source]

Bases: SimMemoryError

exception angr.SimRegionMapError[source]

Bases: SimMemoryError

exception angr.SimMemoryLimitError[source]

Bases: SimMemoryError

exception angr.SimMemoryAddressError[source]

Bases: SimMemoryError

exception angr.SimFastMemoryError[source]

Bases: SimMemoryError

exception angr.SimEventError[source]

Bases: SimStateError

exception angr.SimPosixError[source]

Bases: SimStateError

exception angr.SimFilesystemError[source]

Bases: SimError

exception angr.SimSymbolicFilesystemError[source]

Bases: SimFilesystemError

exception angr.SimFileError[source]

Bases: SimMemoryError, SimFilesystemError

exception angr.SimHeapError[source]

Bases: SimStateError

exception angr.SimUnsupportedError[source]

Bases: SimError

exception angr.SimSolverError[source]

Bases: SimError

exception angr.SimSolverModeError[source]

Bases: SimSolverError

exception angr.SimSolverOptionError[source]

Bases: SimSolverError

exception angr.SimValueError[source]

Bases: SimSolverError

exception angr.SimUnsatError[source]

Bases: SimValueError

exception angr.SimOperationError[source]

Bases: SimError

exception angr.UnsupportedIROpError[source]

Bases: SimOperationError, SimUnsupportedError

exception angr.SimExpressionError[source]

Bases: SimError

exception angr.UnsupportedIRExprError[source]

Bases: SimExpressionError, SimUnsupportedError

exception angr.SimCCallError[source]

Bases: SimExpressionError

exception angr.UnsupportedCCallError[source]

Bases: SimCCallError, SimUnsupportedError

exception angr.SimUninitializedAccessError(expr_type, expr)[source]

Bases: SimExpressionError

__init__(expr_type, expr)[source]
exception angr.SimStatementError[source]

Bases: SimError

exception angr.UnsupportedIRStmtError[source]

Bases: SimStatementError, SimUnsupportedError

exception angr.UnsupportedDirtyError[source]

Bases: UnsupportedIRStmtError, SimUnsupportedError

exception angr.SimMissingTempError[source]

Bases: SimValueError, IndexError

exception angr.SimEngineError[source]

Bases: SimError

exception angr.SimIRSBError[source]

Bases: SimEngineError

exception angr.SimTranslationError[source]

Bases: SimEngineError

exception angr.SimProcedureError[source]

Bases: SimEngineError

exception angr.SimProcedureArgumentError[source]

Bases: SimProcedureError

exception angr.SimShadowStackError[source]

Bases: SimProcedureError

exception angr.SimFastPathError[source]

Bases: SimEngineError

exception angr.SimIRSBNoDecodeError[source]

Bases: SimIRSBError

exception angr.AngrUnsupportedSyscallError[source]

Bases: AngrSyscallError, SimProcedureError, SimUnsupportedError

angr.UnsupportedSyscallError

alias of AngrUnsupportedSyscallError

exception angr.SimReliftException(state)[source]

Bases: SimEngineError

__init__(state)[source]
exception angr.SimSlicerError[source]

Bases: SimError

exception angr.SimActionError[source]

Bases: SimError

exception angr.SimCCError[source]

Bases: SimError

exception angr.SimUCManagerError[source]

Bases: SimError

exception angr.SimUCManagerAllocationError[source]

Bases: SimUCManagerError

exception angr.SimUnicornUnsupport[source]

Bases: SimError

exception angr.SimUnicornError[source]

Bases: SimError

exception angr.SimUnicornSymbolic[source]

Bases: SimError

exception angr.SimEmptyCallStackError[source]

Bases: SimError

exception angr.SimStateOptionsError[source]

Bases: SimError

exception angr.SimException[source]

Bases: SimError

exception angr.SimSegfaultException(addr, reason, original_addr=None)[source]

Bases: SimException, SimMemoryError

__init__(addr, reason, original_addr=None)[source]
angr.SimSegfaultError

alias of SimSegfaultException

exception angr.SimZeroDivisionException[source]

Bases: SimException, SimOperationError

exception angr.AngrNoPluginError[source]

Bases: AngrError

exception angr.SimConcreteMemoryError[source]

Bases: AngrError

exception angr.SimConcreteRegisterError[source]

Bases: AngrError

exception angr.SimConcreteBreakpointError[source]

Bases: AngrError

exception angr.AngrDecompilationError[source]

Bases: AngrError

exception angr.UnsupportedNodeTypeError[source]

Bases: AngrError, NotImplementedError

class angr.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, base_state=None, stop_at_calls=False, cross_insn_opt=False, max_predecessors=10, include_imarks=True)[source]

Bases: object

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)

  • dst_run (int)

  • dst_stmt_idx (int)

  • direction (str)

  • ignore_sp (bool)

  • ignore_bp (bool)

  • max_level (int)

  • stop_at_calls (bool)

  • max_predecessors (int)

  • include_imarks (bool)

__init__(graph, dst_run, dst_stmt_idx, direction='backward', project=None, cfg=None, ignore_sp=False, ignore_bp=False, ignored_regs=None, max_level=3, base_state=None, stop_at_calls=False, cross_insn_opt=False, max_predecessors=10, include_imarks=True)[source]
Parameters:
  • graph (DiGraph) – A graph representing the control flow graph. Note that it does not take angr.analyses.CFGEmulated 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.

  • stop_at_calls (bool) – Limit slicing within a single function. Do not proceed when encounters a call edge.

  • include_imarks (bool) – Should IMarks (instruction boundaries) be included in the slice.

  • max_predecessors (int)

Returns:

None

property slice
dbg_repr(arch=None)[source]
class angr.SimOS(project, name=None)[source]

Bases: object

A class describing OS/arch-level configuration.

Parameters:

project (angr.Project)

__init__(project, name=None)[source]
Parameters:

project (Project)

configure_project()[source]

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

state_blank(addr=None, initial_prefix=None, brk=None, stack_end=None, stack_size=8388608, stdin=None, thread_idx=None, permissions_backer=None, **kwargs)[source]

Initialize a blank state.

All parameters are optional.

Parameters:
  • addr – The execution start address.

  • initial_prefix

  • stack_end – The end of the stack (i.e., the byte after the last valid stack address).

  • stack_size – The number of bytes to allocate for stack space

  • brk – The address of the process’ break.

Returns:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

state_entry(**kwargs)[source]
state_full_init(**kwargs)[source]
state_call(addr, *args, **kwargs)[source]
prepare_call_state(calling_state, initial_state=None, preserve_registers=(), preserve_memory=())[source]

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, basic_addr=None)[source]

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

Returns a 2-tuple. The first item is the address of the function code, the second is the address of the relocation target.

handle_exception(successors, engine, exception)[source]

Perform exception handling. This method will be called when, during execution, a SimException is thrown. Currently, this can only indicate a segfault, but in the future it could indicate any unexpected exceptional behavior that can’t be handled by ordinary control flow.

The method may mutate the provided SimSuccessors object in any way it likes, or re-raise the exception.

Parameters:
  • successors – The SimSuccessors object currently being executed on

  • engine – The engine that was processing this step

  • exception – The actual exception object

syscall(state, allow_unsupported=True)[source]
syscall_abi(state)[source]
Return type:

str

syscall_cc(state)[source]
Return type:

SimCCSyscall | None

is_syscall_addr(addr)[source]
syscall_from_addr(addr, allow_unsupported=True)[source]
syscall_from_number(number, allow_unsupported=True, abi=None)[source]
setup_gdt(state, gdt)[source]

Write the GlobalDescriptorTable object in the current state memory

Parameters:
  • state – state in which to write the GDT

  • gdt – GlobalDescriptorTable object

Returns:

generate_gdt(fs, gs, fs_size=4294967295, gs_size=4294967295)[source]

Generate a GlobalDescriptorTable object and populate it using the value of the gs and fs register

Parameters:
  • fs – value of the fs segment register

  • gs – value of the gs segment register

  • fs_size – size of the fs segment register

  • gs_size – size of the gs segment register

Returns:

gdt a GlobalDescriptorTable object

class angr.Block(addr, project=None, arch=None, size=None, max_size=None, byte_string=None, vex=None, thumb=False, backup_state=None, extra_stop_points=None, opt_level=None, num_inst=None, traceflags=0, strict_block_end=None, collect_data_refs=False, cross_insn_opt=True, load_from_ro_regions=False, const_prop=False, initial_regs=None, skip_stmts=False)[source]

Bases: Serializable

Represents a basic block in a binary or a program.

BLOCK_MAX_SIZE = 4096
__init__(addr, project=None, arch=None, size=None, max_size=None, byte_string=None, vex=None, thumb=False, backup_state=None, extra_stop_points=None, opt_level=None, num_inst=None, traceflags=0, strict_block_end=None, collect_data_refs=False, cross_insn_opt=True, load_from_ro_regions=False, const_prop=False, initial_regs=None, skip_stmts=False)[source]
arch
thumb
addr
size
pp(**kwargs)[source]
set_initial_regs()[source]
static reset_initial_regs()[source]
property vex: IRSB
property vex_nostmt
property disassembly: DisassemblerBlock

Provide a disassembly object using whatever disassembler is available

property capstone
property codenode
property bytes: bytes
property instructions
property instruction_addrs
serialize_to_cmessage()[source]

Serialize the class object and returns a protobuf cmessage object.

Returns:

A protobuf cmessage object.

Return type:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg)[source]

Parse a protobuf cmessage and create a class object.

Parameters:

cmsg – The probobuf cmessage object.

Returns:

A unserialized class object.

Return type:

cls

class angr.SimulationManager(project, active_states=None, stashes=None, hierarchy=None, resilience=None, save_unsat=False, auto_drop=None, errored=None, completion_mode=<built-in function any>, techniques=None, suggestions=True, **kwargs)[source]

Bases: object

The Simulation Manager is the future future.

Simulation managers allow you to wrangle multiple states in a slick way. States 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 states at different rates, then merge them together.

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

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

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

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

  • stashes – A dictionary to use as the stash store.

  • active_states – Active states to seed the “active” stash with.

  • hierarchy – A StateHierarchy object to use to track the relationships between states.

  • resilience – A set of errors to catch during stepping to put a state in the errore list. You may also provide the values False, None (default), or True to catch, respectively, no errors, all angr-specific errors, and a set of many common errors.

  • save_unsat – Set to True in order to introduce unsatisfiable states into the unsat stash instead of discarding them immediately.

  • auto_drop – A set of stash names which should be treated as garbage chutes.

  • completion_mode – A function describing how multiple exploration techniques with the complete hook set will interact. By default, the builtin function any.

  • techniques – A list of techniques that should be pre-set to use with this manager.

  • suggestions – Whether to automatically install the Suggestions exploration technique. Default True.

Variables:
  • errored – Not a stash, but a list of ErrorRecords. Whenever a step raises an exception that we catch, the state and some information about the error are placed in this list. You can adjust the list of caught exceptions with the resilience parameter.

  • stashes – All the stashes on this instance, as a dictionary.

  • completion_mode – A function describing how multiple exploration techniques with the complete hook set will interact. By default, the builtin function any.

ALL = '_ALL'
DROP = '_DROP'
__init__(project, active_states=None, stashes=None, hierarchy=None, resilience=None, save_unsat=False, auto_drop=None, errored=None, completion_mode=<built-in function any>, techniques=None, suggestions=True, **kwargs)[source]
active: list[SimState]
stashed: list[SimState]
pruned: list[SimState]
unsat: list[SimState]
deadended: list[SimState]
unconstrained: list[SimState]
found: list[SimState]
one_active: SimState
one_stashed: SimState
one_pruned: SimState
one_unsat: SimState
one_deadended: SimState
one_unconstrained: SimState
one_found: SimState
property errored: list[ErrorRecord]
property stashes: defaultdict[str, list[SimState]]
mulpyplex(*stashes)[source]

Mulpyplex across several stashes.

Parameters:

stashes – the stashes to mulpyplex

Returns:

a mulpyplexed list of states from the stashes in question, in the specified order

copy(deep=False)[source]

Make a copy of this simulation manager. Pass deep=True to copy all the states in it as well.

If the current callstack includes hooked methods, the already-called methods will not be included in the copy.

use_technique(tech)[source]

Use an exploration technique with this SimulationManager.

Techniques can be found in angr.exploration_techniques.

Parameters:

tech (ExplorationTechnique) – An ExplorationTechnique object that contains code to modify this SimulationManager’s behavior.

Returns:

The technique that was added, for convenience

remove_technique(tech)[source]

Remove an exploration technique from a list of active techniques.

Parameters:

tech (ExplorationTechnique) – An ExplorationTechnique object.

explore(stash='active', n=None, find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False, **kwargs)[source]

Tick stash “stash” forward (up to “n” times or until “num_find” states are found), looking for condition “find”, avoiding condition “avoid”. Stores found states into “find_stash’ and avoided states 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 state 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 states which cannot possibly reach a success state without going through a failure state will be preemptively avoided.

run(stash='active', n=None, until=None, **kwargs)[source]

Run until the SimulationManager has reached a completed state, according to the current exploration techniques. If no exploration techniques that define a completion state are being used, run until there is nothing left to run.

Parameters:
  • stash – Operate on this stash

  • n – Step at most this many times

  • until – If provided, should be a function that takes a SimulationManager and returns True or False. Stepping will terminate when it is True.

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

complete()[source]

Returns whether or not this manager has reached a “completed” state.

step(stash='active', target_stash=None, n=None, selector_func=None, step_func=None, error_list=None, successor_func=None, until=None, filter_func=None, **run_args)[source]

Step a stash of states forward 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’)

  • target_stash – The name of the stash to put the results in (default: same as stash)

  • error_list – The list to put ErrorRecord objects in (default: self.errored)

  • selector_func – If provided, should be a function that takes a state and returns a boolean. If True, the state will be stepped. Otherwise, it will be kept as-is.

  • step_func – If provided, should be a function that takes a SimulationManager and returns a SimulationManager. Will be called with the SimulationManager 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 state and return its successors. Otherwise, project.factory.successors will be used.

  • filter_func – If provided, should be a function that takes a state and return the name of the stash, to which the state should be moved.

  • until – (DEPRECATED) If provided, should be a function that takes a SimulationManager and returns True or False. Stepping will terminate when it is True.

  • n – (DEPRECATED) The number of times to step (default: 1 if “until” is not provided)

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

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 simulation manager, for chaining.

Return type:

SimulationManager

step_state(state, successor_func=None, error_list=None, **run_args)[source]

Don’t use this function manually - it is meant to interface with exploration techniques.

filter(state, filter_func=None)[source]

Don’t use this function manually - it is meant to interface with exploration techniques.

selector(state, selector_func=None)[source]

Don’t use this function manually - it is meant to interface with exploration techniques.

successors(state, successor_func=None, **run_args)[source]

Don’t use this function manually - it is meant to interface with exploration techniques.

prune(filter_func=None, from_stash='active', to_stash='pruned')[source]

Prune unsatisfiable states from a stash.

This function will move all unsatisfiable states in the given stash into a different stash.

Parameters:
  • filter_func – Only prune states that match this filter.

  • from_stash – Prune states from this stash. (default: ‘active’)

  • to_stash – Put pruned states in this stash. (default: ‘pruned’)

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

populate(stash, states)[source]

Populate a stash with a collection of states.

Parameters:
  • stash – A stash to populate.

  • states – A list of states with which to populate the stash.

absorb(simgr)[source]

Collect all the states from simgr and put them in their corresponding stashes in this manager. This will not modify simgr.

move(from_stash, to_stash, filter_func=None)[source]

Move states from one stash to another.

Parameters:
  • from_stash – Take matching states from this stash.

  • to_stash – Put matching states into this stash.

  • filter_func – Stash states that match this filter. Should be a function that takes a state and returns True or False. (default: stash all states)

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

stash(filter_func=None, from_stash='active', to_stash='stashed')[source]

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

Parameters:
  • filter_func – Stash states that match this filter. Should be a function that takes a state and returns True or False. (default: stash all states)

  • from_stash – Take matching states from this stash. (default: ‘active’)

  • to_stash – Put matching states into this stash. (default: ‘stashed’)

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

unstash(filter_func=None, to_stash='active', from_stash='stashed')[source]

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

Parameters:
  • filter_func – Unstash states that match this filter. Should be a function that takes a state and returns True or False. (default: unstash all states)

  • from_stash – take matching states from this stash. (default: ‘stashed’)

  • to_stash – put matching states into this stash. (default: ‘active’)

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

drop(filter_func=None, stash='active')[source]

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

Parameters:
  • filter_func – Drop states that match this filter. Should be a function that takes a state and returns True or False. (default: drop all states)

  • stash – Drop matching states from this stash. (default: ‘active’)

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

apply(state_func=None, stash_func=None, stash='active', to_stash=None)[source]

Applies a given function to a given stash.

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

  • stash_func – A function to apply to the whole stash. Should take a list of states and return a list of states. The resulting list will replace the stash. If both state_func and stash_func are provided state_func is applied first, then stash_func is applied on the results.

  • stash – A stash to work with.

  • to_stash – If specified, this stash will be used to store the resulting states instead.

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

split(stash_splitter=None, stash_ranker=None, state_ranker=None, limit=8, from_stash='active', to_stash='stashed')[source]

Split a stash of states into two stashes depending on the specified options.

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 state_ranker. If no functions are provided, the states are simply split according to the limit.

The sort done with state_ranker is ascending.

Parameters:
  • stash_splitter – A function that should take a list of states and return a tuple of two lists (the two resulting stashes).

  • stash_ranker – A function that should take a list of states and return a sorted list of states. This list will then be split according to “limit”.

  • state_ranker – An alternative to stash_splitter. States will be sorted with outputs of this function, which are to be used as a key. The first “limit” of them will be kept, the rest split off.

  • limit – For use with state_ranker. The number of states to keep. Default: 8

  • from_stash – The stash to split (default: ‘active’)

  • to_stash – The stash to write to (default: ‘stashed’)

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

merge(merge_func=None, merge_key=None, stash='active', prune=True)[source]

Merge the states in a given stash.

Parameters:
  • stash – The stash (default: ‘active’)

  • merge_func – If provided, instead of using state.merge, call this function with the states as the argument. Should return the merged state.

  • merge_key – If provided, should be a function that takes a state and returns a key that will compare equal for all states that are allowed to be merged together, as a first approximation. By default: uses PC, callstack, and open file descriptors.

  • prune – Whether to prune the stash prior to merging it

Returns:

The simulation manager, for chaining.

Return type:

SimulationManager

class angr.Analysis[source]

Bases: object

This class represents an analysis on the program.

Variables:
  • project – The project for this analysis.

  • kb (KnowledgeBase) – The knowledgebase object.

  • _progress_callback – 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 (progress.Progress) – The progress bar object.

project: Project
kb: KnowledgeBase
errors = []
named_errors = {}
angr.register_analysis(cls, name)[source]
class angr.ExplorationTechnique[source]

Bases: object

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

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

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

__init__()[source]
setup(simgr)[source]

Perform any initialization on this manager you might need to do.

Parameters:

simgr (angr.SimulationManager) – The simulation manager to which you have just been added

step(simgr, stash='active', **kwargs)[source]

Hook the process of stepping a stash forward. Should call simgr.step(stash, **kwargs) in order to do the actual processing.

Parameters:
filter(simgr, state, **kwargs)[source]

Perform filtering on which stash a state should be inserted into.

If the state should be filtered, return the name of the stash to move the state to. If you want to modify the state before filtering it, return a tuple of the stash to move the state to and the modified state. To defer to the original categorization procedure, return the result of simgr.filter(state, **kwargs)

If the user provided a filter_func in their step or run command, it will appear here.

Parameters:
selector(simgr, state, **kwargs)[source]

Determine if a state should participate in the current round of stepping. Return True if the state should be stepped, and False if the state should not be stepped. To defer to the original selection procedure, return the result of simgr.selector(state, **kwargs).

If the user provided a selector_func in their step or run command, it will appear here.

Parameters:
step_state(simgr, state, **kwargs)[source]

Determine the categorization of state successors into stashes. The result should be a dict mapping stash names to the list of successor states that fall into that stash, or None as a stash name to use the original stash name.

If you would like to directly work with a SimSuccessors object, you can obtain it with simgr.successors(state, **kwargs). This is not recommended, as it denies other hooks the opportunity to look at the successors. Therefore, the usual technique is to call simgr.step_state(state, **kwargs) and then mutate the returned dict before returning it yourself.

..note:: This takes precedence over the filter hook - filter is only applied to states returned from here in the None stash.

Parameters:
successors(simgr, state, **kwargs)[source]

Perform the process of stepping a state forward, returning a SimSuccessors object.

To defer to the original succession procedure, return the result of simgr.successors(state, **kwargs). Be careful about not calling this method (e.g. calling project.factory.successors manually) as it denies other hooks the opportunity to instrument the step. Instead, you can mutate the kwargs for the step before calling the original, and mutate the result before returning it yourself.

If the user provided a successor_func in their step or run command, it will appear here.

Parameters:
complete(simgr)[source]

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

This is the one hook which is not subject to the nesting rules of hooks. You should not call simgr.complete, you should make your own decision and return True or False. Each of the techniques’ completion checkers will be called and the final result will be compted with simgr.completion_mode.

Parameters:

simgr (angr.SimulationManager)

class angr.StateHierarchy[source]

Bases: object

The state hierarchy holds weak references to SimStateHistory objects in a directed acyclic graph. It is useful for queries about a state’s ancestry, notably “what is the best ancestor state for a merge among these states” and “what is the most recent unsatisfiable state while using LAZY_SOLVES”

__init__()[source]
get_ref(obj)[source]
dead_ref(ref)[source]
defer_cleanup()[source]
add_state(s)[source]
add_history(h)[source]
simplify()[source]
full_simplify()[source]
lineage(h)[source]

Returns the lineage of histories leading up to h.

all_successors(h)[source]
history_successors(h)[source]
history_predecessors(h)[source]
history_contains(h)[source]
unreachable_state(state)[source]
unreachable_history(h)[source]
most_mergeable(states)[source]

Find the “most mergeable” set of states from those provided.

Parameters:

states – a list of states

Returns:

a tuple of: (list of states to merge, those states’ common history, list of states to not merge yet)

class angr.SimState(project=None, arch=None, plugins=None, mode=None, options=None, add_options=None, remove_options=None, special_memory_filler=None, os_name=None, plugin_preset='default', cle_memory_backer=None, dict_memory_backer=None, permissions_map=None, default_permissions=3, stack_perms=None, stack_end=None, stack_size=None, regioned_memory_cls=None, **kwargs)[source]

Bases: PluginHub

The SimState represents the state of a program, including its memory, registers, and so forth.

Parameters:
Variables:
  • regs – A convenient view of the state’s registers, where each register is a property

  • mem – A convenient view of the state’s memory, a angr.state_plugins.view.SimMemView

  • registers – The state’s register file as a flat memory region

  • memory – The state’s memory as a flat memory region

  • solver – The symbolic solver and variable manager for this state

  • inspect – The breakpoint manager, a angr.state_plugins.inspect.SimInspector

  • log – Information about the state’s history

  • scratch – Information about the current execution step

  • posix – MISNOMER: information about the operating system or environment model

  • fs – The current state of the simulated filesystem

  • libc – Information about the standard library we are emulating

  • cgc – Information about the cgc environment

  • uc_manager – Control of under-constrained symbolic execution

  • unicorn – Control of the Unicorn Engine

solver: SimSolver
posix: SimSystemPosix
registers: DefaultMemory
regs: SimRegNameView
memory: DefaultMemory
callstack: CallStack
mem: SimMemView
history: SimStateHistory
inspect: SimInspector
jni_references: SimStateJNIReferences
scratch: SimStateScratch
__init__(project=None, arch=None, plugins=None, mode=None, options=None, add_options=None, remove_options=None, special_memory_filler=None, os_name=None, plugin_preset='default', cle_memory_backer=None, dict_memory_backer=None, permissions_map=None, default_permissions=3, stack_perms=None, stack_end=None, stack_size=None, regioned_memory_cls=None, **kwargs)[source]
property plugins
property se

Deprecated alias for solver

property ip

Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions. Use _ip to not trigger breakpoints or generate actions.

Returns:

an expression

property addr

Get the concrete address of the instruction pointer, without triggering SimInspect breakpoints or generating SimActions. An integer is returned, or an exception is raised if the instruction pointer is symbolic.

Returns:

an int

property arch: Arch
T = ~T
get_plugin(name)[source]

Get the plugin named name. If no such plugin is currently active, try to activate a new one using the current preset.

has_plugin(name)[source]

Return whether or not a plugin with the name name is currently active.

register_plugin(name, plugin, inhibit_init=False)[source]

Add a new plugin plugin with name name to the active plugins.

property javavm_memory

In case of an JavaVM with JNI support, a state can store the memory plugin twice; one for the native and one for the java view of the state.

Returns:

The JavaVM view of the memory plugin.

property javavm_registers

In case of an JavaVM with JNI support, a state can store the registers plugin twice; one for the native and one for the java view of the state.

Returns:

The JavaVM view of the registers plugin.

simplify(*args)[source]

Simplify this state’s constraints.

add_constraints(*constraints)[source]

Add some constraints to the state.

You may pass in any number of symbolic booleans as variadic positional arguments.

satisfiable(**kwargs)[source]

Whether the state’s constraints are satisfiable

downsize()[source]

Clean up after the solver engine. Calling this when a state no longer needs to be solved on will reduce memory usage.

step(**kwargs)[source]

Perform a step of symbolic execution using this state. Any arguments to AngrObjectFactory.successors can be passed to this.

Returns:

A SimSuccessors object categorizing the results of the step.

block(*args, **kwargs)[source]

Represent the basic block at this state’s instruction pointer. Any arguments to AngrObjectFactory.block can ba passed to this.

Returns:

A Block object describing the basic block of code at this point.

copy()[source]

Returns a copy of the state.

merge(*others, **kwargs)[source]

Merges this state with the other states. Returns the merging result, merged state, and the merge flag.

Parameters:
  • states – the states to merge

  • merge_conditions – a tuple of the conditions under which each state holds

  • common_ancestor – a state that represents the common history between the states being merged. Usually it is only available when EFFICIENT_STATE_MERGING is enabled, otherwise weak-refed states might be dropped from state history instances.

  • plugin_whitelist – a list of plugin names that will be merged. If this option is given and is not None, any plugin that is not inside this list will not be merged, and will be created as a fresh instance in the new state.

  • common_ancestor_history – a SimStateHistory instance that represents the common history between the states being merged. This is to allow optimal state merging when EFFICIENT_STATE_MERGING is disabled.

Returns:

(merged state, merge flag, a bool indicating if any merging occurred)

widen(*others)[source]

Perform a widening between self and other states :type others: :param others: :return:

reg_concrete(*args, **kwargs)[source]

Returns the contents of a register but, if that register is symbolic, raises a SimValueError.

mem_concrete(*args, **kwargs)[source]

Returns the contents of a memory but, if the contents are symbolic, raises a SimValueError.

stack_push(thing)[source]

Push ‘thing’ to the stack, writing the thing to memory and adjusting the stack pointer.

stack_pop()[source]

Pops from the stack and returns the popped thing. The length will be the architecture word size.

stack_read(offset, length, bp=False)[source]

Reads length bytes, at an offset into the stack.

Parameters:
  • offset – The offset from the stack pointer.

  • length – The number of bytes to read.

  • bp – If True, offset from the BP instead of the SP. Default: False.

make_concrete_int(expr)[source]
prepare_callsite(retval, args, cc='wtf')[source]
dbg_print_stack(depth=None, sp=None)[source]

Only used for debugging purposes. Return the current stack info in formatted string. If depth is None, the current stack frame (from sp to bp) will be printed out.

set_mode(mode)[source]
property thumb
property with_condition
angr.default_cc(arch, platform='Linux', language=None, syscall=False, **kwargs)[source]

Return the default calling convention for a given architecture, platform, and language combination.

Parameters:
  • arch (str) – The architecture name.

  • platform (str | None) – The platform name (e.g., “Linux” or “Win32”).

  • language (Optional[str]) – The programming language name (e.g., “go”).

  • syscall (bool) – Return syscall convention (True), or normal calling convention (False, default).

Return type:

type[SimCC] | None

Returns:

A default calling convention class if we can find one for the architecture, platform, and language combination, or None if nothing fits.

class angr.PointerWrapper(value, buffer=False)[source]

Bases: object

__init__(value, buffer=False)[source]
class angr.SimCC(arch)[source]

Bases: object

A calling convention allows you to extract from a state the data passed from function to function by calls and returns. Most of the methods provided by SimCC that operate on a state assume that the program is just after a call but just before stack frame allocation, though this may be overridden with the stack_base parameter to each individual method.

This is the base class for all calling conventions.

Parameters:

arch (archinfo.Arch)

__init__(arch)[source]
Parameters:

arch (Arch) – The Archinfo arch for this CC

ARG_REGS: list[str] = []
FP_ARG_REGS: list[str] = []
STACKARG_SP_BUFF = 0
STACKARG_SP_DIFF = 0
CALLER_SAVED_REGS: list[str] = []
RETURN_ADDR: SimFunctionArgument = None
RETURN_VAL: SimFunctionArgument = None
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = None
FP_RETURN_VAL: SimFunctionArgument | None = None
ARCH = None
CALLEE_CLEANUP = False
STACK_ALIGNMENT = 1
property int_args

Iterate through all the possible arg positions that can only be used to store integer or pointer values.

Returns an iterator of SimFunctionArguments

property memory_args

Iterate through all the possible arg positions that can be used to store any kind of argument.

Returns an iterator of SimFunctionArguments

property fp_args

Iterate through all the possible arg positions that can only be used to store floating point values.

Returns an iterator of SimFunctionArguments

is_fp_arg(arg)[source]

This should take a SimFunctionArgument instance and return whether or not that argument is a floating-point argument.

Returns True for MUST be a floating point arg,

False for MUST NOT be a floating point arg, None for when it can be either.

class ArgSession(cc)

Bases: object

A class to keep track of the state accumulated in laying parameters out into memory

cc
fp_iter
int_iter
both_iter
__init__(cc)
getstate()
setstate(state)
arg_session(ret_ty)[source]

Return an arg session.

A session provides the control interface necessary to describe how integral and floating-point arguments are laid out into memory. The default behavior is that there are a finite list of int-only and fp-only argument slots, and an infinite number of generic slots, and when an argument of a given type is requested, the most slot available is used. If you need different behavior, subclass ArgSession.

You need to provide the return type of the function in order to kick off an arg layout session.

Parameters:

ret_ty (SimType | None)

return_in_implicit_outparam(ty)[source]
stack_space(args)[source]
Parameters:

args – A list of SimFunctionArguments

Returns:

The number of bytes that should be allocated on the stack to store all these args, NOT INCLUDING the return address.

return_val(ty, perspective_returned=False)[source]

The location the return value is stored, based on its type.

property return_addr

The location the return address is stored.

next_arg(session, arg_type)[source]
Parameters:
static is_fp_value(val)[source]
static guess_prototype(args, prototype=None)[source]

Come up with a plausible SimTypeFunction for the given args (as would be passed to e.g. setup_callsite).

You can pass a variadic function prototype in the base_type parameter and all its arguments will be used, only guessing types for the variadic arguments.

arg_locs(prototype)[source]
Return type:

list[SimFunctionArgument]

get_args(state, prototype, stack_base=None)[source]
set_return_val(state, val, ty, stack_base=None, perspective_returned=False)[source]
setup_callsite(state, ret_addr, args, prototype, stack_base=None, alloc_base=None, grow_like_stack=True)[source]

This function performs the actions of the caller getting ready to jump into a function.

Parameters:
  • state – The SimState to operate on

  • ret_addr – The address to return to when the called function finishes

  • args – The list of arguments that that the called function will see

  • prototype – The signature of the call you’re making. Should include variadic args concretely.

  • 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

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 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 stack base will be used and grow_like_stack will implicitly be True.

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 sequential allocations happen at increasing addresses.

teardown_callsite(state, return_val=None, prototype=None, force_callee_cleanup=False)[source]

This function performs the actions of the callee as it’s getting ready to return. It returns the address to return to.

Parameters:
  • state – The state to mutate

  • return_val – The value to return

  • prototype – The prototype of the given function

  • force_callee_cleanup – If we should clean up the stack allocation for the arguments even if it’s not the callee’s job to do so

TODO: support the stack_base parameter from setup_callsite…? Does that make sense in this context? Maybe it could make sense by saying that you pass it in as something like the “saved base pointer” value?

static find_cc(arch, args, sp_delta, platform='Linux')[source]

Pinpoint the best-fit calling convention and return the corresponding SimCC instance, or None if no fit is found.

Parameters:
  • arch (Arch) – An ArchX instance. Can be obtained from archinfo.

  • args (list[SimFunctionArgument]) – A list of arguments. It may be updated by the first matched calling convention to remove non-argument arguments.

  • sp_delta (int) – The change of stack pointer before and after the call is made.

  • platform (str)

Return type:

SimCC | None

Returns:

A calling convention instance, or None if none of the SimCC subclasses seems to fit the arguments provided.

get_arg_info(state, prototype)[source]

This is just a simple wrapper that collects the information from various locations prototype is as passed to self.arg_locs and self.get_args :param angr.SimState state: The state to evaluate and extract the values from :return: A list of tuples, where the nth tuple is (type, name, location, value) of the nth argument

class angr.SimFileBase(name=None, writable=True, ident=None, concrete=False, file_exists=True, **kwargs)[source]

Bases: SimStatePlugin

SimFiles are the storage mechanisms used by SimFileDescriptors.

Different types of SimFiles can have drastically different interfaces, and as a result there’s not much that can be specified on this base class. All the read and write methods take a pos argument, which may have different semantics per-class. 0 will always be a valid position to use, though, and the next position you should use is part of the return tuple.

Some simfiles are “streams”, meaning that the position that reads come from is determined not by the position you pass in (it will in fact be ignored), but by an internal variable. This is stored as .pos if you care to read it. Don’t write to it. The same lack-of-semantics applies to this field as well.

Variables:
  • name – The name of the file. Purely for cosmetic purposes

  • ident – The identifier of the file, typically autogenerated from the name and a nonce. Purely for cosmetic purposes, but does appear in symbolic values autogenerated in the file.

  • seekable – Bool indicating whether seek operations on this file should succeed. If this is True, then pos must be a number of bytes from the start of the file.

  • writable – Bool indicating whether writing to this file is allowed.

  • pos – If the file is a stream, this will be the current position. Otherwise, None.

  • concrete – Whether or not this file contains mostly concrete data. Will be used by some SimProcedures to choose how to handle variable-length operations like fgets.

  • file_exists – Set to False, if file does not exists, set to a claripy Bool if unknown, default True.

seekable = False
pos = None
__init__(name=None, writable=True, ident=None, concrete=False, file_exists=True, **kwargs)[source]
static make_ident(name)[source]
concretize(**kwargs)[source]

Return a concretization of the contents of the file. The type of the return value of this method will vary depending on which kind of SimFile you’re using.

read(pos, size, **kwargs)[source]

Read some data from the file.

Parameters:
  • pos – The offset in the file to read from.

  • size – The size to read. May be symbolic.

Returns:

A tuple of the data read (a bitvector of the length that is the maximum length of the read), the actual size of the read, and the new file position pointer.

write(pos, data, size=None, **kwargs)[source]

Write some data to the file.

Parameters:
  • pos – The offset in the file to write to. May be ignored if the file is a stream or device.

  • data – The data to write as a bitvector

  • size – The optional size of the data to write. If not provided will default to the length of the data. Must be constrained to less than or equal to the size of the data.

Returns:

The new file position pointer.

property size

The number of data bytes stored by the file at present. May be a symbolic value.

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

class angr.SimFile(name=None, content=None, size=None, has_end=None, seekable=True, writable=True, ident=None, concrete=None, **kwargs)[source]

Bases: SimFileBase, DefaultMemory

The normal SimFile is meant to model files on disk. It subclasses SimSymbolicMemory so loads and stores to/from it are very simple.

Parameters:
  • name – The name of the file

  • content – Optional initial content for the file as a string or bitvector

  • size – Optional size of the file. If content is not specified, it defaults to zero

  • has_end – Whether the size boundary is treated as the end of the file or a frontier at which new content will be generated. If unspecified, will pick its value based on options.FILES_HAVE_EOF. Another caveat is that if the size is also unspecified this value will default to False.

  • seekable – Optional bool indicating whether seek operations on this file should succeed, default True.

  • writable – Whether writing to this file is allowed

  • concrete – Whether or not this file contains mostly concrete data. Will be used by some SimProcedures to choose how to handle variable-length operations like fgets.

Variables:

has_end – Whether this file has an EOF

__init__(name=None, content=None, size=None, has_end=None, seekable=True, writable=True, ident=None, concrete=None, **kwargs)[source]
property category

reg, mem, or file.

Type:

Return the category of this SimMemory instance. It can be one of the three following categories

set_state(state)[source]

Sets a new state (for example, if the state has been branched)

property size

The number of data bytes stored by the file at present. May be a symbolic value.

concretize(**kwargs)[source]

Return a concretization of the contents of the file, as a flat bytestring.

read(pos, size, **kwargs)[source]

Read some data from the file.

Parameters:
  • pos – The offset in the file to read from.

  • size – The size to read. May be symbolic.

Returns:

A tuple of the data read (a bitvector of the length that is the maximum length of the read), the actual size of the read, and the new file position pointer.

write(pos, data, size=None, events=True, **kwargs)[source]

Write some data to the file.

Parameters:
  • pos – The offset in the file to write to. May be ignored if the file is a stream or device.

  • data – The data to write as a bitvector

  • size – The optional size of the data to write. If not provided will default to the length of the data. Must be constrained to less than or equal to the size of the data.

Returns:

The new file position pointer.

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(_)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

class angr.SimPackets(name, write_mode=None, content=None, writable=True, ident=None, **kwargs)[source]

Bases: SimFileBase

The SimPackets is meant to model inputs whose content is delivered a series of asynchronous chunks. The data is stored as a list of read or write results. For symbolic sizes, state.libc.max_packet_size will be respected. If the SHORT_READS option is enabled, reads will return a symbolic size constrained to be less than or equal to the requested size.

A SimPackets cannot be used for both reading and writing - for socket objects that can be both read and written to you should use a file descriptor to multiplex the read and write operations into two separate file storage mechanisms.

Parameters:
  • name – The name of the file, for cosmetic purposes

  • write_mode – Whether this file is opened in read or write mode. If this is unspecified it will be autodetected.

  • content – Some initial content to use for the file. Can be a list of bytestrings or a list of tuples of content ASTs and size ASTs.

Variables:
  • write_mode – See the eponymous parameter

  • content – A list of packets, as tuples of content ASTs and size ASTs.

__init__(name, write_mode=None, content=None, writable=True, ident=None, **kwargs)[source]
set_state(state)[source]

Sets a new state (for example, if the state has been branched)

property size

The number of data bytes stored by the file at present. May be a symbolic value.

concretize(**kwargs)[source]

Returns a list of the packets read or written as bytestrings.

read(pos, size, **kwargs)[source]

Read a packet from the stream.

Parameters:
  • pos (int) – The packet number to read from the sequence of the stream. May be None to append to the stream.

  • size – The size to read. May be symbolic.

  • short_reads – Whether to replace the size with a symbolic value constrained to less than or equal to the original size. If unspecified, will be chosen based on the state option.

Returns:

A tuple of the data read (a bitvector of the length that is the maximum length of the read) and the actual size of the read.

write(pos, data, size=None, events=True, **kwargs)[source]

Write a packet to the stream.

Parameters:
  • pos (int) – The packet number to write in the sequence of the stream. May be None to append to the stream.

  • data – The data to write, as a string or bitvector.

  • size – The optional size to write. May be symbolic; must be constrained to at most the size of data.

Returns:

The next packet to use after this

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(_)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

class angr.SimFileStream(name=None, content=None, pos=0, **kwargs)[source]

Bases: SimFile

A specialized SimFile that uses a flat memory backing, but functions as a stream, tracking its position internally.

The pos argument to the read and write methods will be ignored, and will return None. Instead, there is an attribute pos on the file itself, which will give you what you want.

Parameters:
  • name – The name of the file, for cosmetic purposes

  • pos – The initial position of the file, default zero

  • kwargs – Any other keyword arguments will go on to the SimFile constructor.

Variables:

pos – The current position in the file.

__init__(name=None, content=None, pos=0, **kwargs)[source]
set_state(state)[source]

Sets a new state (for example, if the state has been branched)

read(pos, size, **kwargs)[source]

Read some data from the file.

Parameters:
  • pos – The offset in the file to read from.

  • size – The size to read. May be symbolic.

Returns:

A tuple of the data read (a bitvector of the length that is the maximum length of the read), the actual size of the read, and the new file position pointer.

write(_, data, size=None, **kwargs)[source]

Write some data to the file.

Parameters:
  • pos – The offset in the file to write to. May be ignored if the file is a stream or device.

  • data – The data to write as a bitvector

  • size – The optional size of the data to write. If not provided will default to the length of the data. Must be constrained to less than or equal to the size of the data.

Returns:

The new file position pointer.

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

class angr.SimPacketsStream(name, pos=0, **kwargs)[source]

Bases: SimPackets

A specialized SimPackets that tracks its position internally.

The pos argument to the read and write methods will be ignored, and will return None. Instead, there is an attribute pos on the file itself, which will give you what you want.

Parameters:
  • name – The name of the file, for cosmetic purposes

  • pos – The initial position of the file, default zero

  • kwargs – Any other keyword arguments will go on to the SimPackets constructor.

Variables:

pos – The current position in the file.

__init__(name, pos=0, **kwargs)[source]
read(pos, size, **kwargs)[source]

Read a packet from the stream.

Parameters:
  • pos (int) – The packet number to read from the sequence of the stream. May be None to append to the stream.

  • size – The size to read. May be symbolic.

  • short_reads – Whether to replace the size with a symbolic value constrained to less than or equal to the original size. If unspecified, will be chosen based on the state option.

Returns:

A tuple of the data read (a bitvector of the length that is the maximum length of the read) and the actual size of the read.

write(_, data, size=None, **kwargs)[source]

Write a packet to the stream.

Parameters:
  • pos (int) – The packet number to write in the sequence of the stream. May be None to append to the stream.

  • data – The data to write, as a string or bitvector.

  • size – The optional size to write. May be symbolic; must be constrained to at most the size of data.

Returns:

The next packet to use after this

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

class angr.SimFileDescriptor(simfile, flags=0)[source]

Bases: SimFileDescriptorBase

A simple file descriptor forwarding reads and writes to a SimFile. Contains information about the current opened state of the file, such as the flags or (if relevant) the current position.

Variables:
  • file – The SimFile described to by this descriptor

  • flags – The mode that the file descriptor was opened with, a bitfield of flags

__init__(simfile, flags=0)[source]
read_data(size, **kwargs)[source]

Reads some data from the file, returning the data.

Parameters:

size – The requested length of the read

Returns:

A tuple of the data read and the real length of the read

write_data(data, size=None, **kwargs)[source]

Write some data, provided as an argument into the file.

Parameters:
  • data – A bitvector to write into the file

  • size – The requested size of the write (may be symbolic)

Returns:

The real length of the write

seek(offset, whence='start')[source]

Seek the file descriptor to a different position in the file.

Parameters:
  • offset – The offset to seek to, interpreted according to whence

  • whence – What the offset is relative to; one of the strings “start”, “current”, or “end”

Returns:

A symbolic boolean describing whether the seek succeeded or not

eof()[source]

Return the EOF status. May be a symbolic boolean.

tell()[source]

Return the current position, or None if the concept doesn’t make sense for the given file.

size()[source]

Return the size of the data stored in the file in bytes, or None if the concept doesn’t make sense for the given file.

concretize(**kwargs)[source]

Return a concretization of the underlying file. Returns whatever format is preferred by the file.

property file_exists

This should be True in most cases. Only if we opened an fd of unknown existence, ALL_FILES_EXIST is False and ANY_FILE_MIGHT_EXIST is True, this is a symbolic boolean.

property read_storage

Return the SimFile backing reads from this fd

property write_storage

Return the SimFile backing writes to this fd

property read_pos

Return the current position of the read file pointer.

If the underlying read file is a stream, this will return the position of the stream. Otherwise, will return the position of the file descriptor in the file.

property write_pos

Return the current position of the read file pointer.

If the underlying read file is a stream, this will return the position of the stream. Otherwise, will return the position of the file descriptor in the file.

set_state(state)[source]

Sets a new state (for example, if the state has been branched)

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(_)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

class angr.SimFileDescriptorDuplex(read_file, write_file)[source]

Bases: SimFileDescriptorBase

A file descriptor that refers to two file storage mechanisms, one to read from and one to write to. As a result, operations like seek, eof, etc no longer make sense.

Parameters:
  • read_file – The SimFile to read from

  • write_file – The SimFile to write to

__init__(read_file, write_file)[source]
read_data(size, **kwargs)[source]

Reads some data from the file, returning the data.

Parameters:

size – The requested length of the read

Returns:

A tuple of the data read and the real length of the read

write_data(data, size=None, **kwargs)[source]

Write some data, provided as an argument into the file.

Parameters:
  • data – A bitvector to write into the file

  • size – The requested size of the write (may be symbolic)

Returns:

The real length of the write

set_state(state)[source]

Sets a new state (for example, if the state has been branched)

eof()[source]

Return the EOF status. May be a symbolic boolean.

tell()[source]

Return the current position, or None if the concept doesn’t make sense for the given file.

seek(offset, whence='start')[source]

Seek the file descriptor to a different position in the file.

Parameters:
  • offset – The offset to seek to, interpreted according to whence

  • whence – What the offset is relative to; one of the strings “start”, “current”, or “end”

Returns:

A symbolic boolean describing whether the seek succeeded or not

size()[source]

Return the size of the data stored in the file in bytes, or None if the concept doesn’t make sense for the given file.

concretize(**kwargs)[source]

Return a concretization of the underlying files, as a tuple of (read file, write file).

property read_storage

Return the SimFile backing reads from this fd

property write_storage

Return the SimFile backing writes to this fd

property read_pos

Return the current position of the read file pointer.

If the underlying read file is a stream, this will return the position of the stream. Otherwise, will return the position of the file descriptor in the file.

property write_pos

Return the current position of the read file pointer.

If the underlying read file is a stream, this will return the position of the stream. Otherwise, will return the position of the file descriptor in the file.

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(_)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

class angr.SimMount[source]

Bases: SimStatePlugin

This is the base class for “mount points” in angr’s simulated filesystem. Subclass this class and give it to the filesystem to intercept all file creations and opens below the mountpoint. Since this a SimStatePlugin you may also want to implement set_state, copy, merge, etc.

get(path_elements)[source]

Implement this function to instrument file lookups.

Parameters:

path_elements – A list of path elements traversing from the mountpoint to the file

Returns:

A SimFile, or None

insert(path_elements, simfile)[source]

Implement this function to instrument file creation.

Parameters:
  • path_elements – A list of path elements traversing from the mountpoint to the file

  • simfile – The file to insert

Returns:

A bool indicating whether the insert occurred

delete(path_elements)[source]

Implement this function to instrument file deletion.

Parameters:

path_elements – A list of path elements traversing from the mountpoint to the file

Returns:

A bool indicating whether the delete occurred

lookup(sim_file)[source]

Look up the path of a SimFile in the mountpoint

Parameters:

sim_file – A SimFile object needs to be looked up

Returns:

A string representing the path of the file in the mountpoint Or None if the SimFile does not exist in the mountpoint

class angr.SimHostFilesystem(host_path=None, **kwargs)[source]

Bases: SimConcreteFilesystem

Simulated mount that makes some piece from the host filesystem available to the guest.

Parameters:
  • host_path (str) – The path on the host to mount

  • pathsep (str) – The host path separator character, default os.path.sep

__init__(host_path=None, **kwargs)[source]
copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

class angr.SimHeapBrk(heap_base=None, heap_size=None)[source]

Bases: SimHeapBase

SimHeapBrk represents a trivial heap implementation based on the Unix brk system call. This type of heap stores virtually no metadata, so it is up to the user to determine when it is safe to release memory. This also means that it does not properly support standard heap operations like realloc.

This heap implementation is a holdover from before any more proper implementations were modelled. At the time, various libc (or win32) SimProcedures handled the heap in the same way that this plugin does now. To make future heap implementations plug-and-playable, they should implement the necessary logic themselves, and dependent SimProcedures should invoke a method by the same name as theirs (prepended with an underscore) upon the heap plugin. Depending on the heap implementation, if the method is not supported, an error should be raised.

Out of consideration for the original way the heap was handled, this plugin implements functionality for all relevant SimProcedures (even those that would not normally be supported together in a single heap implementation).

Variables:

heap_location – the address of the top of the heap, bounding the allocations made starting from heap_base

__init__(heap_base=None, heap_size=None)[source]
copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

allocate(sim_size)[source]

The actual allocation primitive for this heap implementation. Increases the position of the break to allocate space. Has no guards against the heap growing too large.

Parameters:

sim_size – a size specifying how much to increase the break pointer by

Returns:

a pointer to the previous break position, above which there is now allocated space

release(sim_size)[source]

The memory release primitive for this heap implementation. Decreases the position of the break to deallocate space. Guards against releasing beyond the initial heap base.

Parameters:

sim_size – a size specifying how much to decrease the break pointer by (may be symbolic or not)

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

class angr.SimHeapPTMalloc(heap_base=None, heap_size=None)[source]

Bases: SimHeapFreelist

A freelist-style heap implementation inspired by ptmalloc. The chunks used by this heap contain heap metadata in addition to user data. While the real-world ptmalloc is implemented using multiple lists of free chunks (corresponding to their different sizes), this more basic model uses a single list of chunks and searches for free chunks using a first-fit algorithm.

NOTE: The plugin must be registered using register_plugin with name heap in order to function properly.

Variables:
  • heap_base – the address of the base of the heap in memory

  • heap_size – the total size of the main memory region managed by the heap in memory

  • mmap_base – the address of the region from which large mmap allocations will be made

  • free_head_chunk – the head of the linked list of free chunks in the heap

__init__(heap_base=None, heap_size=None)[source]
copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

chunks()[source]

Returns an iterator over all the chunks in the heap.

allocated_chunks()[source]

Returns an iterator over all the allocated chunks in the heap.

free_chunks()[source]

Returns an iterator over all the free chunks in the heap.

chunk_from_mem(ptr)[source]

Given a pointer to a user payload, return the base of the chunk associated with that payload (i.e. the chunk pointer). Returns None if ptr is null.

Parameters:

ptr – a pointer to the base of a user payload in the heap

Returns:

a pointer to the base of the associated heap chunk, or None if ptr is null

malloc(sim_size)[source]

A somewhat faithful implementation of libc malloc.

Parameters:

sim_size – the amount of memory (in bytes) to be allocated

Returns:

the address of the allocation, or a NULL pointer if the allocation failed

free(ptr)[source]

A somewhat faithful implementation of libc free.

Parameters:

ptr – the location in memory to be freed

calloc(sim_nmemb, sim_size)[source]

A somewhat faithful implementation of libc calloc.

Parameters:
  • sim_nmemb – the number of elements to allocated

  • sim_size – the size of each element (in bytes)

Returns:

the address of the allocation, or a NULL pointer if the allocation failed

realloc(ptr, size)[source]

A somewhat faithful implementation of libc realloc.

Parameters:
  • ptr – the location in memory to be reallocated

  • size – the new size desired for the allocation

Returns:

the address of the allocation, or a NULL pointer if the allocation was freed or if no new allocation was made

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

init_state()[source]

Use this function to perform any initialization on the state at plugin-add time

class angr.PTChunk(base, sim_state, heap=None)[source]

Bases: Chunk

A chunk, inspired by the implementation of chunks in ptmalloc. Provides a representation of a chunk via a view into the memory plugin. For the chunk definitions and docs that this was loosely based off of, see glibc malloc/malloc.c, line 1033, as of commit 5a580643111ef6081be7b4c7bd1997a5447c903f. Alternatively, take the following link. https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=67cdfd0ad2f003964cd0f7dfe3bcd85ca98528a7;hb=5a580643111ef6081be7b4c7bd1997a5447c903f#l1033

Variables:
  • base – the location of the base of the chunk in memory

  • state – the program state that the chunk is resident in

  • heap – the heap plugin that the chunk is managed by

__init__(base, sim_state, heap=None)[source]
get_size()[source]

Returns the actual size of a chunk (as opposed to the entire size field, which may include some flags).

get_data_size()[source]

Returns the size of the data portion of a chunk.

set_size(size, is_free=None)[source]

Use this to set the size on a chunk. When the chunk is new (such as when a free chunk is shrunk to form an allocated chunk and a remainder free chunk) it is recommended that the is_free hint be used since setting the size depends on the chunk’s freeness, and vice versa.

Parameters:
  • size – size of the chunk

  • is_free – boolean indicating the chunk’s freeness

set_prev_freeness(is_free)[source]

Sets (or unsets) the flag controlling whether the previous chunk is free.

Parameters:

is_free – if True, sets the previous chunk to be free; if False, sets it to be allocated

is_prev_free()[source]

Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free.

Returns:

True if the previous chunk is free; False otherwise

prev_size()[source]

Returns the size of the previous chunk, masking off what would be the flag bits if it were in the actual size field. Performs NO CHECKING to determine whether the previous chunk size is valid (for example, when the previous chunk is not free, its size cannot be determined).

is_free()[source]

Returns a concrete determination as to whether the chunk is free.

data_ptr()[source]

Returns the address of the payload of the chunk.

next_chunk()[source]

Returns the chunk immediately following (and adjacent to) this one, if it exists.

Returns:

The following chunk, or None if applicable

prev_chunk()[source]

Returns the chunk immediately prior (and adjacent) to this one, if that chunk is free. If the prior chunk is not free, then its base cannot be located and this method raises an error.

Returns:

If possible, the previous chunk; otherwise, raises an error

fwd_chunk()[source]

Returns the chunk following this chunk in the list of free chunks. If this chunk is not free, then it resides in no such list and this method raises an error.

Returns:

If possible, the forward chunk; otherwise, raises an error

set_fwd_chunk(fwd)[source]

Sets the chunk following this chunk in the list of free chunks.

Parameters:

fwd – the chunk to follow this chunk in the list of free chunks

bck_chunk()[source]

Returns the chunk backward from this chunk in the list of free chunks. If this chunk is not free, then it resides in no such list and this method raises an error.

Returns:

If possible, the backward chunk; otherwise, raises an error

set_bck_chunk(bck)[source]

Sets the chunk backward from this chunk in the list of free chunks.

Parameters:

bck – the chunk to precede this chunk in the list of free chunks

class angr.Server(project, spill_yard=None, db=None, max_workers=None, max_states=10, staging_max=10, bucketizer=True, recursion_limit=1000, worker_exit_callback=None, techniques=None, add_options=None, remove_options=None)[source]

Bases: object

Server implements the analysis server with a series of control interfaces exposed.

Variables:
  • project – An instance of angr.Project.

  • spill_yard (str) – A directory to store spilled states.

  • db (str) – Path of the database that stores information about spilled states.

  • max_workers (int) – Maximum number of workers. Each worker starts a new process.

  • max_states (int) – Maximum number of active states for each worker.

  • staging_max (int) – Maximum number of inactive states that are kept into memory before spilled onto the disk and potentially be picked up by another worker.

  • bucketizer (bool) – Use the Bucketizer exploration strategy.

  • _worker_exit_callback – A method that will be called upon the exit of each worker.

__init__(project, spill_yard=None, db=None, max_workers=None, max_states=10, staging_max=10, bucketizer=True, recursion_limit=1000, worker_exit_callback=None, techniques=None, add_options=None, remove_options=None)[source]
inc_active_workers()[source]
dec_active_workers()[source]
stop()[source]
property active_workers
property stopped
on_worker_exit(worker_id, stashes)[source]
run()[source]
class angr.KnowledgeBase(project, obj=None, name=None)[source]

Bases: object

Represents a “model” of knowledge about an artifact.

Contains things like a CFG, data references, etc.

functions: FunctionManager
variables: VariableManager
structured_code: StructuredCodeManager
defs: KeyDefinitionManager
cfgs: CFGManager
types: TypesStore
propagations: PropagationManager
xrefs: XRefManager
__init__(project, obj=None, name=None)[source]
property callgraph
property unresolved_indirect_jumps
property resolved_indirect_jumps
has_plugin(name)[source]
get_plugin(name)[source]
register_plugin(name, plugin)[source]
release_plugin(name)[source]
K = ~K
get_knowledge(requested_plugin_cls)[source]

Type inference safe method to request a knowledge base plugin Explicitly passing the type of the requested plugin achieves two things: 1. Every location using this plugin can be easily found with an IDE by searching explicit references to the type 2. Basic type inference can deduce the result type and properly type check usages of it

If there isn’t already an instance of this class None will be returned to make it clear to the caller that there is no existing knowledge of this type yet. The code that initially creates this knowledge should use the register_plugin method to register the initial knowledge state :type requested_plugin_cls: type[K] :param requested_plugin_cls: :rtype: K | None :return: Instance of the requested plugin class or null if it is not a known plugin

Parameters:

requested_plugin_cls (type[K])

Return type:

K | None

request_knowledge(requested_plugin_cls)[source]
Return type:

K

Parameters:

requested_plugin_cls (type[K])

Project

angr.project.load_shellcode(shellcode, arch, start_offset=0, load_address=0, thumb=False, **kwargs)[source]

Load a new project based on a snippet of assembly or bytecode.

Parameters:
  • shellcode (bytes | str) – The data to load, as either a bytestring of instructions or a string of assembly text

  • arch – The name of the arch to use, or an archinfo class

  • start_offset – The offset into the data to start analysis (default 0)

  • load_address – The address to place the data in memory (default 0)

  • thumb – Whether this is ARM Thumb shellcode

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, engine=None, load_options=None, translation_cache=True, selfmodifying_code=False, support_selfmodifying_code=None, store_function=None, load_function=None, analyses_preset=None, concrete_target=None, eager_ifunc_resolution=None, **kwargs)[source]

Bases: object

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.

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

  • arch (Arch)

  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

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_procedures – 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.

  • engine – The SimEngine class to use for this project.

  • translation_cache (bool) – If True, cache translated basic blocks rather than re-translating them.

  • selfmodifying_code (bool) – Whether we aggressively support self-modifying code. When enabled, emulation will try to read code from the current state instead of the original memory, regardless of the current memory protections.

  • store_function – A function that defines how the Project should be stored. Default to pickling.

  • load_function – A function that defines how the Project should be loaded. Default to unpickling.

  • analyses_preset (angr.misc.PluginPreset) – The plugin preset for the analyses provider (i.e. Analyses instance).

  • load_options (dict[str, Any] | None)

  • support_selfmodifying_code (bool | None)

Any additional keyword arguments passed will be passed onto cle.Loader.

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.

  • storage – Dictionary of things that should be loaded/stored with the Project.

Parameters:
  • arch (Arch)

  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

__init__(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, engine=None, load_options=None, translation_cache=True, selfmodifying_code=False, support_selfmodifying_code=None, store_function=None, load_function=None, analyses_preset=None, concrete_target=None, eager_ifunc_resolution=None, **kwargs)[source]
Parameters:
  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

arch: Arch
property analyses: AnalysesHubWithDefault
hook(addr, hook=None, length=0, kwargs=None, replace=False)[source]

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.

When hook is not specified, it returns a function decorator that allows easy hooking. Usage:

# Assuming proj is an instance of angr.Project, we will add a custom hook at the entry
# point of the project.
@proj.hook(proj.entry)
def my_hook(state):
    print("Welcome to execution!")
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.

  • replace (bool | None) – Control the behavior on finding that the address is already hooked. If true, silently replace the hook. If false (default), warn and do not replace the hook. If none, warn and replace the hook.

is_hooked(addr)[source]

Returns True if addr is hooked.

Parameters:

addr – An address.

Return type:

bool

Returns:

True if addr is hooked, False otherwise.

hooked_by(addr)[source]

Returns the current hook for addr.

Parameters:

addr – An address.

Return type:

SimProcedure | None

Returns:

None if the address is not hooked.

unhook(addr)[source]

Remove a hook.

Parameters:

addr – The address of the hook.

hook_symbol(symbol_name, simproc, kwargs=None, replace=None)[source]

Resolve a dependency in a binary. Looks up the address of the given symbol, and then hooks that address. If the symbol was not available in the loaded libraries, this address may be provided by the CLE externs object.

Additionally, if instead of a symbol name you provide an address, some secret functionality will kick in and you will probably just hook that address, UNLESS you’re on powerpc64 ABIv1 or some yet-unknown scary ABI that has its function pointers point to something other than the actual functions, in which case it’ll do the right thing.

Parameters:
  • symbol_name – The name of the dependency to resolve.

  • simproc – The SimProcedure instance (or function) with which to hook the symbol

  • 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.

  • replace (Optional[bool]) – Control the behavior on finding that the address is already hooked. If true, silently replace the hook. If false, warn and do not replace the hook. If none (default), warn and replace the hook.

Returns:

The address of the new symbol.

Return type:

int

symbol_hooked_by(symbol_name)[source]

Return the SimProcedure, if it exists, for the given symbol name.

Parameters:

symbol_name (str) – Name of the symbol.

Return type:

SimProcedure | None

Returns:

None if the address is not hooked.

is_symbol_hooked(symbol_name)[source]

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

unhook_symbol(symbol_name)[source]

Remove the hook on a symbol. This function will fail if the symbol is provided by the extern object, as that would result in a state where analysis would be unable to cope with a call to this symbol.

rehook_symbol(new_address, symbol_name, stubs_on_sync)[source]

Move the hook for a symbol to a specific address :type new_address: :param new_address: the new address that will trigger the SimProc execution :type symbol_name: :param symbol_name: the name of the symbol (f.i. strcmp ) :return: None

execute(*args, **kwargs)[source]

This function is a symbolic execution helper in the simple style supported by triton and manticore. It designed to be run after setting up hooks (see Project.hook), in which the symbolic state can be checked.

This function can be run in three different ways:

  • When run with no parameters, this function begins symbolic execution from the entrypoint.

  • It can also be run with a “state” parameter specifying a SimState to begin symbolic execution from.

  • Finally, it can accept any arbitrary keyword arguments, which are all passed to project.factory.full_init_state.

If symbolic execution finishes, this function returns the resulting simulation manager.

terminate_execution()[source]

Terminates a symbolic execution that was started with Project.execute().

class angr.factory.AngrObjectFactory(project, default_engine=None)[source]

Bases: object

This factory provides access to important analysis elements.

Parameters:

default_engine (type[SimEngine] | None)

__init__(project, default_engine=None)[source]
Parameters:

default_engine (type[SimEngine] | None)

snippet(addr, jumpkind=None, **block_opts)[source]
successors(*args, engine=None, **kwargs)[source]

Perform execution using an engine. Generally, return a SimSuccessors object classifying the results of the run.

Parameters:
  • state – The state to analyze

  • engine – The engine to use. If not provided, will use the project default.

  • 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.

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

blank_state(**kwargs)[source]

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:

SimState

entry_state(**kwargs)[source]

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:

SimState

full_init_state(**kwargs)[source]

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.

It can take any of the arguments that can be provided to entry_state, except for addr.

call_state(addr, *args, **kwargs)[source]

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

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 sequential allocations happen at increasing addresses.

simulation_manager(thing=None, **kwargs)[source]

Constructs a new simulation manager.

Parameters:
  • thing (Union[list[SimState], SimState, None]) – What to put in the new SimulationManager’s active stash (either a SimState or a list of SimStates).

  • kwargs – Any additional keyword arguments will be passed to the SimulationManager constructor

Returns:

The new SimulationManager

Return type:

angr.sim_manager.SimulationManager

Many different types can be passed to this method:

  • If nothing is passed in, the SimulationManager is seeded with a state initialized for the program entry point, i.e. entry_state().

  • If a SimState is passed in, the SimulationManager is seeded with that state.

  • If a list is passed in, the list must contain only SimStates and the whole list will be used to seed the SimulationManager.

simgr(*args, **kwargs)[source]

Alias for simulation_manager to save our poor fingers

callable(addr, prototype=None, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None, add_options=None, remove_options=None)[source]

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

  • prototype – The prototype of the call to use, as a string or a SimTypeFunction

  • concrete_only – Throw an exception if the execution splits into multiple states

  • 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.callable.Callable

cc()[source]

Return a SimCC (calling convention) parameterized for this project.

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.

function_prototype()[source]

Return a default function prototype parameterized for this project and SimOS.

block(addr, size=None, max_size=None, byte_string=None, vex=None, thumb=False, backup_state=None, extra_stop_points=None, opt_level=None, num_inst=None, traceflags=0, insn_bytes=None, insn_text=None, strict_block_end=None, collect_data_refs=False, cross_insn_opt=True, load_from_ro_regions=False, const_prop=False, initial_regs=None, skip_stmts=False)[source]
fresh_block(addr, size, backup_state=None)[source]
class angr.block.DisassemblerBlock(addr, insns, thumb, arch)[source]

Bases: object

Helper class to represent a block of disassembled target architecture instructions

__init__(addr, insns, thumb, arch)[source]
addr
insns
thumb
arch
pp()[source]
class angr.block.DisassemblerInsn[source]

Bases: object

Helper class to represent a disassembled target architecture instruction

property size: int
property address: int
property mnemonic: str
property op_str: str
class angr.block.CapstoneBlock(addr, insns, thumb, arch)[source]

Bases: DisassemblerBlock

Deep copy of the capstone blocks, which have serious issues with having extended lifespans outside of capstone itself

class angr.block.CapstoneInsn(capstone_insn)[source]

Bases: DisassemblerInsn

Represents a capstone instruction.

__init__(capstone_insn)[source]
insn
property size: int
property address: int
property mnemonic: str
property op_str: str
class angr.block.Block(addr, project=None, arch=None, size=None, max_size=None, byte_string=None, vex=None, thumb=False, backup_state=None, extra_stop_points=None, opt_level=None, num_inst=None, traceflags=0, strict_block_end=None, collect_data_refs=False, cross_insn_opt=True, load_from_ro_regions=False, const_prop=False, initial_regs=None, skip_stmts=False)[source]

Bases: Serializable

Represents a basic block in a binary or a program.

BLOCK_MAX_SIZE = 4096
__init__(addr, project=None, arch=None, size=None, max_size=None, byte_string=None, vex=None, thumb=False, backup_state=None, extra_stop_points=None, opt_level=None, num_inst=None, traceflags=0, strict_block_end=None, collect_data_refs=False, cross_insn_opt=True, load_from_ro_regions=False, const_prop=False, initial_regs=None, skip_stmts=False)[source]
arch
thumb
addr
size
pp(**kwargs)[source]
set_initial_regs()[source]
static reset_initial_regs()[source]
property vex: IRSB
property vex_nostmt
property disassembly: DisassemblerBlock

Provide a disassembly object using whatever disassembler is available

property capstone
property codenode
property bytes: bytes
property instructions
property instruction_addrs
serialize_to_cmessage()[source]

Serialize the class object and returns a protobuf cmessage object.

Returns:

A protobuf cmessage object.

Return type:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg)[source]

Parse a protobuf cmessage and create a class object.

Parameters:

cmsg – The probobuf cmessage object.

Returns:

A unserialized class object.

Return type:

cls

class angr.block.SootBlock(addr, project=None, arch=None)[source]

Bases: object

Represents a Soot IR basic block.

__init__(addr, project=None, arch=None)[source]
property soot
property size
property codenode

Plugin Ecosystem

class angr.misc.plugins.PluginHub[source]

Bases: Generic[P]

A plugin hub is an object which contains many plugins, as well as the notion of a “preset”, or a backer that can provide default implementations of plugins which cater to a certain circumstance.

Objects in angr like the SimState, the Analyses hub, the SimEngine selector, etc all use this model to unify their mechanisms for automatically collecting and selecting components to use. If you’re familiar with design patterns this is a configurable Strategy Pattern.

Each PluginHub subclass should have a corresponding Plugin subclass, and perhaps a PluginPreset subclass if it wants its presets to be able to specify anything more interesting than a list of defaults.

__init__()[source]
classmethod register_default(name, plugin_cls, preset='default')[source]
classmethod register_preset(name, preset)[source]

Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to automatically register themselves with a preset by using a classmethod of their own with only the name of the preset to register with.

property plugin_preset

Get the current active plugin preset

property has_plugin_preset: bool

Check whether or not there is a plugin preset in use on this hub right now

use_plugin_preset(preset)[source]

Apply a preset to the hub. If there was a previously active preset, discard it.

Preset can be either the string name of a preset or a PluginPreset instance.

discard_plugin_preset()[source]

Discard the current active preset. Will release any active plugins that could have come from the old preset.

get_plugin(name)[source]

Get the plugin named name. If no such plugin is currently active, try to activate a new one using the current preset.

Return type:

TypeVar(P)

Parameters:

name (str)

has_plugin(name)[source]

Return whether or not a plugin with the name name is currently active.

register_plugin(name, plugin)[source]

Add a new plugin plugin with name name to the active plugins.

Parameters:

name (str)

release_plugin(name)[source]

Deactivate and remove the plugin with name name.

class angr.misc.plugins.PluginPreset[source]

Bases: object

A plugin preset object contains a mapping from name to a plugin class. A preset can be active on a hub, which will cause it to handle requests for plugins which are not already present on the hub.

Unlike Plugins and PluginHubs, instances of PluginPresets are defined on the module level for individual presets. You should register the preset instance with a hub to allow plugins to easily add themselves to the preset without an explicit reference to the preset itself.

__init__()[source]
activate(hub)[source]

This method is called when the preset becomes active on a hub.

deactivate(hub)[source]

This method is called when the preset is discarded from the hub.

add_default_plugin(name, plugin_cls)[source]

Add a plugin to the preset.

list_default_plugins()[source]

Return a list of the names of available default plugins.

request_plugin(name)[source]

Return the plugin class which is registered under the name name, or raise NoPlugin if the name isn’t available.

Return type:

type[TypeVar(P)]

Parameters:

name (str)

copy()[source]

Return a copy of self.

class angr.misc.plugins.PluginVendor[source]

Bases: Generic[P], PluginHub[P]

A specialized hub which serves only as a plugin vendor, never having any “active” plugins. It will directly return the plugins provided by the preset instead of instantiating them.

release_plugin(name)[source]

Deactivate and remove the plugin with name name.

register_plugin(name, plugin)[source]

Add a new plugin plugin with name name to the active plugins.

class angr.misc.plugins.VendorPreset[source]

Bases: PluginPreset

A specialized preset class for use with the PluginVendor.

Program State

angr.sim_state.arch_overridable(f)[source]
class angr.sim_state.SimState(project=None, arch=None, plugins=None, mode=None, options=None, add_options=None, remove_options=None, special_memory_filler=None, os_name=None, plugin_preset='default', cle_memory_backer=None, dict_memory_backer=None, permissions_map=None, default_permissions=3, stack_perms=None, stack_end=None, stack_size=None, regioned_memory_cls=None, **kwargs)[source]

Bases: PluginHub

The SimState represents the state of a program, including its memory, registers, and so forth.

Parameters:
Variables:
  • regs – A convenient view of the state’s registers, where each register is a property

  • mem – A convenient view of the state’s memory, a angr.state_plugins.view.SimMemView

  • registers – The state’s register file as a flat memory region

  • memory – The state’s memory as a flat memory region

  • solver – The symbolic solver and variable manager for this state

  • inspect – The breakpoint manager, a angr.state_plugins.inspect.SimInspector

  • log – Information about the state’s history

  • scratch – Information about the current execution step

  • posix – MISNOMER: information about the operating system or environment model

  • fs – The current state of the simulated filesystem

  • libc – Information about the standard library we are emulating

  • cgc – Information about the cgc environment

  • uc_manager – Control of under-constrained symbolic execution

  • unicorn – Control of the Unicorn Engine

solver: SimSolver
posix: SimSystemPosix
registers: DefaultMemory
regs: SimRegNameView
memory: DefaultMemory
callstack: CallStack
mem: SimMemView
history: SimStateHistory
inspect: SimInspector
jni_references: SimStateJNIReferences
scratch: SimStateScratch
__init__(project=None, arch=None, plugins=None, mode=None, options=None, add_options=None, remove_options=None, special_memory_filler=None, os_name=None, plugin_preset='default', cle_memory_backer=None, dict_memory_backer=None, permissions_map=None, default_permissions=3, stack_perms=None, stack_end=None, stack_size=None, regioned_memory_cls=None, **kwargs)[source]
property plugins
property se

Deprecated alias for solver

property ip

Get the instruction pointer expression, trigger SimInspect breakpoints, and generate SimActions. Use _ip to not trigger breakpoints or generate actions.

Returns:

an expression

property addr

Get the concrete address of the instruction pointer, without triggering SimInspect breakpoints or generating SimActions. An integer is returned, or an exception is raised if the instruction pointer is symbolic.

Returns:

an int

property arch: Arch
T = ~T
get_plugin(name)[source]

Get the plugin named name. If no such plugin is currently active, try to activate a new one using the current preset.

has_plugin(name)[source]

Return whether or not a plugin with the name name is currently active.

register_plugin(name, plugin, inhibit_init=False)[source]

Add a new plugin plugin with name name to the active plugins.

property javavm_memory

In case of an JavaVM with JNI support, a state can store the memory plugin twice; one for the native and one for the java view of the state.

Returns:

The JavaVM view of the memory plugin.

property javavm_registers

In case of an JavaVM with JNI support, a state can store the registers plugin twice; one for the native and one for the java view of the state.

Returns:

The JavaVM view of the registers plugin.

simplify(*args)[source]

Simplify this state’s constraints.

add_constraints(*constraints)[source]

Add some constraints to the state.

You may pass in any number of symbolic booleans as variadic positional arguments.

satisfiable(**kwargs)[source]

Whether the state’s constraints are satisfiable

downsize()[source]

Clean up after the solver engine. Calling this when a state no longer needs to be solved on will reduce memory usage.

step(**kwargs)[source]

Perform a step of symbolic execution using this state. Any arguments to AngrObjectFactory.successors can be passed to this.

Returns:

A SimSuccessors object categorizing the results of the step.

block(*args, **kwargs)[source]

Represent the basic block at this state’s instruction pointer. Any arguments to AngrObjectFactory.block can ba passed to this.

Returns:

A Block object describing the basic block of code at this point.

copy()[source]

Returns a copy of the state.

merge(*others, **kwargs)[source]

Merges this state with the other states. Returns the merging result, merged state, and the merge flag.

Parameters:
  • states – the states to merge

  • merge_conditions – a tuple of the conditions under which each state holds

  • common_ancestor – a state that represents the common history between the states being merged. Usually it is only available when EFFICIENT_STATE_MERGING is enabled, otherwise weak-refed states might be dropped from state history instances.

  • plugin_whitelist – a list of plugin names that will be merged. If this option is given and is not None, any plugin that is not inside this list will not be merged, and will be created as a fresh instance in the new state.

  • common_ancestor_history – a SimStateHistory instance that represents the common history between the states being merged. This is to allow optimal state merging when EFFICIENT_STATE_MERGING is disabled.

Returns:

(merged state, merge flag, a bool indicating if any merging occurred)

widen(*others)[source]

Perform a widening between self and other states :type others: :param others: :return:

reg_concrete(*args, **kwargs)[source]

Returns the contents of a register but, if that register is symbolic, raises a SimValueError.

mem_concrete(*args, **kwargs)[source]

Returns the contents of a memory but, if the contents are symbolic, raises a SimValueError.

stack_push(thing)[source]

Push ‘thing’ to the stack, writing the thing to memory and adjusting the stack pointer.

stack_pop()[source]

Pops from the stack and returns the popped thing. The length will be the architecture word size.

stack_read(offset, length, bp=False)[source]

Reads length bytes, at an offset into the stack.

Parameters:
  • offset – The offset from the stack pointer.

  • length – The number of bytes to read.

  • bp – If True, offset from the BP instead of the SP. Default: False.

make_concrete_int(expr)[source]
prepare_callsite(retval, args, cc='wtf')[source]
dbg_print_stack(depth=None, sp=None)[source]

Only used for debugging purposes. Return the current stack info in formatted string. If depth is None, the current stack frame (from sp to bp) will be printed out.

set_mode(mode)[source]
property thumb
property with_condition
class angr.sim_state_options.StateOption(name, types, default='_NO_DEFAULT_VALUE', description=None)[source]

Bases: object

Describes a state option.

__init__(name, types, default='_NO_DEFAULT_VALUE', description=None)[source]
name
types
default
description
property has_default_value
one_type()[source]
class angr.sim_state_options.SimStateOptions(thing)[source]

Bases: object

A per-state manager of state options. An option can be either a key-valued entry or a Boolean switch (which can be seen as a key-valued entry whose value can only be either True or False).

OPTIONS = {'ABSTRACT_MEMORY': <O ABSTRACT_MEMORY[bool]>, 'ABSTRACT_SOLVER': <O ABSTRACT_SOLVER[bool]>, 'ACTION_DEPS': <O ACTION_DEPS[bool]>, 'ADD_AUTO_REFS': <O ADD_AUTO_REFS[bool]>, 'ALLOW_SEND_FAILURES': <O ALLOW_SEND_FAILURES[bool]>, 'ALL_FILES_EXIST': <O ALL_FILES_EXIST[bool]>, 'ANY_FILE_MIGHT_EXIST': <O ANY_FILE_MIGHT_EXIST[bool]>, 'APPROXIMATE_FIRST': <O APPROXIMATE_FIRST[bool]>, 'APPROXIMATE_GUARDS': <O APPROXIMATE_GUARDS[bool]>, 'APPROXIMATE_MEMORY_INDICES': <O APPROXIMATE_MEMORY_INDICES[bool]>, 'APPROXIMATE_MEMORY_SIZES': <O APPROXIMATE_MEMORY_SIZES[bool]>, 'APPROXIMATE_SATISFIABILITY': <O APPROXIMATE_SATISFIABILITY[bool]>, 'AST_DEPS': <O AST_DEPS[bool]>, 'AUTO_REFS': <O AUTO_REFS[bool]>, 'AVOID_MULTIVALUED_READS': <O AVOID_MULTIVALUED_READS[bool]>, 'AVOID_MULTIVALUED_WRITES': <O AVOID_MULTIVALUED_WRITES[bool]>, 'BEST_EFFORT_MEMORY_STORING': <O BEST_EFFORT_MEMORY_STORING[bool]>, 'BYPASS_ERRORED_IRCCALL': <O BYPASS_ERRORED_IRCCALL[bool]>, 'BYPASS_ERRORED_IROP': <O BYPASS_ERRORED_IROP[bool]>, 'BYPASS_ERRORED_IRSTMT': <O BYPASS_ERRORED_IRSTMT[bool]>, 'BYPASS_UNSUPPORTED_IRCCALL': <O BYPASS_UNSUPPORTED_IRCCALL[bool]>, 'BYPASS_UNSUPPORTED_IRDIRTY': <O BYPASS_UNSUPPORTED_IRDIRTY[bool]>, 'BYPASS_UNSUPPORTED_IREXPR': <O BYPASS_UNSUPPORTED_IREXPR[bool]>, 'BYPASS_UNSUPPORTED_IROP': <O BYPASS_UNSUPPORTED_IROP[bool]>, 'BYPASS_UNSUPPORTED_IRSTMT': <O BYPASS_UNSUPPORTED_IRSTMT[bool]>, 'BYPASS_UNSUPPORTED_SYSCALL': <O BYPASS_UNSUPPORTED_SYSCALL[bool]>, 'BYPASS_VERITESTING_EXCEPTIONS': <O BYPASS_VERITESTING_EXCEPTIONS[bool]>, 'CACHELESS_SOLVER': <O CACHELESS_SOLVER[bool]>, 'CALLLESS': <O CALLLESS[bool]>, 'CGC_ENFORCE_FD': <O CGC_ENFORCE_FD[bool]>, 'CGC_NON_BLOCKING_FDS': <O CGC_NON_BLOCKING_FDS[bool]>, 'CGC_NO_SYMBOLIC_RECEIVE_LENGTH': <O CGC_NO_SYMBOLIC_RECEIVE_LENGTH[bool]>, 'COMPOSITE_SOLVER': <O COMPOSITE_SOLVER[bool]>, 'CONCRETIZE': <O CONCRETIZE[bool]>, 'CONCRETIZE_SYMBOLIC_FILE_READ_SIZES': <O CONCRETIZE_SYMBOLIC_FILE_READ_SIZES[bool]>, 'CONCRETIZE_SYMBOLIC_WRITE_SIZES': <O CONCRETIZE_SYMBOLIC_WRITE_SIZES[bool]>, 'CONSERVATIVE_READ_STRATEGY': <O CONSERVATIVE_READ_STRATEGY[bool]>, 'CONSERVATIVE_WRITE_STRATEGY': <O CONSERVATIVE_WRITE_STRATEGY[bool]>, 'CONSTRAINT_TRACKING_IN_SOLVER': <O CONSTRAINT_TRACKING_IN_SOLVER[bool]>, 'COPY_STATES': <O COPY_STATES[bool]>, 'CPUID_SYMBOLIC': <O CPUID_SYMBOLIC[bool]>, 'DOWNSIZE_Z3': <O DOWNSIZE_Z3[bool]>, 'DO_CCALLS': <O DO_CCALLS[bool]>, 'DO_RET_EMULATION': <O DO_RET_EMULATION[bool]>, 'EFFICIENT_STATE_MERGING': <O EFFICIENT_STATE_MERGING[bool]>, 'ENABLE_NX': <O ENABLE_NX[bool]>, 'EXCEPTION_HANDLING': <O EXCEPTION_HANDLING[bool]>, 'EXTENDED_IROP_SUPPORT': <O EXTENDED_IROP_SUPPORT[bool]>, 'FAST_MEMORY': <O FAST_MEMORY[bool]>, 'FAST_REGISTERS': <O FAST_REGISTERS[bool]>, 'FILES_HAVE_EOF': <O FILES_HAVE_EOF[bool]>, 'HYBRID_SOLVER': <O HYBRID_SOLVER[bool]>, 'JAVA_IDENTIFY_GETTER_SETTER': <O JAVA_IDENTIFY_GETTER_SETTER[bool]>, 'JAVA_TRACK_ATTRIBUTES': <O JAVA_TRACK_ATTRIBUTES[bool]>, 'KEEP_IP_SYMBOLIC': <O KEEP_IP_SYMBOLIC[bool]>, 'LAZY_SOLVES': <O LAZY_SOLVES[bool]>, 'MEMORY_CHUNK_INDIVIDUAL_READS': <O MEMORY_CHUNK_INDIVIDUAL_READS[bool]>, 'MEMORY_FIND_STRICT_SIZE_LIMIT': <O MEMORY_FIND_STRICT_SIZE_LIMIT[bool]>, 'MEMORY_SYMBOLIC_BYTES_MAP': <O MEMORY_SYMBOLIC_BYTES_MAP[bool]>, 'NO_CROSS_INSN_OPT': <O NO_CROSS_INSN_OPT[bool]>, 'NO_IP_CONCRETIZATION': <O NO_IP_CONCRETIZATION[bool]>, 'NO_SYMBOLIC_JUMP_RESOLUTION': <O NO_SYMBOLIC_JUMP_RESOLUTION[bool]>, 'NO_SYMBOLIC_SYSCALL_RESOLUTION': <O NO_SYMBOLIC_SYSCALL_RESOLUTION[bool]>, 'OPTIMIZE_IR': <O OPTIMIZE_IR[bool]>, 'PRODUCE_ZERODIV_SUCCESSORS': <O PRODUCE_ZERODIV_SUCCESSORS[bool]>, 'REGION_MAPPING': <O REGION_MAPPING[bool]>, 'REPLACEMENT_SOLVER': <O REPLACEMENT_SOLVER[bool]>, 'REVERSE_MEMORY_HASH_MAP': <O REVERSE_MEMORY_HASH_MAP[bool]>, 'REVERSE_MEMORY_NAME_MAP': <O REVERSE_MEMORY_NAME_MAP[bool]>, 'SHORT_READS': <O SHORT_READS[bool]>, 'SIMPLIFY_CONSTRAINTS': <O SIMPLIFY_CONSTRAINTS[bool]>, 'SIMPLIFY_EXIT_GUARD': <O SIMPLIFY_EXIT_GUARD[bool]>, 'SIMPLIFY_EXIT_STATE': <O SIMPLIFY_EXIT_STATE[bool]>, 'SIMPLIFY_EXIT_TARGET': <O SIMPLIFY_EXIT_TARGET[bool]>, 'SIMPLIFY_EXPRS': <O SIMPLIFY_EXPRS[bool]>, 'SIMPLIFY_MEMORY_READS': <O SIMPLIFY_MEMORY_READS[bool]>, 'SIMPLIFY_MEMORY_WRITES': <O SIMPLIFY_MEMORY_WRITES[bool]>, 'SIMPLIFY_MERGED_CONSTRAINTS': <O SIMPLIFY_MERGED_CONSTRAINTS[bool]>, 'SIMPLIFY_REGISTER_READS': <O SIMPLIFY_REGISTER_READS[bool]>, 'SIMPLIFY_REGISTER_WRITES': <O SIMPLIFY_REGISTER_WRITES[bool]>, 'SIMPLIFY_RETS': <O SIMPLIFY_RETS[bool]>, 'SPECIAL_MEMORY_FILL': <O SPECIAL_MEMORY_FILL[bool]>, 'STRICT_PAGE_ACCESS': <O STRICT_PAGE_ACCESS[bool]>, 'SUPER_FASTPATH': <O SUPER_FASTPATH[bool]>, 'SUPPORT_FLOATING_POINT': <O SUPPORT_FLOATING_POINT[bool]>, 'SYMBION_KEEP_STUBS_ON_SYNC': <O SYMBION_KEEP_STUBS_ON_SYNC[bool]>, 'SYMBION_SYNC_CLE': <O SYMBION_SYNC_CLE[bool]>, 'SYMBOLIC': <O SYMBOLIC[bool]>, 'SYMBOLIC_INITIAL_VALUES': <O SYMBOLIC_INITIAL_VALUES[bool]>, 'SYMBOLIC_MEMORY_NO_SINGLEVALUE_OPTIMIZATIONS': <O SYMBOLIC_MEMORY_NO_SINGLEVALUE_OPTIMIZATIONS[bool]>, 'SYMBOLIC_TEMPS': <O SYMBOLIC_TEMPS[bool]>, 'SYMBOLIC_WRITE_ADDRESSES': <O SYMBOLIC_WRITE_ADDRESSES[bool]>, 'SYMBOL_FILL_UNCONSTRAINED_MEMORY': <O SYMBOL_FILL_UNCONSTRAINED_MEMORY[bool]>, 'SYMBOL_FILL_UNCONSTRAINED_REGISTERS': <O SYMBOL_FILL_UNCONSTRAINED_REGISTERS[bool]>, 'SYNC_CLE_BACKEND_CONCRETE': <O SYNC_CLE_BACKEND_CONCRETE[bool]>, 'TRACK_ACTION_HISTORY': <O TRACK_ACTION_HISTORY[bool]>, 'TRACK_CONSTRAINTS': <O TRACK_CONSTRAINTS[bool]>, 'TRACK_CONSTRAINT_ACTIONS': <O TRACK_CONSTRAINT_ACTIONS[bool]>, 'TRACK_JMP_ACTIONS': <O TRACK_JMP_ACTIONS[bool]>, 'TRACK_MEMORY_ACTIONS': <O TRACK_MEMORY_ACTIONS[bool]>, 'TRACK_MEMORY_MAPPING': <O TRACK_MEMORY_MAPPING[bool]>, 'TRACK_OP_ACTIONS': <O TRACK_OP_ACTIONS[bool]>, 'TRACK_REGISTER_ACTIONS': <O TRACK_REGISTER_ACTIONS[bool]>, 'TRACK_SOLVER_VARIABLES': <O TRACK_SOLVER_VARIABLES[bool]>, 'TRACK_TMP_ACTIONS': <O TRACK_TMP_ACTIONS[bool]>, 'TRUE_RET_EMULATION_GUARD': <O TRUE_RET_EMULATION_GUARD[bool]>, 'UNDER_CONSTRAINED_SYMEXEC': <O UNDER_CONSTRAINED_SYMEXEC[bool]>, 'UNICORN': <O UNICORN[bool]>, 'UNICORN_AGGRESSIVE_CONCRETIZATION': <O UNICORN_AGGRESSIVE_CONCRETIZATION[bool]>, 'UNICORN_HANDLE_CGC_RANDOM_SYSCALL': <O UNICORN_HANDLE_CGC_RANDOM_SYSCALL[bool]>, 'UNICORN_HANDLE_CGC_RECEIVE_SYSCALL': <O UNICORN_HANDLE_CGC_RECEIVE_SYSCALL[bool]>, 'UNICORN_HANDLE_CGC_TRANSMIT_SYSCALL': <O UNICORN_HANDLE_CGC_TRANSMIT_SYSCALL[bool]>, 'UNICORN_HANDLE_SYMBOLIC_ADDRESSES': <O UNICORN_HANDLE_SYMBOLIC_ADDRESSES[bool]>, 'UNICORN_HANDLE_SYMBOLIC_CONDITIONS': <O UNICORN_HANDLE_SYMBOLIC_CONDITIONS[bool]>, 'UNICORN_HANDLE_SYMBOLIC_SYSCALLS': <O UNICORN_HANDLE_SYMBOLIC_SYSCALLS[bool]>, 'UNICORN_SYM_REGS_SUPPORT': <O UNICORN_SYM_REGS_SUPPORT[bool]>, 'UNICORN_THRESHOLD_CONCRETIZATION': <O UNICORN_THRESHOLD_CONCRETIZATION[bool]>, 'UNICORN_TRACK_BBL_ADDRS': <O UNICORN_TRACK_BBL_ADDRS[bool]>, 'UNICORN_TRACK_STACK_POINTERS': <O UNICORN_TRACK_STACK_POINTERS[bool]>, 'UNICORN_ZEROPAGE_GUARD': <O UNICORN_ZEROPAGE_GUARD[bool]>, 'UNINITIALIZED_ACCESS_AWARENESS': <O UNINITIALIZED_ACCESS_AWARENESS[bool]>, 'UNSUPPORTED_BYPASS_ZERO_DEFAULT': <O UNSUPPORTED_BYPASS_ZERO_DEFAULT[bool]>, 'UNSUPPORTED_FORCE_CONCRETIZE': <O UNSUPPORTED_FORCE_CONCRETIZE[bool]>, 'USE_SIMPLIFIED_CCALLS': <O USE_SIMPLIFIED_CCALLS[bool]>, 'USE_SYSTEM_TIMES': <O USE_SYSTEM_TIMES[bool]>, 'VALIDATE_APPROXIMATIONS': <O VALIDATE_APPROXIMATIONS[bool]>, 'ZERO_FILL_UNCONSTRAINED_MEMORY': <O ZERO_FILL_UNCONSTRAINED_MEMORY[bool]>, 'ZERO_FILL_UNCONSTRAINED_REGISTERS': <O ZERO_FILL_UNCONSTRAINED_REGISTERS[bool]>, 'jumptable_symbolic_ip_max_targets': <O jumptable_symbolic_ip_max_targets[int]: The maximum number of concrete addresses a symbolic instruction pointer can be concretized to if it is part of a jump table.>, 'symbolic_ip_max_targets': <O symbolic_ip_max_targets[int]: The maximum number of concrete addresses a symbolic instruction pointer can be concretized to.>}
__init__(thing)[source]
Parameters:

thing – Either a set of Boolean switches to enable, or an existing SimStateOptions instance.

add(boolean_switch)[source]

[COMPATIBILITY] Enable a Boolean switch.

Parameters:

boolean_switch (str) – Name of the Boolean switch.

Returns:

None

update(boolean_switches)[source]

[COMPATIBILITY] In order to be compatible with the old interface, you can enable a collection of Boolean switches at the same time by doing the following:

>>> state.options.update({sim_options.SYMBOLIC, sim_options.ABSTRACT_MEMORY})

or

>>> state.options.update(sim_options.unicorn)
Parameters:

boolean_switches (set) – A collection of Boolean switches to enable.

Returns:

None

remove(name)[source]

Drop a state option if it exists, or raise a KeyError if the state option is not set.

[COMPATIBILITY] Remove a Boolean switch.

Parameters:

name (str) – Name of the state option.

Returns:

NNone

discard(name)[source]

Drop a state option if it exists, or silently return if the state option is not set.

[COMPATIBILITY] Disable a Boolean switch.

Parameters:

name (str) – Name of the Boolean switch.

Returns:

None

difference(boolean_switches)[source]

[COMPATIBILITY] Make a copy of the current instance, and then discard all options that are in boolean_switches.

Parameters:

boolean_switches (set) – A collection of Boolean switches to disable.

Returns:

A new SimStateOptions instance.

copy()[source]

Get a copy of the current SimStateOptions instance.

Returns:

A new SimStateOptions instance.

Return type:

SimStateOptions

tally(exclude_false=True, description=False)[source]

Return a string representation of all state options.

Parameters:
  • exclude_false (bool) – Whether to exclude Boolean switches that are disabled.

  • description (bool) – Whether to display the description of each option.

Returns:

A string representation.

Return type:

str

classmethod register_option(name, types, default=None, description=None)[source]

Register a state option.

Parameters:
  • name (str) – Name of the state option.

  • types – A collection of allowed types of this state option.

  • default – The default value of this state option.

  • description (str) – The description of this state option.

Returns:

None

classmethod register_bool_option(name, description=None)[source]

Register a Boolean switch as state option. This is equivalent to cls.register_option(name, set([bool]), description=description)

Parameters:
  • name (str) – Name of the state option.

  • description (str) – The description of this state option.

Returns:

None

class angr.state_plugins.SimStatePlugin[source]

Bases: object

This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They are intended to be used for things such as tracking open files, tracking heap details, and providing storage and persistence for SimProcedures.

STRONGREF_STATE = False
__init__()[source]
state: SimState
set_state(state)[source]

Sets a new state (for example, if the state has been branched)

set_strongref_state(state)[source]
copy(_memo)[source]

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

static memo(f)[source]

A decorator function you should apply to copy

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

classmethod register_default(name, xtr=None)[source]
init_state()[source]

Use this function to perform any initialization on the state at plugin-add time

class angr.state_plugins.SimStateLibc[source]

Bases: SimStatePlugin

This state plugin keeps track of various libc stuff:

LOCALE_ARRAY = [b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x03 ', b'\x02 ', b'\x02 ', b'\x02 ', b'\x02 ', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x02\x00', b'\x01`', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x08\xd8', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x08\xd5', b'\x08\xd5', b'\x08\xd5', b'\x08\xd5', b'\x08\xd5', b'\x08\xd5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x08\xc5', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x08\xd6', b'\x08\xd6', b'\x08\xd6', b'\x08\xd6', b'\x08\xd6', b'\x08\xd6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x08\xc6', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x04\xc0', b'\x02\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00', b'\x00\x00']
TOLOWER_LOC_ARRAY = [128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 4294967295, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255]
TOUPPER_LOC_ARRAY = [128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 4294967295, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255]
__init__()[source]
copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

property errno
ret_errno(val)[source]
class angr.state_plugins.SimInspector[source]

Bases: SimStatePlugin

The breakpoint interface, used to instrument execution. For usage information, look here: https://docs.angr.io/core-concepts/simulation#breakpoints

BP_AFTER = 'after'
BP_BEFORE = 'before'
BP_BOTH = 'both'
__init__()[source]
action(event_type, when, **kwargs)[source]

Called from within the engine when events happens. This function checks all breakpoints registered for that event and fires the ones whose conditions match.

make_breakpoint(event_type, *args, **kwargs)[source]

Creates and adds a breakpoint which would trigger on event_type. Additional arguments are passed to the BP constructor.

Returns:

The created breakpoint, so that it can be removed later.

b(event_type, *args, **kwargs)

Creates and adds a breakpoint which would trigger on event_type. Additional arguments are passed to the BP constructor.

Returns:

The created breakpoint, so that it can be removed later.

add_breakpoint(event_type, bp)[source]

Adds a breakpoint which would trigger on event_type.

Parameters:
  • event_type – The event type to trigger on

  • bp – The breakpoint

Returns:

The created breakpoint.

remove_breakpoint(event_type, bp=None, filter_func=None)[source]

Removes a breakpoint.

Parameters:
  • bp – The breakpoint to remove.

  • filter_func – A filter function to specify whether each breakpoint should be removed or not.

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

downsize()[source]

Remove previously stored attributes from this plugin instance to save memory. This method is supposed to be called by breakpoint implementors. A typical workflow looks like the following :

>>> # Add `attr0` and `attr1` to `self.state.inspect`
>>> self.state.inspect(xxxxxx, attr0=yyyy, attr1=zzzz)
>>> # Get new attributes out of SimInspect in case they are modified by the user
>>> new_attr0 = self.state._inspect.attr0
>>> new_attr1 = self.state._inspect.attr1
>>> # Remove them from SimInspect
>>> self.state._inspect.downsize()
merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

set_state(state)[source]

Sets a new state (for example, if the state has been branched)

class angr.state_plugins.PosixDevFS[source]

Bases: SimMount

get(path)[source]

Implement this function to instrument file lookups.

Parameters:

path_elements – A list of path elements traversing from the mountpoint to the file

Returns:

A SimFile, or None

insert(path, simfile)[source]

Implement this function to instrument file creation.

Parameters:
  • path_elements – A list of path elements traversing from the mountpoint to the file

  • simfile – The file to insert

Returns:

A bool indicating whether the insert occurred

delete(path)[source]

Implement this function to instrument file deletion.

Parameters:

path_elements – A list of path elements traversing from the mountpoint to the file

Returns:

A bool indicating whether the delete occurred

lookup(_)[source]

Look up the path of a SimFile in the mountpoint

Parameters:

sim_file – A SimFile object needs to be looked up

Returns:

A string representing the path of the file in the mountpoint Or None if the SimFile does not exist in the mountpoint

merge(others, conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

copy(_)[source]

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

class angr.state_plugins.PosixProcFS[source]

Bases: SimMount

The virtual file system mounted at /proc (as of now, on Linux).

get(path)[source]

Implement this function to instrument file lookups.

Parameters:

path_elements – A list of path elements traversing from the mountpoint to the file

Returns:

A SimFile, or None

insert(path, simfile)[source]

Implement this function to instrument file creation.

Parameters:
  • path_elements – A list of path elements traversing from the mountpoint to the file

  • simfile – The file to insert

Returns:

A bool indicating whether the insert occurred

delete(path)[source]

Implement this function to instrument file deletion.

Parameters:

path_elements – A list of path elements traversing from the mountpoint to the file

Returns:

A bool indicating whether the delete occurred

lookup(_)[source]

Look up the path of a SimFile in the mountpoint

Parameters:

sim_file – A SimFile object needs to be looked up

Returns:

A string representing the path of the file in the mountpoint Or None if the SimFile does not exist in the mountpoint

merge(others, conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

copy(_)[source]

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

class angr.state_plugins.SimSystemPosix(stdin=None, stdout=None, stderr=None, fd=None, sockets=None, socket_queue=None, argv=None, argc=None, environ=None, auxv=None, tls_modules=None, sigmask=None, pid=None, ppid=None, uid=None, gid=None, brk=None)[source]

Bases: SimStatePlugin

Data storage and interaction mechanisms for states with an environment conforming to posix. Available as state.posix.

SIG_BLOCK = 0
SIG_UNBLOCK = 1
SIG_SETMASK = 2
EPERM = 1
ENOENT = 2
ESRCH = 3
EINTR = 4
EIO = 5
ENXIO = 6
E2BIG = 7
ENOEXEC = 8
EBADF = 9
ECHILD = 10
EAGAIN = 11
ENOMEM = 12
EACCES = 13
EFAULT = 14
ENOTBLK = 15
EBUSY = 16
EEXIST = 17
EXDEV = 18
ENODEV = 19
ENOTDIR = 20
EISDIR = 21
EINVAL = 22
ENFILE = 23
EMFILE = 24
ENOTTY = 25
ETXTBSY = 26
EFBIG = 27
ENOSPC = 28
ESPIPE = 29
EROFS = 30
EPIPE = 32
EDOM = 33
ERANGE = 34
__init__(stdin=None, stdout=None, stderr=None, fd=None, sockets=None, socket_queue=None, argv=None, argc=None, environ=None, auxv=None, tls_modules=None, sigmask=None, pid=None, ppid=None, uid=None, gid=None, brk=None)[source]
copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

property closed_fds
init_state()[source]

Use this function to perform any initialization on the state at plugin-add time

set_brk(new_brk)[source]
set_state(state)[source]

Sets a new state (for example, if the state has been branched)

open(name, flags, preferred_fd=None)[source]

Open a symbolic file. Basically open(2).

Parameters:
  • name (string or bytes) – Path of the symbolic file, as a string or bytes.

  • flags – File operation flags, a bitfield of constants from open(2), as an AST

  • preferred_fd – Assign this fd if it’s not already claimed.

Returns:

The file descriptor number allocated (maps through posix.get_fd to a SimFileDescriptor) or -1 if the open fails.

mode from open(2) is unsupported at present.

open_socket(ident)[source]
get_fd(fd, create_file=True)[source]

Looks up the SimFileDescriptor associated with the given number (an AST). If the number is concrete and does not map to anything, return None. If the number is symbolic, constrain it to an open fd and create a new file for it. Set create_file to False if no write-access is planned (i.e. fd is read-only).

get_concrete_fd(fd, create_file=True)[source]

Same behavior as get_fd(fd), only the result is a concrete integer fd (or -1) instead of a SimFileDescriptor.

close(fd)[source]

Closes the given file descriptor (an AST). Returns whether the operation succeeded (a concrete boolean)

fstat(fd)[source]
fstat_with_result(sim_fd)[source]
sigmask(sigsetsize=None)[source]

Gets the current sigmask. If it’s blank, a new one is created (of sigsetsize).

Parameters:

sigsetsize – the size (in bytes of the sigmask set)

Returns:

the sigmask

sigprocmask(how, new_mask, sigsetsize, valid_ptr=True)[source]

Updates the signal mask.

Parameters:
  • how – the “how” argument of sigprocmask (see manpage)

  • new_mask – the mask modification to apply

  • sigsetsize – the size (in bytes of the sigmask set)

  • valid_ptr – is set if the new_mask was not NULL

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(_)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

dump_file_by_path(path, **kwargs)[source]

Returns the concrete content for a file by path.

Parameters:
  • path – file path as string

  • kwargs – passed to state.solver.eval

Returns:

file contents as string

dumps(fd, **kwargs)[source]

Returns the concrete content for a file descriptor.

BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout, or stderr as a flat string.

Parameters:

fd – A file descriptor.

Returns:

The concrete content.

Return type:

str

class angr.state_plugins.SimSolver(solver=None, all_variables=None, temporal_tracked_variables=None, eternal_tracked_variables=None)[source]

Bases: SimStatePlugin

This is the plugin you’ll use to interact with symbolic variables, creating them and evaluating them. It should be available on a state as state.solver.

Any top-level variable of the claripy module can be accessed as a property of this object.

__init__(solver=None, all_variables=None, temporal_tracked_variables=None, eternal_tracked_variables=None)[source]
reload_solver(constraints=None)[source]

Reloads the solver. Useful when changing solver options.

Parameters:

constraints (list) – A new list of constraints to use in the reloaded solver instead of the current one

get_variables(*keys)[source]

Iterate over all variables for which their tracking key is a prefix of the values provided.

Elements are a tuple, the first element is the full tracking key, the second is the symbol.

>>> list(s.solver.get_variables('mem'))
[(('mem', 0x1000), <BV64 mem_1000_4_64>), (('mem', 0x1008), <BV64 mem_1008_5_64>)]
>>> list(s.solver.get_variables('file'))
[(('file', 1, 0), <BV8 file_1_0_6_8>), (('file', 1, 1), <BV8 file_1_1_7_8>),
    (('file', 2, 0), <BV8 file_2_0_8_8>)]
>>> list(s.solver.get_variables('file', 2))
[(('file', 2, 0), <BV8 file_2_0_8_8>)]
>>> list(s.solver.get_variables())
[(('mem', 0x1000), <BV64 mem_1000_4_64>), (('mem', 0x1008), <BV64 mem_1008_5_64>),
    (('file', 1, 0), <BV8 file_1_0_6_8>), (('file', 1, 1), <BV8 file_1_1_7_8>),
    (('file', 2, 0), <BV8 file_2_0_8_8>)]
register_variable(v, key, eternal=True)[source]

Register a value with the variable tracking system

Parameters:
  • v – The BVS to register

  • key – A tuple to register the variable under

Parma eternal:

Whether this is an eternal variable, default True. If False, an incrementing counter will be appended to the key.

describe_variables(v)[source]

Given an AST, iterate over all the keys of all the BVS leaves in the tree which are registered.

Unconstrained(name, bits, uninitialized=True, inspect=True, events=True, key=None, eternal=False, uc_alloc_depth=None, **kwargs)[source]

Creates an unconstrained symbol or a default concrete value (0), based on the state options.

Parameters:
  • name – The name of the symbol.

  • bits – The size (in bits) of the symbol.

  • uninitialized – Whether this value should be counted as an “uninitialized” value in the course of an analysis.

  • inspect – Set to False to avoid firing SimInspect breakpoints

  • events – Set to False to avoid generating a SimEvent for the occasion

  • key – Set this to a tuple of increasingly specific identifiers (for example, ('mem', 0xffbeff00) or ('file', 4, 0x20) to cause it to be tracked, i.e. accessible through solver.get_variables.

  • eternal – Set to True in conjunction with setting a key to cause all states with the same ancestry to retrieve the same symbol when trying to create the value. If False, a counter will be appended to the key.

Returns:

an unconstrained symbol (or a concrete value of 0).

BVS(name, size, min=None, max=None, stride=None, uninitialized=False, explicit_name=None, key=None, eternal=False, inspect=True, events=True, **kwargs)[source]

Creates a bit-vector symbol (i.e., a variable). Other keyword parameters are passed directly on to the constructor of claripy.ast.BV.

Parameters:
  • name – The name of the symbol.

  • size – The size (in bits) of the bit-vector.

  • min – The minimum value of the symbol. Note that this only work when using VSA.

  • max – The maximum value of the symbol. Note that this only work when using VSA.

  • stride – The stride of the symbol. Note that this only work when using VSA.

  • uninitialized – Whether this value should be counted as an “uninitialized” value in the course of an analysis.

  • explicit_name – Set to True to prevent an identifier from appended to the name to ensure uniqueness.

  • key – Set this to a tuple of increasingly specific identifiers (for example, ('mem', 0xffbeff00) or ('file', 4, 0x20) to cause it to be tracked, i.e. accessible through solver.get_variables.

  • eternal – Set to True in conjunction with setting a key to cause all states with the same ancestry to retrieve the same symbol when trying to create the value. If False, a counter will be appended to the key.

  • inspect – Set to False to avoid firing SimInspect breakpoints

  • events – Set to False to avoid generating a SimEvent for the occasion

Returns:

A BV object representing this symbol.

copy(memo=None, **kwargs)

Should return a copy of the plugin without any state attached. Should check the memo first, and add itself to memo if it ends up making a new copy.

In order to simplify using the memo, you should annotate implementations of this function with SimStatePlugin.memo

The base implementation of this function constructs a new instance of the plugin’s class without calling its initializer. If you super-call down to it, make sure you instantiate all the fields in your copy method!

Parameters:

memo – A dictionary mapping object identifiers (id(obj)) to their copied instance. Use this to avoid infinite recursion and diverged copies.

merge(others, merge_conditions, common_ancestor=None)[source]

Should merge the state plugin with the provided others. This will be called by state.merge() after copying the target state, so this should mutate the current instance to merge with the others.

Note that when multiple instances of a single plugin object (for example, a file) are referenced in the state, it is important that merge only ever be called once. This should be solved by designating one of the plugin’s referees as the “real owner”, who should be the one to actually merge it. This technique doesn’t work to resolve the similar issue that arises during copying because merging doesn’t produce a new reference to insert.

There will be n others and n+1 merge conditions, since the first condition corresponds to self. To match elements up to conditions, say zip([self] + others, merge_conditions)

When implementing this, make sure that you “deepen” both others and common_ancestor before calling sub-elements’ merge methods, e.g.

self.foo.merge(
    [o.foo for o in others],
    merge_conditions,
    common_ancestor=common_ancestor.foo if common_ancestor is not None else None
)

During static analysis, merge_conditions can be None, in which case you should use state.solver.union(values). TODO: fish please make this less bullshit

There is a utility claripy.ite_cases which will help with constructing arbitrarily large merged ASTs. Use it like self.bar = claripy.ite_cases(zip(conditions[1:], [o.bar for o in others]), self.bar)

Parameters:
  • others – the other state plugins to merge with

  • merge_conditions – a symbolic condition for each of the plugins

  • common_ancestor – a common ancestor of this plugin and the others being merged

Returns:

True if the state plugins are actually merged.

Return type:

bool

widen(others)[source]

The widening operation for plugins. Widening is a special kind of merging that produces a more general state from several more specific states. It is used only during intensive static analysis. The same behavior regarding copying and mutation from merge should be followed.

Parameters:

others – the other state plugin

Returns:

True if the state plugin is actually widened.

Return type:

bool

downsize()[source]

Frees memory associated with the constraint solver by clearing all of its internal caches.

property constraints

Returns the constraints of the state stored by the solver.

eval_to_ast(e, n, extra_constraints=(), exact=None)[source]

Evaluate an expression, using the solver if necessary. Returns AST objects.

Parameters:
  • e – the expression

  • n – the number of desired solutions

  • extra_constraints – extra constraints to apply to the solver

  • exact – if False, returns approximate solutions

Returns:

a tuple of the solutions, in the form of claripy AST nodes

Return type:

tuple

max(e, extra_constraints=(), exact=None, signed=False)[source]

Return the maximum value of expression e.

:param e : expression (an AST) to evaluate :type extra_constraints: :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve :param exact : if False, return approximate solutions. :param signed : Whether the expression should be treated as a signed value. :return: the maximum possible value of e (backend object)

min(e, extra_constraints=(), exact=None, signed=False)[source]

Return the minimum value of expression e.

:param e : expression (an AST) to evaluate :type extra_constraints: :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve :param exact : if False, return approximate solutions. :param signed : Whether the expression should be treated as a signed value. :return: the minimum possible value of e (backend object)

solution(e, v, extra_constraints=(), exact=None)[source]

Return True if v is a solution of expr with the extra constraints, False otherwise.

Parameters:
  • e – An expression (an AST) to evaluate

  • v – The proposed solution (an AST)

  • extra_constraints – Extra constraints (as ASTs) to add to the solver for this solve.

  • exact – If False, return approximate solutions.

Returns:

True if v is a solution of expr, False otherwise

is_true(e, extra_constraints=(), exact=None)[source]

If the expression provided is absolutely, definitely a true boolean, return True. Note that returning False doesn’t necessarily mean that the expression can be false, just that we couldn’t figure that out easily.

Parameters:
  • e – An expression (an AST) to evaluate

  • extra_constraints – Extra constraints (as ASTs) to add to the solver for this solve.

  • exact – If False, return approximate solutions.

Returns:

True if v is definitely true, False otherwise

is_false(e, extra_constraints=(), exact=None)[source]

If the expression provided is absolutely, definitely a false boolean, return True. Note that returning False doesn’t necessarily mean that the expression can be true, just that we couldn’t figure that out easily.

Parameters:
  • e – An expression (an AST) to evaluate

  • extra_constraints – Extra constraints (as ASTs) to add to the solver for this solve.

  • exact – If False, return approximate solutions.

Returns:

True if v is definitely false, False otherwise

unsat_core(extra_constraints=())[source]

This function returns the unsat core from the backend solver.

Parameters:

extra_constraints – Extra constraints (as ASTs) to add to the solver for this solve.

Returns:

The unsat core.

satisfiable(extra_constraints=(), exact=None)[source]

This function does a constraint check and checks if the solver is in a sat state.

Parameters:
  • extra_constraints – Extra constraints (as ASTs) to add to s for this solve

  • exact – If False, return approximate solutions.

Returns:

True if sat, otherwise false

add(*constraints)[source]

Add some constraints to the solver.

Parameters:

constraints – Pass any constraints that you want to add (ASTs) as varargs.

CastType = ~CastType