API 参考手册

class angr.BP(when='before', enabled=None, condition=None, action=None, **kwargs)[源代码]

基类:object

A breakpoint.

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

Checks state state to see if the breakpoint should fire.

参数:
  • state -- The state.

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

返回:

A boolean representing whether the checkpoint should fire.

fire(state)[源代码]

Trigger the breakpoint.

参数:

state -- The state.

class angr.Analysis[源代码]

基类:object

This class represents an analysis on the program.

变量:
  • 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: list[AnalysisLogEntry] = []
named_errors: defaultdict[str, list[AnalysisLogEntry]] = {}
exception angr.AngrAnalysisError[源代码]

基类:AngrError

exception angr.AngrAnnotatedCFGError[源代码]

基类:AngrError

exception angr.AngrAssemblyError[源代码]

基类:AngrError

exception angr.AngrBackwardSlicingError[源代码]

基类:AngrError

exception angr.AngrBladeError[源代码]

基类:AngrError

exception angr.AngrBladeSimProcError[源代码]

基类:AngrBladeError

exception angr.AngrCFGError[源代码]

基类:AngrError

exception angr.AngrCallableError[源代码]

基类:AngrSurveyorError

exception angr.AngrCallableMultistateError[源代码]

基类:AngrCallableError

exception angr.AngrCorruptDBError[源代码]

基类:AngrDBError

exception angr.AngrDBError[源代码]

基类:AngrError

exception angr.AngrDDGError[源代码]

基类:AngrAnalysisError

exception angr.AngrDataGraphError[源代码]

基类:AngrAnalysisError

exception angr.AngrDecompilationError[源代码]

基类:AngrError

exception angr.AngrDelayJobNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.AngrDirectorError[源代码]

基类:AngrExplorationTechniqueError

exception angr.AngrError[源代码]

基类:Exception

exception angr.AngrExitError[源代码]

基类:AngrError

exception angr.AngrExplorationTechniqueError[源代码]

基类:AngrError

exception angr.AngrExplorerError[源代码]

基类:AngrExplorationTechniqueError

exception angr.AngrForwardAnalysisError[源代码]

基类:AngrError

exception angr.AngrIncompatibleDBError[源代码]

基类:AngrDBError

exception angr.AngrIncongruencyError[源代码]

基类:AngrAnalysisError

exception angr.AngrInvalidArgumentError[源代码]

基类:AngrError

exception angr.AngrJobMergingFailureNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.AngrJobWideningFailureNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.AngrLifterError[源代码]

基类:AngrError

exception angr.AngrLoopAnalysisError[源代码]

基类:AngrAnalysisError

exception angr.AngrMissingTypeError[源代码]

基类:AngrTypeError

exception angr.AngrNoPluginError[源代码]

基类:AngrError

exception angr.AngrPathError[源代码]

基类:AngrError

exception angr.AngrRuntimeError[源代码]

基类:RuntimeError

exception angr.AngrSimOSError[源代码]

基类:AngrError

exception angr.AngrSkipJobNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.AngrSurveyorError[源代码]

基类:AngrError

exception angr.AngrSyscallError[源代码]

基类:AngrError

exception angr.AngrTracerError[源代码]

基类:AngrExplorationTechniqueError

exception angr.AngrTypeError[源代码]

基类:AngrError, TypeError

exception angr.AngrUnsupportedSyscallError[源代码]

基类:AngrSyscallError, SimProcedureError, SimUnsupportedError

exception angr.AngrVFGError[源代码]

基类:AngrError

exception angr.AngrVFGRestartAnalysisNotice[源代码]

基类:AngrVFGError

exception angr.AngrValueError[源代码]

基类:AngrError, ValueError

exception angr.AngrVaultError[源代码]

基类:AngrError

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)[源代码]

基类: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.

参数:
  • 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)[源代码]
参数:
  • 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)

返回:

None

property slice
dbg_repr(arch=None)[源代码]
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)[源代码]

基类: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)[源代码]
arch
thumb
addr
size
pp(**kwargs)[源代码]
set_initial_regs()[源代码]
static reset_initial_regs()[源代码]
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: int
property instruction_addrs
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.ExplorationTechnique[源代码]

基类:object

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

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__()[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
filter(simgr, state, **kwargs)[源代码]

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.

参数:
selector(simgr, state, **kwargs)[源代码]

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.

参数:
step_state(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
complete(simgr)[源代码]

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.

参数:

simgr (angr.SimulationManager)

class angr.KnowledgeBase(project, obj=None, name=None)[源代码]

基类:object

Represents a "model" of knowledge about an artifact.

Contains things like a CFG, data references, etc.

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

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

参数:

requested_plugin_cls (type[K])

返回类型:

K | None

request_knowledge(requested_plugin_cls)[源代码]
返回类型:

K

参数:

requested_plugin_cls (type[K])

class angr.PTChunk(base, sim_state, heap=None)[源代码]

基类: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

变量:
  • 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)[源代码]
get_size()[源代码]

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

get_data_size()[源代码]

Returns the size of the data portion of a chunk.

set_size(size, is_free=None)[源代码]

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.

参数:
  • size -- size of the chunk

  • is_free -- boolean indicating the chunk's freeness

set_prev_freeness(is_free)[源代码]

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

参数:

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

is_prev_free()[源代码]

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.

返回:

True if the previous chunk is free; False otherwise

prev_size()[源代码]

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()[源代码]

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

data_ptr()[源代码]

Returns the address of the payload of the chunk.

next_chunk()[源代码]

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

返回:

The following chunk, or None if applicable

prev_chunk()[源代码]

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.

返回:

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

fwd_chunk()[源代码]

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.

返回:

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

set_fwd_chunk(fwd)[源代码]

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

参数:

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

bck_chunk()[源代码]

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.

返回:

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

set_bck_chunk(bck)[源代码]

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

参数:

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

exception angr.PathUnreachableError[源代码]

基类:AngrPathError

class angr.PointerWrapper(value, buffer=False)[源代码]

基类:object

__init__(value, buffer=False)[源代码]
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)[源代码]

基类: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.

参数:
  • 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.

参数:
  • 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.

变量:
  • 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.

参数:
  • 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)[源代码]
参数:
  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

arch: Arch
property kb
get_kb(name)[源代码]
property analyses: AnalysesHubWithDefault
hook(addr, hook=None, length=0, kwargs=None, replace=False)[源代码]

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!")
参数:
  • 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)[源代码]

Returns True if addr is hooked.

参数:

addr -- An address.

返回类型:

bool

返回:

True if addr is hooked, False otherwise.

hooked_by(addr)[源代码]

Returns the current hook for addr.

参数:

addr -- An address.

返回类型:

SimProcedure | None

返回:

None if the address is not hooked.

unhook(addr)[源代码]

Remove a hook.

参数:

addr -- The address of the hook.

hook_symbol(symbol_name, simproc, kwargs=None, replace=None)[源代码]

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.

参数:
  • 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.

返回:

The address of the new symbol.

返回类型:

int

symbol_hooked_by(symbol_name)[源代码]

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

参数:

symbol_name (str) -- Name of the symbol.

返回类型:

SimProcedure | None

返回:

None if the address is not hooked.

is_symbol_hooked(symbol_name)[源代码]

Check if a symbol is already hooked.

参数:

symbol_name (str) -- Name of the symbol.

返回:

True if the symbol can be resolved and is hooked, False otherwise.

返回类型:

bool

unhook_symbol(symbol_name)[源代码]

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)[源代码]

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)[源代码]

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()[源代码]

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

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)[源代码]

基类:object

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

变量:
  • 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)[源代码]
inc_active_workers()[源代码]
dec_active_workers()[源代码]
stop()[源代码]
property active_workers
property stopped
on_worker_exit(worker_id, stashes)[源代码]
run()[源代码]
exception angr.SimAbstractMemoryError[源代码]

基类:SimMemoryError

exception angr.SimActionError[源代码]

基类:SimError

class angr.SimCC(arch)[源代码]

基类: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.

参数:

arch (archinfo.Arch)

__init__(arch)[源代码]
参数:

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)[源代码]

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)

基类:object

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

both_iter
cc
fp_iter
int_iter
__init__(cc)
getstate()
setstate(state)
arg_session(ret_ty)[源代码]

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.

参数:

ret_ty (SimType | None)

return_in_implicit_outparam(ty)[源代码]
stack_space(args)[源代码]
参数:

args -- A list of SimFunctionArguments

返回:

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)[源代码]

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)[源代码]
参数:
static is_fp_value(val)[源代码]
static guess_prototype(args, prototype=None)[源代码]

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)[源代码]
返回类型:

list[SimFunctionArgument]

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

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

参数:
  • 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)[源代码]

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

参数:
  • 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')[源代码]

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

参数:
  • 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)

返回类型:

SimCC | None

返回:

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

get_arg_info(state, prototype)[源代码]

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

exception angr.SimCCError[源代码]

基类:SimError

exception angr.SimCCallError[源代码]

基类:SimExpressionError

exception angr.SimConcreteBreakpointError[源代码]

基类:AngrError

exception angr.SimConcreteMemoryError[源代码]

基类:AngrError

exception angr.SimConcreteRegisterError[源代码]

基类:AngrError

exception angr.SimEmptyCallStackError[源代码]

基类:SimError

exception angr.SimEngineError[源代码]

基类:SimError

exception angr.SimError[源代码]

基类:Exception

bbl_addr = None
stmt_idx = None
ins_addr = None
executed_instruction_count = None
guard = None
record_state(state)[源代码]
exception angr.SimEventError[源代码]

基类:SimStateError

exception angr.SimException[源代码]

基类:SimError

exception angr.SimExpressionError[源代码]

基类:SimError

exception angr.SimFastMemoryError[源代码]

基类:SimMemoryError

exception angr.SimFastPathError[源代码]

基类:SimEngineError

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

基类: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.

参数:
  • 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.

变量:

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)[源代码]
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)[源代码]

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)[源代码]

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

read(pos, size, **kwargs)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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

基类: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.

变量:
  • 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)[源代码]
static make_ident(name)[源代码]
concretize(**kwargs)[源代码]

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)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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

class angr.SimFileDescriptor(simfile, flags=0)[源代码]

基类: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.

变量:
  • 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)[源代码]
read_data(size, **kwargs)[源代码]

Reads some data from the file, returning the data.

参数:

size -- The requested length of the read

返回:

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

write_data(data, size=None, **kwargs)[源代码]

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

参数:
  • data -- A bitvector to write into the file

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

返回:

The real length of the write

seek(offset, whence='start')[源代码]

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

参数:
  • 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"

返回:

A symbolic boolean describing whether the seek succeeded or not

eof()[源代码]

Return the EOF status. May be a symbolic boolean.

tell()[源代码]

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

size()[源代码]

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)[源代码]

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)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.SimFileDescriptorDuplex(read_file, write_file)[源代码]

基类: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.

参数:
  • read_file -- The SimFile to read from

  • write_file -- The SimFile to write to

__init__(read_file, write_file)[源代码]
read_data(size, **kwargs)[源代码]

Reads some data from the file, returning the data.

参数:

size -- The requested length of the read

返回:

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

write_data(data, size=None, **kwargs)[源代码]

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

参数:
  • data -- A bitvector to write into the file

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

返回:

The real length of the write

set_state(state)[源代码]

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

eof()[源代码]

Return the EOF status. May be a symbolic boolean.

tell()[源代码]

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

seek(offset, whence='start')[源代码]

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

参数:
  • 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"

返回:

A symbolic boolean describing whether the seek succeeded or not

size()[源代码]

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)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

exception angr.SimFileError[源代码]

基类:SimMemoryError, SimFilesystemError

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

基类: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.

参数:
  • 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.

变量:

pos -- The current position in the file.

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

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

read(pos, size, **kwargs)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

exception angr.SimFilesystemError[源代码]

基类:SimError

class angr.SimHeapBrk(heap_base=None, heap_size=None)[源代码]

基类: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).

变量:

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)[源代码]
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!

参数:

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

allocate(sim_size)[源代码]

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.

参数:

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

返回:

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

release(sim_size)[源代码]

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.

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

exception angr.SimHeapError[源代码]

基类:SimStateError

class angr.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]

基类: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.

变量:
  • 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)[源代码]
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!

参数:

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

chunks()[源代码]

Returns an iterator over all the chunks in the heap.

allocated_chunks()[源代码]

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

free_chunks()[源代码]

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

chunk_from_mem(ptr)[源代码]

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.

参数:

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

返回:

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

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

init_state()[源代码]

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

class angr.SimHostFilesystem(host_path=None, **kwargs)[源代码]

基类:SimConcreteFilesystem

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

参数:
  • 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)[源代码]
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!

参数:

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

exception angr.SimIRSBError[源代码]

基类:SimEngineError

exception angr.SimIRSBNoDecodeError[源代码]

基类:SimIRSBError

exception angr.SimMemoryAddressError[源代码]

基类:SimMemoryError

exception angr.SimMemoryError[源代码]

基类:SimStateError

exception angr.SimMemoryLimitError[源代码]

基类:SimMemoryError

exception angr.SimMemoryMissingError(missing_addr, missing_size, *args)[源代码]

基类:SimMemoryError

__init__(missing_addr, missing_size, *args)[源代码]
exception angr.SimMergeError[源代码]

基类:SimStateError

exception angr.SimMissingTempError[源代码]

基类:SimValueError, IndexError

class angr.SimMount[源代码]

基类: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)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path_elements, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path_elements)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(sim_file)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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

class angr.SimOS(project, name=None)[源代码]

基类:object

A class describing OS/arch-level configuration.

参数:

project (angr.Project)

__init__(project, name=None)[源代码]
参数:

project (Project)

configure_project()[源代码]

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)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

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

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

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

prepare_function_symbol(symbol_name, basic_addr=None)[源代码]

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)[源代码]

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.

参数:
  • 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)[源代码]
syscall_abi(state)[源代码]
返回类型:

str

syscall_cc(state)[源代码]
返回类型:

SimCCSyscall | None

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

Write the GlobalDescriptorTable object in the current state memory

参数:
  • state -- state in which to write the GDT

  • gdt -- GlobalDescriptorTable object

返回:

generate_gdt(fs, gs, fs_size=4294967295, gs_size=4294967295)[源代码]

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

参数:
  • 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

返回:

gdt a GlobalDescriptorTable object

exception angr.SimOperationError[源代码]

基类:SimError

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

基类: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.

参数:
  • 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.

变量:
  • 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)[源代码]
set_state(state)[源代码]

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)[源代码]

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

read(pos, size, **kwargs)[源代码]

Read a packet from the stream.

参数:
  • 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.

返回:

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)[源代码]

Write a packet to the stream.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.SimPacketsStream(name, pos=0, **kwargs)[源代码]

基类: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.

参数:
  • 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.

变量:

pos -- The current position in the file.

__init__(name, pos=0, **kwargs)[源代码]
read(pos, size, **kwargs)[源代码]

Read a packet from the stream.

参数:
  • 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.

返回:

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)[源代码]

Write a packet to the stream.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

exception angr.SimPosixError[源代码]

基类:SimStateError

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)[源代码]

基类: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

参数:

arch -- The architecture to use for this procedure

The following parameters are optional:

参数:
  • 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:

变量:
  • 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:

变量:
  • 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:

变量:
  • 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)[源代码]
state: SimState
execute(state, successors=None, arguments=None, ret_to=None)[源代码]

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)[源代码]
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)[源代码]

Implement the actual procedure here!

static_exits(blocks, **kwargs)[源代码]

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

参数:

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

返回:

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

返回类型:

list

dynamic_returns(blocks, **kwargs)[源代码]

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

参数:

blocks -- Blocks that are executed before reaching this SimProcedure.

返回类型:

bool

返回:

True if the call returns, False otherwise.

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

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

参数:
  • 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)[源代码]
ret(expr=None)[源代码]

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')[源代码]

Add an exit representing calling another function via pointer.

参数:
  • 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')[源代码]

Add an exit representing jumping to an address.

exit(exit_code)[源代码]

Add an exit representing terminating the program.

ty_ptr(ty)[源代码]
property is_java
property argument_types
property return_type
exception angr.SimProcedureArgumentError[源代码]

基类:SimProcedureError

exception angr.SimProcedureError[源代码]

基类:SimEngineError

exception angr.SimRegionMapError[源代码]

基类:SimMemoryError

exception angr.SimReliftException(state)[源代码]

基类:SimEngineError

__init__(state)[源代码]
angr.SimSegfaultError

SimSegfaultException 的别名

exception angr.SimSegfaultException(addr, reason, original_addr=None)[源代码]

基类:SimException, SimMemoryError

__init__(addr, reason, original_addr=None)[源代码]
exception angr.SimShadowStackError[源代码]

基类:SimProcedureError

exception angr.SimSlicerError[源代码]

基类:SimError

exception angr.SimSolverError[源代码]

基类:SimError

exception angr.SimSolverModeError[源代码]

基类:SimSolverError

exception angr.SimSolverOptionError[源代码]

基类:SimSolverError

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)[源代码]

基类:Generic[IPTypeConc, IPTypeSym], PluginHub[SimStatePlugin]

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

参数:
变量:
  • 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)[源代码]
参数:
property plugins
property ip

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

返回:

an expression

property addr: IPTypeConc

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.

返回:

an int

property arch: Arch
T = ~T
get_plugin(name)[源代码]

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)[源代码]

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

register_plugin(name, plugin, inhibit_init=False)[源代码]

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.

返回:

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.

返回:

The JavaVM view of the registers plugin.

simplify(*args)[源代码]

Simplify this state's constraints.

add_constraints(*constraints)[源代码]

Add some constraints to the state.

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

satisfiable(**kwargs)[源代码]

Whether the state's constraints are satisfiable

downsize()[源代码]

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

step(**kwargs)[源代码]

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

返回:

A SimSuccessors object categorizing the results of the step.

block(*args, **kwargs)[源代码]

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

返回:

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

copy()[源代码]

Returns a copy of the state.

merge(*others, **kwargs)[源代码]

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

参数:
  • 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.

返回:

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

widen(*others)[源代码]

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

reg_concrete(*args, **kwargs)[源代码]

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

mem_concrete(*args, **kwargs)[源代码]

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

stack_push(thing)[源代码]

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

stack_pop()[源代码]

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

stack_read(offset, length, bp=False)[源代码]

Reads length bytes, at an offset into the stack.

参数:
  • 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)[源代码]
prepare_callsite(retval, args, cc='wtf')[源代码]
dbg_print_stack(depth=None, sp=None)[源代码]

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)[源代码]
property thumb
property with_condition
exception angr.SimStateError[源代码]

基类:SimError

exception angr.SimStateOptionsError[源代码]

基类:SimError

class angr.SimStatePlugin[源代码]

基类: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__()[源代码]
set_state(state)[源代码]

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

set_strongref_state(state)[源代码]
copy(_memo)[源代码]

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!

参数:

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

static memo(f)[源代码]

A decorator function you should apply to copy

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

classmethod register_default(name, xtr=None)[源代码]
init_state()[源代码]

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

exception angr.SimStatementError[源代码]

基类:SimError

exception angr.SimSymbolicFilesystemError[源代码]

基类:SimFilesystemError

exception angr.SimTranslationError[源代码]

基类:SimEngineError

exception angr.SimUCManagerAllocationError[源代码]

基类:SimUCManagerError

exception angr.SimUCManagerError[源代码]

基类:SimError

exception angr.SimUnicornError[源代码]

基类:SimError

exception angr.SimUnicornSymbolic[源代码]

基类:SimError

exception angr.SimUnicornUnsupport[源代码]

基类:SimError

exception angr.SimUninitializedAccessError(expr_type, expr)[源代码]

基类:SimExpressionError

__init__(expr_type, expr)[源代码]
exception angr.SimUnsatError[源代码]

基类:SimValueError

exception angr.SimUnsupportedError[源代码]

基类:SimError

exception angr.SimValueError[源代码]

基类:SimSolverError

exception angr.SimZeroDivisionException[源代码]

基类:SimException, SimOperationError

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)[源代码]

基类: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.

参数:
  • 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.

变量:
  • 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)[源代码]
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)[源代码]

Mulpyplex across several stashes.

参数:

stashes -- the stashes to mulpyplex

返回:

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

copy(deep=False)[源代码]

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)[源代码]

Use an exploration technique with this SimulationManager.

Techniques can be found in angr.exploration_techniques.

参数:

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

返回:

The technique that was added, for convenience

remove_technique(tech)[源代码]

Remove an exploration technique from a list of active techniques.

参数:

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)[源代码]

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)[源代码]

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.

参数:
  • 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.

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

complete()[源代码]

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)[源代码]

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.

参数:
  • 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:

参数:
  • 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

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

step_state(state, successor_func=None, error_list=None, **run_args)[源代码]

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

filter(state, filter_func=None)[源代码]

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

selector(state, selector_func=None)[源代码]

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

successors(state, successor_func=None, **run_args)[源代码]

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

prune(filter_func=None, from_stash='active', to_stash='pruned')[源代码]

Prune unsatisfiable states from a stash.

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

populate(stash, states)[源代码]

Populate a stash with a collection of states.

参数:
  • stash -- A stash to populate.

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

absorb(simgr)[源代码]

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)[源代码]

Move states from one stash to another.

参数:
  • 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)

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

stash(filter_func=None, from_stash='active', to_stash='stashed')[源代码]

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

unstash(filter_func=None, to_stash='active', from_stash='stashed')[源代码]

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

drop(filter_func=None, stash='active')[源代码]

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

apply(state_func=None, stash_func=None, stash='active', to_stash=None)[源代码]

Applies a given function to a given stash.

参数:
  • 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.

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

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

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.

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

merge(merge_func=None, merge_key=None, stash='active', prune=True)[源代码]

Merge the states in a given stash.

参数:
  • 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

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

exception angr.SimulationManagerError[源代码]

基类:AngrError

class angr.StateHierarchy[源代码]

基类: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__()[源代码]
get_ref(obj)[源代码]
dead_ref(ref)[源代码]
defer_cleanup()[源代码]
add_state(s)[源代码]
add_history(h)[源代码]
simplify()[源代码]
full_simplify()[源代码]
lineage(h)[源代码]

Returns the lineage of histories leading up to h.

all_successors(h)[源代码]
history_successors(h)[源代码]
history_predecessors(h)[源代码]
history_contains(h)[源代码]
unreachable_state(state)[源代码]
unreachable_history(h)[源代码]
most_mergeable(states)[源代码]

Find the "most mergeable" set of states from those provided.

参数:

states -- a list of states

返回:

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

exception angr.TracerEnvironmentError[源代码]

基类:AngrError

exception angr.UnsupportedCCallError[源代码]

基类:SimCCallError, SimUnsupportedError

exception angr.UnsupportedDirtyError[源代码]

基类:UnsupportedIRStmtError, SimUnsupportedError

exception angr.UnsupportedIRExprError[源代码]

基类:SimExpressionError, SimUnsupportedError

exception angr.UnsupportedIROpError[源代码]

基类:SimOperationError, SimUnsupportedError

exception angr.UnsupportedIRStmtError[源代码]

基类:SimStatementError, SimUnsupportedError

exception angr.UnsupportedNodeTypeError[源代码]

基类:AngrError, NotImplementedError

angr.UnsupportedSyscallError

AngrUnsupportedSyscallError 的别名

angr.default_cc(arch, platform='Linux', language=None, syscall=False, default=None)[源代码]

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

参数:
  • 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).

  • default (Optional[type[SimCC]]) -- The default calling convention to return if nothing fits.

返回类型:

type[SimCC] | None

返回:

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

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

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

参数:
  • 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

angr.register_analysis(cls, name)[源代码]

Project

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

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

参数:
  • 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)[源代码]

基类: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.

参数:
  • 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.

参数:
  • 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.

变量:
  • 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.

参数:
  • 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)[源代码]
参数:
  • load_options (dict[str, Any] | None)

  • selfmodifying_code (bool)

  • support_selfmodifying_code (bool | None)

arch: Arch
property kb
get_kb(name)[源代码]
property analyses: AnalysesHubWithDefault
hook(addr, hook=None, length=0, kwargs=None, replace=False)[源代码]

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!")
参数:
  • 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)[源代码]

Returns True if addr is hooked.

参数:

addr -- An address.

返回类型:

bool

返回:

True if addr is hooked, False otherwise.

hooked_by(addr)[源代码]

Returns the current hook for addr.

参数:

addr -- An address.

返回类型:

SimProcedure | None

返回:

None if the address is not hooked.

unhook(addr)[源代码]

Remove a hook.

参数:

addr -- The address of the hook.

hook_symbol(symbol_name, simproc, kwargs=None, replace=None)[源代码]

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.

参数:
  • 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.

返回:

The address of the new symbol.

返回类型:

int

symbol_hooked_by(symbol_name)[源代码]

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

参数:

symbol_name (str) -- Name of the symbol.

返回类型:

SimProcedure | None

返回:

None if the address is not hooked.

is_symbol_hooked(symbol_name)[源代码]

Check if a symbol is already hooked.

参数:

symbol_name (str) -- Name of the symbol.

返回:

True if the symbol can be resolved and is hooked, False otherwise.

返回类型:

bool

unhook_symbol(symbol_name)[源代码]

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)[源代码]

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)[源代码]

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()[源代码]

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

class angr.factory.AngrObjectFactory(project, default_engine=None)[源代码]

基类:object

This factory provides access to important analysis elements.

参数:

default_engine (type[SimEngine] | None)

__init__(project, default_engine=None)[源代码]
参数:

default_engine (type[SimEngine] | None)

default_engine_factory: type[SimEngine]
project: Project
procedure_engine: ProcedureEngine
property default_engine
snippet(addr, jumpkind=None, **block_opts)[源代码]
successors(*args, engine=None, **kwargs)[源代码]

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

参数:
  • 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)[源代码]

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

参数:
  • 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.

返回:

The blank state.

返回类型:

SimState

entry_state(**kwargs)[源代码]

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

参数:
  • 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.

返回:

The entry state.

返回类型:

SimState

full_init_state(**kwargs)[源代码]

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

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

call_state(addr, *args, **kwargs)[源代码]

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

参数:
  • 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.

参数:
  • 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.

返回:

The state at the beginning of the function.

返回类型:

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)[源代码]

Constructs a new simulation manager.

参数:
  • 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

返回:

The new SimulationManager

返回类型:

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)[源代码]

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)[源代码]

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

参数:
  • 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

返回:

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

返回类型:

angr.callable.Callable

cc()[源代码]

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()[源代码]

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)[源代码]
fresh_block(addr, size, backup_state=None)[源代码]
class angr.block.DisassemblerBlock(addr, insns, thumb, arch)[源代码]

基类:object

Helper class to represent a block of disassembled target architecture instructions

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

基类: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)[源代码]

基类: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)[源代码]

基类:DisassemblerInsn

Represents a capstone instruction.

__init__(capstone_insn)[源代码]
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)[源代码]

基类: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)[源代码]
arch
thumb
addr
size
pp(**kwargs)[源代码]
set_initial_regs()[源代码]
static reset_initial_regs()[源代码]
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: int
property instruction_addrs
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.block.SootBlock(addr, project=None, arch=None)[源代码]

基类:object

Represents a Soot IR basic block.

__init__(addr, project=None, arch=None)[源代码]
property soot
property size
property codenode

Plugin Ecosystem

class angr.misc.plugins.PluginHub[源代码]

基类: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__()[源代码]
classmethod register_default(name, plugin_cls, preset='default')[源代码]
classmethod register_preset(name, preset)[源代码]

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)[源代码]

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()[源代码]

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

get_plugin(name)[源代码]

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

返回类型:

TypeVar(P)

参数:

name (str)

has_plugin(name)[源代码]

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

register_plugin(name, plugin)[源代码]

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

参数:

name (str)

release_plugin(name)[源代码]

Deactivate and remove the plugin with name name.

class angr.misc.plugins.PluginPreset[源代码]

基类: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__()[源代码]
activate(hub)[源代码]

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

deactivate(hub)[源代码]

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

add_default_plugin(name, plugin_cls)[源代码]

Add a plugin to the preset.

list_default_plugins()[源代码]

Return a list of the names of available default plugins.

request_plugin(name)[源代码]

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

返回类型:

type[TypeVar(P)]

参数:

name (str)

copy()[源代码]

Return a copy of self.

class angr.misc.plugins.PluginVendor[源代码]

基类: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)[源代码]

Deactivate and remove the plugin with name name.

register_plugin(name, plugin)[源代码]

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

class angr.misc.plugins.VendorPreset[源代码]

基类:PluginPreset

A specialized preset class for use with the PluginVendor.

Program State

angr.sim_state.arch_overridable(f)[源代码]
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)[源代码]

基类:Generic[IPTypeConc, IPTypeSym], PluginHub[SimStatePlugin]

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

参数:
变量:
  • 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)[源代码]
参数:
property plugins
property ip

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

返回:

an expression

property addr: IPTypeConc

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.

返回:

an int

property arch: Arch
T = ~T
get_plugin(name)[源代码]

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)[源代码]

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

register_plugin(name, plugin, inhibit_init=False)[源代码]

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.

返回:

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.

返回:

The JavaVM view of the registers plugin.

simplify(*args)[源代码]

Simplify this state's constraints.

add_constraints(*constraints)[源代码]

Add some constraints to the state.

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

satisfiable(**kwargs)[源代码]

Whether the state's constraints are satisfiable

downsize()[源代码]

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

step(**kwargs)[源代码]

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

返回:

A SimSuccessors object categorizing the results of the step.

block(*args, **kwargs)[源代码]

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

返回:

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

copy()[源代码]

Returns a copy of the state.

merge(*others, **kwargs)[源代码]

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

参数:
  • 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.

返回:

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

widen(*others)[源代码]

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

reg_concrete(*args, **kwargs)[源代码]

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

mem_concrete(*args, **kwargs)[源代码]

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

stack_push(thing)[源代码]

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

stack_pop()[源代码]

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

stack_read(offset, length, bp=False)[源代码]

Reads length bytes, at an offset into the stack.

参数:
  • 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)[源代码]
prepare_callsite(retval, args, cc='wtf')[源代码]
dbg_print_stack(depth=None, sp=None)[源代码]

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)[源代码]
property thumb
property with_condition
class angr.sim_state_options.StateOption(name, types, default='_NO_DEFAULT_VALUE', description=None)[源代码]

基类:object

Describes a state option.

__init__(name, types, default='_NO_DEFAULT_VALUE', description=None)[源代码]
name
types
default
description
property has_default_value
one_type()[源代码]
class angr.sim_state_options.SimStateOptions(thing)[源代码]

基类: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)[源代码]
参数:

thing -- Either a set of Boolean switches to enable, or an existing SimStateOptions instance.

add(boolean_switch)[源代码]

[COMPATIBILITY] Enable a Boolean switch.

参数:

boolean_switch (str) -- Name of the Boolean switch.

返回:

None

update(boolean_switches)[源代码]

[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)
参数:

boolean_switches (set) -- A collection of Boolean switches to enable.

返回:

None

remove(name)[源代码]

Drop a state option if it exists, or raise a KeyError if the state option is not set.

[COMPATIBILITY] Remove a Boolean switch.

参数:

name (str) -- Name of the state option.

返回:

NNone

discard(name)[源代码]

Drop a state option if it exists, or silently return if the state option is not set.

[COMPATIBILITY] Disable a Boolean switch.

参数:

name (str) -- Name of the Boolean switch.

返回:

None

difference(boolean_switches)[源代码]

[COMPATIBILITY] Make a copy of the current instance, and then discard all options that are in boolean_switches.

参数:

boolean_switches (set) -- A collection of Boolean switches to disable.

返回:

A new SimStateOptions instance.

copy()[源代码]

Get a copy of the current SimStateOptions instance.

返回:

A new SimStateOptions instance.

返回类型:

SimStateOptions

tally(exclude_false=True, description=False)[源代码]

Return a string representation of all state options.

参数:
  • exclude_false (bool) -- Whether to exclude Boolean switches that are disabled.

  • description (bool) -- Whether to display the description of each option.

返回:

A string representation.

返回类型:

str

classmethod register_option(name, types, default=None, description=None)[源代码]

Register a state option.

参数:
  • 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.

返回:

None

classmethod register_bool_option(name, description=None)[源代码]

Register a Boolean switch as state option. This is equivalent to cls.register_option(name, set([bool]), description=description)

参数:
  • name (str) -- Name of the state option.

  • description (str) -- The description of this state option.

返回:

None

class angr.state_plugins.GDB(omit_fp=False, adjust_stack=False)[源代码]

基类:SimStatePlugin

Initialize or update a state from gdb dumps of the stack, heap, registers and data (or arbitrary) segments.

__init__(omit_fp=False, adjust_stack=False)[源代码]
参数:
  • omit_fp -- The frame pointer register is used for something else. (i.e. --omit_frame_pointer)

  • adjust_stack -- Use different stack addresses than the gdb session (not recommended).

set_stack(stack_dump, stack_top)[源代码]

Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :

dump binary memory [stack_dump] [begin_addr] [end_addr]

We set the stack to the same addresses as the gdb session to avoid pointers corruption.

参数:
  • stack_dump -- The dump file.

  • stack_top -- The address of the top of the stack in the gdb session.

set_heap(heap_dump, heap_base)[源代码]

Heap dump is a dump of the heap from gdb, i.e. the result of the following gdb command:

dump binary memory [stack_dump] [begin] [end]

参数:
  • heap_dump -- The dump file.

  • heap_base -- The start address of the heap in the gdb session.

set_data(addr, data_dump)[源代码]

Update any data range (most likely use is the data segments of loaded objects)

set_regs(regs_dump)[源代码]

Initialize register values within the state

参数:

regs_dump -- The output of info registers in gdb.

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!

参数:

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.CallStack(call_site_addr=0, func_addr=0, stack_ptr=0, ret_addr=0, jumpkind='Ijk_Call', next_frame=None, invoke_return_variable=None)[源代码]

基类:SimStatePlugin

Stores the address of the function you're in and the value of SP at the VERY BOTTOM of the stack, i.e. points to the return address.

参数:

next_frame (CallStack | None)

__init__(call_site_addr=0, func_addr=0, stack_ptr=0, ret_addr=0, jumpkind='Ijk_Call', next_frame=None, invoke_return_variable=None)[源代码]
参数:

next_frame (CallStack | None)

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!

参数:

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

set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

property current_function_address

Address of the current function.

返回:

the address of the function

返回类型:

int

property current_stack_pointer

Get the value of the stack pointer.

返回:

Value of the stack pointer

返回类型:

int

property current_return_target

Get the return target.

返回:

The address of return target.

返回类型:

int

static stack_suffix_to_string(stack_suffix)[源代码]

Convert a stack suffix to a human-readable string representation. :param tuple stack_suffix: The stack suffix. :return: A string representation :rtype: str

property top

Returns the element at the top of the callstack without removing it.

返回:

A CallStack.

push(cf)[源代码]

Push the frame cf onto the stack. Return the new stack.

pop()[源代码]

Pop the top frame from the stack. Return the new stack.

call(callsite_addr, addr, retn_target=None, stack_pointer=None)[源代码]

Push a stack frame into the call stack. This method is called when calling a function in CFG recovery.

参数:
  • callsite_addr (int) -- Address of the call site

  • addr (int) -- Address of the call target

  • retn_target (int or None) -- Address of the return target

  • stack_pointer (int) -- Value of the stack pointer

返回:

None

ret(retn_target=None)[源代码]

Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery.

参数:

retn_target (int) -- The target to return to.

返回:

None

dbg_repr()[源代码]

Debugging representation of this CallStack object.

返回:

Details of this CalLStack

返回类型:

str

stack_suffix(context_sensitivity_level)[源代码]

Generate the stack suffix. A stack suffix can be used as the key to a SimRun in CFG recovery.

参数:

context_sensitivity_level (int) -- Level of context sensitivity.

返回:

A tuple of stack suffix.

返回类型:

tuple

class angr.state_plugins.PTChunk(base, sim_state, heap=None)[源代码]

基类: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

变量:
  • 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)[源代码]
get_size()[源代码]

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

get_data_size()[源代码]

Returns the size of the data portion of a chunk.

set_size(size, is_free=None)[源代码]

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.

参数:
  • size -- size of the chunk

  • is_free -- boolean indicating the chunk's freeness

set_prev_freeness(is_free)[源代码]

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

参数:

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

is_prev_free()[源代码]

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.

返回:

True if the previous chunk is free; False otherwise

prev_size()[源代码]

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()[源代码]

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

data_ptr()[源代码]

Returns the address of the payload of the chunk.

next_chunk()[源代码]

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

返回:

The following chunk, or None if applicable

prev_chunk()[源代码]

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.

返回:

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

fwd_chunk()[源代码]

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.

返回:

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

set_fwd_chunk(fwd)[源代码]

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

参数:

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

bck_chunk()[源代码]

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.

返回:

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

set_bck_chunk(bck)[源代码]

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

参数:

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

class angr.state_plugins.PTChunkIterator(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]

基类:object

__init__(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]
class angr.state_plugins.PosixDevFS[源代码]

基类:SimMount

get(path)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(_)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

copy(_)[源代码]

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!

参数:

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[源代码]

基类:SimMount

The virtual file system mounted at /proc (as of now, on Linux).

get(path)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(_)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

copy(_)[源代码]

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!

参数:

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.SimAction(state, region_type)[源代码]

基类:SimEvent

A SimAction represents a semantic action that an analyzed program performs.

TMP = 'tmp'
REG = 'reg'
MEM = 'mem'
__init__(state, region_type)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
property tmp_deps
property reg_deps
copy()[源代码]
downsize()[源代码]

Clears some low-level details (that take up memory) out of the SimAction.

class angr.state_plugins.SimActionConstraint(state, constraint, condition=None)[源代码]

基类:SimAction

A constraint action represents an extra constraint added during execution of a path.

__init__(state, constraint, condition=None)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
class angr.state_plugins.SimActionData(state, region_type, action, tmp=None, addr=None, size=None, data=None, condition=None, fallback=None, fd=None)[源代码]

基类:SimAction

A Data action represents a read or a write from memory, registers or a file.

READ = 'read'
WRITE = 'write'
OPERATE = 'operate'
__init__(state, region_type, action, tmp=None, addr=None, size=None, data=None, condition=None, fallback=None, fd=None)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

downsize()[源代码]

Clears some low-level details (that take up memory) out of the SimAction.

property all_objects
property is_symbolic
property tmp_deps
property reg_deps
property storage
class angr.state_plugins.SimActionExit(state, target, condition=None, exit_type=None)[源代码]

基类:SimAction

An Exit action represents a (possibly conditional) jump.

CONDITIONAL = 'conditional'
DEFAULT = 'default'
__init__(state, target, condition=None, exit_type=None)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
class angr.state_plugins.SimActionObject(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]

基类:object

A SimActionObject tracks an AST and its dependencies.

参数:
__init__(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]
参数:
ast: Base
reg_deps: frozenset[SimActionData | SimActionOperation]
tmp_deps: frozenset[SimActionData | SimActionOperation]
to_claripy()[源代码]
返回类型:

Base

copy()[源代码]
返回类型:

SimActionObject

is_leaf()[源代码]
返回类型:

bool

property op: str
property args: tuple[ArgType, ...]
property length: int | None
property variables: frozenset[str]
property symbolic: bool
property annotations: tuple[Annotation, ...]
property depth: int
SDiv(other)[源代码]
返回类型:

SimActionObject

SMod(other)[源代码]
返回类型:

SimActionObject

union(other)[源代码]
返回类型:

SimActionObject

intersection(other)[源代码]
返回类型:

SimActionObject

widen(other)[源代码]
返回类型:

SimActionObject

raw_to_bv()[源代码]
返回类型:

SimActionObject

bv_to_fp()[源代码]
返回类型:

SimActionObject

class angr.state_plugins.SimActionOperation(state, op, exprs, result)[源代码]

基类:SimAction

An action representing an operation between variables and/or constants.

__init__(state, op, exprs, result)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
class angr.state_plugins.SimDebugVariable(state, addr, var_type)[源代码]

基类:object

A SimDebugVariable will get dynamically created when queriyng for variable in a state with the SimDebugVariablePlugin. It features a link to the state, an address and a type.

参数:
__init__(state, addr, var_type)[源代码]
参数:
static from_cle_variable(state, cle_variable, dwarf_cfa)[源代码]
返回类型:

SimDebugVariable

参数:
property mem_untyped: SimMemView
property mem: SimMemView
property string: SimMemView
with_type(sim_type)[源代码]
返回类型:

SimMemView

参数:

sim_type (SimType)

property resolvable
property resolved
property concrete
store(value)[源代码]
property deref: SimDebugVariable
array(i)[源代码]
返回类型:

SimDebugVariable

member(member_name)[源代码]
返回类型:

SimDebugVariable

参数:

member_name (str)

class angr.state_plugins.SimDebugVariablePlugin[源代码]

基类:SimStatePlugin

This is the plugin you'll use to interact with (global/local) program variables. These variables have a name and a visibility scope which depends on the pc address of the state. With this plugin, you can access/modify the value of such variable or find its memory address. For creating program variables, or for importing them from cle, see the knowledge plugin debug_variables. Run p.kb.dvars.load_from_dwarf() before using this plugin.

示例

>>> p = angr.Project("various_variables", load_debug_info=True)
>>> p.kb.dvars.load_from_dwarf()
>>> state =  # navigate to the state you want
>>> state.dvars.get_variable("pointer2").deref.mem
<int (32 bits) <BV32 0x1> at 0x404020>
get_variable(var_name)[源代码]

Returns the visible variable (if any) with name var_name based on the current state.ip.

返回类型:

SimDebugVariable

参数:

var_name (str)

property dwarf_cfa

Returns the current cfa computation. Set this property to the correct value if needed.

property dwarf_cfa_approx
class angr.state_plugins.SimEvent(state, event_type, **kwargs)[源代码]

基类:object

A SimEvent is a log entry for some notable event during symbolic execution. It logs the location it was generated (ins_addr, bbl_addr, stmt_idx, and sim_procedure) as well as arbitrary tags (objects).

You may also be interested in SimAction, which is a specialization of SimEvent for CPU events.

__init__(state, event_type, **kwargs)[源代码]
class angr.state_plugins.SimFilesystem(files=None, pathsep=None, cwd=None, mountpoints=None)[源代码]

基类:SimStatePlugin

angr's emulated filesystem. Available as state.fs. When constructing, all parameters are optional.

参数:
  • files -- A mapping from filepath to SimFile

  • pathsep -- The character used to separate path elements, default forward slash.

  • cwd -- The path of the current working directory to use

  • mountpoints -- A mapping from filepath to SimMountpoint

变量:
  • pathsep -- The current pathsep

  • cwd -- The current working directory

  • unlinks -- A list of unlink operations, tuples of filename and simfile. Be careful, this list is shallow-copied from successor to successor, so don't mutate anything in it without copying.

__init__(files=None, pathsep=None, cwd=None, mountpoints=None)[源代码]
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!

参数:

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

set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

chdir(path)[源代码]

Changes the current directory to the given path

get(path)[源代码]

Get a file from the filesystem. Returns a SimFile or None.

insert(path, simfile)[源代码]

Insert a file into the filesystem. Returns whether the operation was successful.

delete(path)[源代码]

Remove a file from the filesystem. Returns whether the operation was successful.

This will add a fs_unlink event with the path of the file and also the index into the unlinks list.

mount(path, mount)[源代码]

Add a mountpoint to the filesystem.

unmount(path)[源代码]

Remove a mountpoint from the filesystem.

get_mountpoint(path)[源代码]

Look up the mountpoint servicing the given path.

返回:

A tuple of the mount and a list of path elements traversing from the mountpoint to the specified file.

class angr.state_plugins.SimHeapBase(heap_base=None, heap_size=None)[源代码]

基类:SimStatePlugin

This is the base heap class that all heap implementations should subclass. It defines a few handlers for common heap functions (the libc memory management functions). Heap implementations are expected to override these functions regardless of whether they implement the SimHeapLibc interface. For an example, see the SimHeapBrk implementation, which is based on the original libc SimProcedure implementations.

变量:
  • 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

__init__(heap_base=None, heap_size=None)[源代码]
copy(memo)[源代码]

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!

参数:

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

init_state()[源代码]

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

class angr.state_plugins.SimHeapBrk(heap_base=None, heap_size=None)[源代码]

基类: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).

变量:

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)[源代码]
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!

参数:

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

allocate(sim_size)[源代码]

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.

参数:

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

返回:

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

release(sim_size)[源代码]

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.

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.SimHeapLibc(heap_base=None, heap_size=None)[源代码]

基类:SimHeapBase

A class of heap that implements the major libc heap management functions.

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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

class angr.state_plugins.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]

基类: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.

变量:
  • 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)[源代码]
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!

参数:

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

chunks()[源代码]

Returns an iterator over all the chunks in the heap.

allocated_chunks()[源代码]

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

free_chunks()[源代码]

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

chunk_from_mem(ptr)[源代码]

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.

参数:

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

返回:

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

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

init_state()[源代码]

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

class angr.state_plugins.SimHostFilesystem(host_path=None, **kwargs)[源代码]

基类:SimConcreteFilesystem

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

参数:
  • 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)[源代码]
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!

参数:

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.SimInspector[源代码]

基类: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__()[源代码]
action(event_type, when, **kwargs)[源代码]

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)[源代码]

Creates and adds a breakpoint which would trigger on event_type. Additional arguments are passed to the BP constructor.

返回:

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.

返回:

The created breakpoint, so that it can be removed later.

add_breakpoint(event_type, bp)[源代码]

Adds a breakpoint which would trigger on event_type.

参数:
  • event_type -- The event type to trigger on

  • bp -- The breakpoint

返回:

The created breakpoint.

remove_breakpoint(event_type, bp=None, filter_func=None)[源代码]

Removes a breakpoint.

参数:
  • 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!

参数:

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

downsize()[源代码]

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

set_state(state)[源代码]

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

class angr.state_plugins.SimJavaVmClassloader(initialized_classes=None)[源代码]

基类:SimStatePlugin

JavaVM Classloader is used as an interface for resolving and initializing Java classes.

__init__(initialized_classes=None)[源代码]
get_class(class_name, init_class=False, step_func=None)[源代码]

Get a class descriptor for the class.

参数:
  • class_name (str) -- Name of class.

  • init_class (bool) -- Whether the class initializer <clinit> should be executed.

  • step_func (func) -- Callback function executed at every step of the simulation manager during the execution of the main <clinit> method

get_superclass(class_)[源代码]

Get the superclass of the class.

get_class_hierarchy(base_class)[源代码]

Walks up the class hierarchy and returns a list of all classes between base class (inclusive) and java.lang.Object (exclusive).

is_class_initialized(class_)[源代码]

Indicates whether the classes initializing method <clinit> was already executed on the state.

init_class(class_, step_func=None)[源代码]

This method simulates the loading of a class by the JVM, during which parts of the class (e.g. static fields) are initialized. For this, we run the class initializer method <clinit> (if available) and update the state accordingly.

Note: Initialization is skipped, if the class has already been

initialized (or if it's not loaded in CLE).

property initialized_classes

List of all initialized classes.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.SimLightRegisters(reg_map=None, registers=None)[源代码]

基类:SimStatePlugin

__init__(reg_map=None, registers=None)[源代码]
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!

参数:

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

set_state(state)[源代码]

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

resolve_register(offset, size)[源代码]
load(offset, size=None, **kwargs)[源代码]
store(offset, value, size=None, endness=None, **kwargs)[源代码]
class angr.state_plugins.SimMemView(ty=None, addr=None, state=None)[源代码]

基类:SimStatePlugin

This is a convenient interface with which you can access a program's memory.

The interface works like this:

  • You first use [array index notation] to specify the address you'd like to load from

  • If at that address is a pointer, you may access the deref property to return a SimMemView at the address present in memory.

  • You then specify a type for the data by simply accessing a property of that name. For a list of supported types, look at state.mem.types.

  • You can then refine the type. Any type may support any refinement it likes. Right now the only refinements supported are that you may access any member of a struct by its member name, and you may index into a string or array to access that element.

  • If the address you specified initially points to an array of that type, you can say .array(n) to view the data as an array of n elements.

  • Finally, extract the structured data with .resolved or .concrete. .resolved will return bitvector values, while .concrete will return integer, string, array, etc values, whatever best represents the data.

  • Alternately, you may store a value to memory, by assigning to the chain of properties that you've constructed. Note that because of the way python works, x = s.mem[...].prop; x = val will NOT work, you must say s.mem[...].prop = val.

For example:

>>> s.mem[0x601048].long
<long (64 bits) <BV64 0x4008d0> at 0x601048>
>>> s.mem[0x601048].long.resolved
<BV64 0x4008d0>
>>> s.mem[0x601048].deref
<<untyped> <unresolvable> at 0x4008d0>
>>> s.mem[0x601048].deref.string.concrete
'SOSNEAKY'
参数:

state (SimState)

__init__(ty=None, addr=None, state=None)[源代码]
set_state(state)[源代码]

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

types: ClassVar[dict] = {'CharT': char, 'FILE_t': struct FILE_t, '_Bool': bool, '_ENTRY': struct _ENTRY, '_IO_codecvt': struct _IO_codecvt, '_IO_iconv_t': struct _IO_iconv_t, '_IO_lock_t': struct pthread_mutex_t, '_IO_marker': struct _IO_marker, '_IO_wide_data': struct _IO_wide_data, '__clock_t': uint32_t, '__dev_t': uint64_t, '__gid_t': unsigned int, '__ino64_t': unsigned long long, '__ino_t': unsigned long, '__int128': int128_t, '__int256': int256_t, '__mbstate_t': struct __mbstate_t, '__mode_t': unsigned int, '__nlink_t': unsigned int, '__off64_t': long long, '__off_t': long, '__pid_t': int, '__suseconds_t': int64_t, '__time_t': long, '__uid_t': unsigned int, '_obstack_chunk': struct _obstack_chunk, 'aiocb': struct aiocb, 'aiocb64': struct aiocb64, 'aioinit': struct aioinit, 'argp': struct argp, 'argp_child': struct argp_child, 'argp_option': struct argp_option, 'argp_parser_t': (int, char*, struct argp_state*) -> int, 'argp_state': struct argp_state, 'basic_string': string_t, 'bool': bool, 'byte': uint8_t, 'cc_t': char, 'char': char, 'clock_t': uint32_t, 'crypt_data': struct crypt_data, 'dirent': struct dirent, 'dirent64': struct dirent64, 'double': double, 'drand48_data': struct <anon>, 'dword': uint32_t, 'error_t': int, 'exit_status': struct exit_status, 'float': float, 'fstab': struct fstab, 'group': struct group, 'hostent': struct hostent, 'hsearch_data': struct hsearch_data, 'if_nameindex': struct if_nameindex, 'in_addr': struct in_addr, 'in_port_t': uint16_t, 'ino64_t': unsigned long long, 'ino_t': unsigned long, 'int': int, 'int16_t': int16_t, 'int32_t': int32_t, 'int64_t': int64_t, 'int8_t': int8_t, 'iovec': struct <anon>, 'itimerval': struct itimerval, 'lconv': struct lconv, 'long': long, 'long double': double, 'long int': long, 'long long': long long, 'long long int': long long, 'long signed': long, 'long unsigned int': unsigned long, 'mallinfo': struct mallinfo, 'mallinfo2': struct mallinfo2, 'mntent': struct mntent, 'netent': struct netent, 'ntptimeval': struct ntptimeval, 'obstack': struct obstack, 'off64_t': long long, 'off_t': long, 'option': struct option, 'passwd': struct passwd, 'pid_t': int, 'printf_info': struct printf_info, 'protoent': struct protoent, 'ptrdiff_t': long, 'qword': uint64_t, 'random_data': struct <anon>, 'rlim64_t': uint64_t, 'rlim_t': unsigned long, 'rlimit': struct rlimit, 'rlimit64': struct rlimit64, 'rusage': struct rusage, 'sa_family_t': unsigned short, 'sched_param': struct sched_param, 'sembuf': struct sembuf, 'servent': struct servent, 'sgttyb': struct sgttyb, 'short': short, 'short int': short, 'sigevent': struct sigevent, 'signed': int, 'signed char': char, 'signed int': int, 'signed long': long, 'signed long int': long, 'signed long long': long long, 'signed long long int': long long, 'signed short': short, 'signed short int': short, 'sigstack': struct sigstack, 'sigval': union sigval { sival_int int; sival_ptr void*; }, 'size_t': size_t, 'sockaddr': struct sockaddr, 'sockaddr_in': struct sockaddr_in, 'speed_t': long, 'ssize': size_t, 'ssize_t': size_t, 'stat': struct stat, 'stat64': struct stat64, 'string': string_t, 'struct iovec': struct iovec, 'struct timespec': struct timespec, 'struct timeval': struct timeval, 'tcflag_t': unsigned long, 'termios': struct termios, 'time_t': long, 'timespec': struct timeval, 'timeval': struct timeval, 'timex': struct timex, 'timezone': struct timezone, 'tm': struct tm, 'tms': struct tms, 'uint16_t': uint16_t, 'uint32_t': uint32_t, 'uint64_t': uint64_t, 'uint8_t': uint8_t, 'uintptr_t': unsigned long, 'unsigned': unsigned int, 'unsigned __int128': uint128_t, 'unsigned __int256': uint256_t, 'unsigned char': char, 'unsigned int': unsigned int, 'unsigned long': unsigned long, 'unsigned long int': unsigned long, 'unsigned long long': unsigned long long, 'unsigned long long int': unsigned long long, 'unsigned short': unsigned short, 'unsigned short int': unsigned short, 'utimbuf': struct utimbuf, 'utmp': struct utmp, 'utmpx': struct utmx, 'utsname': struct utsname, 'va_list': struct va_list[1], 'void': void, 'vtimes': struct vtimes, 'wchar_t': short, 'winsize': struct winsize, 'word': uint16_t, 'wstring': wstring_t}
state: angr.SimState = None
struct: StructMode
with_type(sim_type)[源代码]

Returns a copy of the SimMemView with a type.

参数:

sim_type (SimType) -- The new type.

返回类型:

SimMemView

返回:

The typed SimMemView copy.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

property resolvable
property resolved
property concrete
property deref: SimMemView
array(n)[源代码]
返回类型:

SimMemView

member(member_name)[源代码]

If self is a struct and member_name is a member of the struct, return that member element. Otherwise raise an exception.

返回类型:

SimMemView

参数:

member_name (str)

store(value)[源代码]
class angr.state_plugins.SimMount[源代码]

基类: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)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path_elements, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path_elements)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(sim_file)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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

class angr.state_plugins.SimRegNameView[源代码]

基类:SimStatePlugin

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

get(reg_name)[源代码]
class angr.state_plugins.SimSolver(solver=None, all_variables=None, temporal_tracked_variables=None, eternal_tracked_variables=None)[源代码]

基类: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)[源代码]
reload_solver(constraints=None)[源代码]

Reloads the solver. Useful when changing solver options.

参数:

constraints (list) -- A new list of constraints to use in the reloaded solver instead of the current one

get_variables(*keys)[源代码]

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)[源代码]

Register a value with the variable tracking system

参数:
  • 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)[源代码]

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)[源代码]

Creates an unconstrained symbol or a default concrete value (0), based on the state options.

参数:
  • 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.

返回:

an unconstrained symbol (or a concrete value of 0).

BVS(name, size, min=None, max=None, stride=None, uninitialized=False, explicit_name=False, key=None, eternal=False, inspect=True, events=True, **kwargs)[源代码]

Creates a bit-vector symbol (i.e., a variable). Other keyword parameters are passed directly on to the constructor of claripy.ast.BV.

参数:
  • 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

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

downsize()[源代码]

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)[源代码]

Evaluate an expression, using the solver if necessary. Returns AST objects.

参数:
  • e -- the expression

  • n -- the number of desired solutions

  • extra_constraints -- extra constraints to apply to the solver

  • exact -- if False, returns approximate solutions

返回:

a tuple of the solutions, in the form of claripy AST nodes

返回类型:

tuple

max(e, extra_constraints=(), exact=None, signed=False)[源代码]

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)[源代码]

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)[源代码]

Return True if v is a solution of expr with the extra constraints, False otherwise.

参数:
  • 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.

返回:

True if v is a solution of expr, False otherwise

is_true(e, extra_constraints=(), exact=None)[源代码]

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.

参数:
  • 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.

返回:

True if v is definitely true, False otherwise

is_false(e, extra_constraints=(), exact=None)[源代码]

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.

参数:
  • 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.

返回:

True if v is definitely false, False otherwise

unsat_core(extra_constraints=())[源代码]

This function returns the unsat core from the backend solver.

参数:

extra_constraints -- Extra constraints (as ASTs) to add to the solver for this solve.

返回:

The unsat core.

satisfiable(extra_constraints=(), exact=None)[源代码]

This function does a constraint check and checks if the solver is in a sat state.

参数:
  • extra_constraints -- Extra constraints (as ASTs) to add to s for this solve

  • exact -- If False, return approximate solutions.

返回:

True if sat, otherwise false

add(*constraints)[源代码]

Add some constraints to the solver.

参数:

constraints -- Pass any constraints that you want to add (ASTs) as varargs.

CastType = ~CastType
eval_upto(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression, using the solver if necessary. Returns primitives as specified by the cast_to parameter. Only certain primitives are supported, check the implementation of _cast_to to see which ones.

参数:
  • e -- the expression

  • n -- the number of desired solutions

  • extra_constraints -- extra constraints to apply to the solver

  • exact -- if False, returns approximate solutions

  • cast_to -- desired type of resulting values

返回:

a tuple of the solutions, in the form of Python primitives

返回类型:

tuple

eval(e, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get any possible solution. The desired output types can be specified using the cast_to parameter. extra_constraints can be used to specify additional constraints the returned values must satisfy.

参数:
  • e -- the expression to get a solution for

  • kwargs -- Any additional kwargs will be passed down to eval_upto

  • cast_to -- desired type of resulting values

抛出:

SimUnsatError -- if no solution could be found satisfying the given constraints

返回:

eval_one(e, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get the only possible solution. Errors if either no or more than one solution is returned. A kwarg parameter default can be specified to be returned instead of failure!

参数:
  • e -- the expression to get a solution for

  • cast_to -- desired type of resulting values

  • default -- A value can be passed as a kwarg here. It will be returned in case of failure.

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if more than one solution was found to satisfy the given constraints

返回:

The value for e

eval_atmost(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get at most n possible solutions. Errors if either none or more than n solutions are returned.

参数:
  • e -- the expression to get a solution for

  • n -- the inclusive upper limit on the number of solutions

  • cast_to -- desired type of resulting values

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if more than n solutions were found to satisfy the given constraints

返回:

The solutions for e

eval_atleast(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get at least n possible solutions. Errors if less than n solutions were found.

参数:
  • e -- the expression to get a solution for

  • n -- the inclusive lower limit on the number of solutions

  • cast_to -- desired type of resulting values

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if less than n solutions were found to satisfy the given constraints

返回:

The solutions for e

eval_exact(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get exactly the n possible solutions. Errors if any number of solutions other than n was found to exist.

参数:
  • e -- the expression to get a solution for

  • n -- the inclusive lower limit on the number of solutions

  • cast_to -- desired type of resulting values

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if any number of solutions other than n were found to satisfy the given constraints

返回:

The solutions for e

min_int(e, extra_constraints=(), exact=None, signed=False)

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)

max_int(e, extra_constraints=(), exact=None, signed=False)

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)

unique(e, **kwargs)[源代码]

Returns True if the expression e has only one solution by querying the constraint solver. It does also add that unique solution to the solver's constraints.

symbolic(e)[源代码]

Returns True if the expression e is symbolic.

single_valued(e)[源代码]

Returns True whether e is a concrete value or is a value set with only 1 possible value. This differs from unique in that this does not query the constraint solver.

simplify(e=None)[源代码]

Simplifies e. If e is None, simplifies the constraints of this state.

variables(e)[源代码]

Returns the symbolic variables present in the AST of e.

class angr.state_plugins.SimStateCGC[源代码]

基类:SimStatePlugin

This state plugin keeps track of CGC state.

EBADF = 1
EFAULT = 2
EINVAL = 3
ENOMEM = 4
ENOSYS = 5
EPIPE = 6
FD_SETSIZE = 1024
max_allocation = 268435456
__init__()[源代码]
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!

参数:

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

peek_input()[源代码]
discard_input(num_bytes)[源代码]
peek_output()[源代码]
discard_output(num_bytes)[源代码]
addr_invalid(a)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

get_max_sinkhole(length)[源代码]

Find a sinkhole which is large enough to support length bytes.

This uses first-fit. The first sinkhole (ordered in descending order by their address) which can hold length bytes is chosen. If there are more than length bytes in the sinkhole, a new sinkhole is created representing the remaining bytes while the old sinkhole is removed.

add_sinkhole(address, length)[源代码]

Add a sinkhole.

Allow the possibility for the program to reuse the memory represented by the address length pair.

class angr.state_plugins.SimStateGlobals(backer=None)[源代码]

基类:SimStatePlugin

__init__(backer=None)[源代码]
set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

keys()[源代码]
values()[源代码]
items()[源代码]
get(k, alt=None)[源代码]
pop(k, alt=None)[源代码]
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!

参数:

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.SimStateHistory(parent=None, clone=None)[源代码]

基类:SimStatePlugin

This class keeps track of historically-relevant information for paths.

STRONGREF_STATE = True
__init__(parent=None, clone=None)[源代码]
init_state()[源代码]

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

set_strongref_state(state)[源代码]
property addr
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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!

参数:

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

trim()[源代码]

Discard the ancestry of this state.

filter_actions(start_block_addr=None, end_block_addr=None, block_stmt=None, insn_addr=None, read_from=None, write_to=None)[源代码]

Filter self.actions based on some common parameters.

[start_block_addr, end_block_addr]

参数:
  • start_block_addr -- Only return actions generated in blocks starting at this address.

  • end_block_addr -- Only return actions generated in blocks ending at this address.

  • block_stmt -- Only return actions generated in the nth statement of each block.

  • insn_addr -- Only return actions generated in the assembly instruction at this address.

  • read_from -- Only return actions that perform a read from the specified location.

  • write_to -- Only return actions that perform a write to the specified location.

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

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

demote()[源代码]

Demotes this history node, causing it to drop the strong state reference.

reachable()[源代码]
add_event(event_type, **kwargs)[源代码]
add_action(action)[源代码]
extend_actions(new_actions)[源代码]
subscribe_actions()[源代码]
property recent_constraints
property recent_actions
property block_count
property lineage
property parents
property events: Reversible[SimEvent]
property actions: Reversible[SimAction]
property jumpkinds: Reversible[str]
property jump_guards: Reversible[Bool]
property jump_targets
property jump_sources
property descriptions: Reversible[str]
property bbl_addrs: Reversible[int]
property ins_addrs: Reversible[int]
property stack_actions
closest_common_ancestor(other)[源代码]

Find the common ancestor between this history node and 'other'.

参数:

other -- the PathHistory to find a common ancestor with.

返回:

the common ancestor SimStateHistory, or None if there isn't one

constraints_since(other)[源代码]

Returns the constraints that have been accumulated since other.

参数:

other -- a prior PathHistory object

返回:

a list of constraints

make_child()[源代码]
class angr.state_plugins.SimStateJNIReferences(local_refs=None, global_refs=None)[源代码]

基类:SimStatePlugin

Management of the mapping between opaque JNI references and the corresponding Java objects.

__init__(local_refs=None, global_refs=None)[源代码]
lookup(opaque_ref)[源代码]

Lookups the object that was used for creating the reference.

create_new_reference(obj, global_ref=False)[源代码]

Create a new reference thats maps to the given object.

参数:
  • obj -- Object which gets referenced.

  • global_ref (bool) -- Whether a local or global reference is created.

clear_local_references()[源代码]

Clear all local references.

delete_reference(opaque_ref, global_ref=False)[源代码]

Delete the stored mapping of a reference.

参数:
  • opaque_ref -- Reference which should be removed.

  • global_ref (bool) -- Whether opaque_ref is a local or global reference.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.SimStateLibc[源代码]

基类: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__()[源代码]
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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

property errno
ret_errno(val)[源代码]
class angr.state_plugins.SimStateLog(log=None)[源代码]

基类:SimStatePlugin

__init__(log=None)[源代码]
property actions
add_event(event_type, **kwargs)[源代码]
add_action(action)[源代码]
extend_actions(new_actions)[源代码]
events_of_type(event_type)[源代码]
actions_of_type(action_type)[源代码]
property fresh_constraints
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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

clear()[源代码]
class angr.state_plugins.SimStateLoopData(back_edge_trip_counts=None, header_trip_counts=None, current_loop=None)[源代码]

基类:SimStatePlugin

This class keeps track of loop-related information for states. Note that we have 2 counters for loop iterations (trip counts): the first recording the number of times one of the back edges (or continue edges) of a loop is taken, whereas the second recording the number of times the loop header (or loop entry) is executed. These 2 counters may differ since compilers usually optimize loops hence completely change the loop structure at the binary level. This is supposed to be used with LoopSeer exploration technique, which monitors loop execution. For the moment, the only thing we want to analyze is loop trip counts, but nothing prevents us from extending this plugin for other loop analyses.

__init__(back_edge_trip_counts=None, header_trip_counts=None, current_loop=None)[源代码]
参数:
  • back_edge_trip_counts -- Dictionary that stores back edge based trip counts for each loop. Keys are address of loop headers.

  • header_trip_counts -- Dictionary that stores header based trip counts for each loop. Keys are address of loop headers.

  • current_loop -- List of currently running loops. Each element is a tuple (loop object, list of loop exits).

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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!

参数:

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.SimStatePlugin[源代码]

基类: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__()[源代码]
state: SimState
set_state(state)[源代码]

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

set_strongref_state(state)[源代码]
copy(_memo)[源代码]

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!

参数:

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

static memo(f)[源代码]

A decorator function you should apply to copy

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

classmethod register_default(name, xtr=None)[源代码]
init_state()[源代码]

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

class angr.state_plugins.SimStatePreconstrainer(constrained_addrs=None)[源代码]

基类:SimStatePlugin

This state plugin manages the concept of preconstraining - adding constraints which you would like to remove later.

参数:

constrained_addrs -- SimActions for memory operations whose addresses should be constrained during crash analysis

__init__(constrained_addrs=None)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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!

参数:

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

preconstrain(value, variable)[源代码]

Add a preconstraint that variable == value to the state.

参数:
  • value -- The concrete value. Can be a bitvector or a bytestring or an integer.

  • variable -- The BVS to preconstrain.

preconstrain_file(content, simfile, set_length=False)[源代码]

Preconstrain the contents of a file.

参数:
  • content -- The content to preconstrain the file to. Can be a bytestring or a list thereof.

  • simfile -- The actual simfile to preconstrain

preconstrain_flag_page(magic_content)[源代码]

Preconstrain the data in the flag page.

参数:

magic_content -- The content of the magic page as a bytestring.

remove_preconstraints(to_composite_solver=True, simplify=True)[源代码]

Remove the preconstraints from the state.

If you are using the zen plugin, this will also use that to filter the constraints.

参数:
  • to_composite_solver -- Whether to convert the replacement solver to a composite solver. You probably want this if you're switching from tracing to symbolic analysis.

  • simplify -- Whether to simplify the resulting set of constraints.

reconstrain()[源代码]

Split the solver. If any of the subsolvers time out after a short timeout (10 seconds), re-add the preconstraints associated with each of its variables. Hopefully these constraints still allow us to do meaningful things to the state.

class angr.state_plugins.SimStateScratch(scratch=None)[源代码]

基类:SimStatePlugin

Implements the scratch state plugin.

__init__(scratch=None)[源代码]
property priv
push_priv(priv)[源代码]
pop_priv()[源代码]
set_tyenv(tyenv)[源代码]
tmp_expr(tmp)[源代码]

Returns the Claripy expression of a VEX temp value.

参数:
  • tmp -- the number of the tmp

  • simplify -- simplify the tmp before returning it

返回:

a Claripy expression of the tmp

store_tmp(tmp, content, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=None, **kwargs)[源代码]

Stores a Claripy expression in a VEX temp value. If in symbolic mode, this involves adding a constraint for the tmp's symbolic variable.

参数:
  • tmp -- the number of the tmp

  • content -- a Claripy expression of the content

  • reg_deps -- the register dependencies of the content

  • tmp_deps -- the temporary value dependencies of the content

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

clear()[源代码]
class angr.state_plugins.SimSymbolizer[源代码]

基类:SimStatePlugin

The symbolizer state plugin ensures that pointers that are stored in memory are symbolic. This allows for the tracking of and reasoning over these pointers (for example, to reason about memory disclosure).

__init__()[源代码]
init_state()[源代码]

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

set_symbolization_for_all_pages()[源代码]

Sets the symbolizer to symbolize pointers to all pages as they are written to memory..

set_symbolized_target_range(base, length)[源代码]

All pointers to the target range will be symbolized as they are written to memory.

Due to optimizations, the _pages_ containing this range will be set as symbolization targets, not just the range itself.

resymbolize()[源代码]

Re-symbolizes all pointers in memory. This can be called to symbolize any pointers to target regions that were written (and not mangled beyond recognition) before symbolization was set.

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!

参数:

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)[源代码]

基类: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)[源代码]
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!

参数:

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()[源代码]

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

set_brk(new_brk)[源代码]
set_state(state)[源代码]

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

open(name, flags, preferred_fd=None)[源代码]

Open a symbolic file. Basically open(2).

参数:
  • 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.

返回:

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)[源代码]
get_fd(fd, create_file=True)[源代码]

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)[源代码]

Same behavior as get_fd(fd), only the result is a concrete integer fd (or -1) instead of a SimFileDescriptor.

close(fd)[源代码]

Closes the given file descriptor (an AST). Returns whether the operation succeeded (a concrete boolean)

fstat(fd)[源代码]
fstat_with_result(sim_fd)[源代码]
sigmask(sigsetsize=None)[源代码]

Gets the current sigmask. If it's blank, a new one is created (of sigsetsize).

参数:

sigsetsize -- the size (in bytes of the sigmask set)

返回:

the sigmask

sigprocmask(how, new_mask, sigsetsize, valid_ptr=True)[源代码]

Updates the signal mask.

参数:
  • 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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

dump_file_by_path(path, **kwargs)[源代码]

Returns the concrete content for a file by path.

参数:
  • path -- file path as string

  • kwargs -- passed to state.solver.eval

返回:

file contents as string

dumps(fd, **kwargs)[源代码]

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.

参数:

fd -- A file descriptor.

返回:

The concrete content.

返回类型:

str

class angr.state_plugins.SimUCManager(man=None)[源代码]

基类:SimStatePlugin

__init__(man=None)[源代码]
assign(dst_addr_ast)[源代码]

Assign a new region for under-constrained symbolic execution.

参数:

dst_addr_ast -- the symbolic AST which address of the new allocated region will be assigned to.

返回:

as ast of memory address that points to a new region

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!

参数:

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

get_alloc_depth(addr)[源代码]
返回类型:

int | None

参数:

addr (int | Base)

set_alloc_depth(addr, depth)[源代码]
参数:
is_bounded(ast)[源代码]

Test whether an AST is bounded by any existing constraint in the related solver.

参数:

ast -- an claripy.AST object

返回:

True if there is at least one related constraint, False otherwise

set_state(state)[源代码]

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

class angr.state_plugins.Stat(st_dev, st_ino, st_nlink, st_mode, st_uid, st_gid, st_rdev, st_size, st_blksize, st_blocks, st_atime, st_atimensec, st_mtime, st_mtimensec, st_ctime, st_ctimensec)

基类:tuple

st_atime

Alias for field number 10

st_atimensec

Alias for field number 11

st_blksize

Alias for field number 8

st_blocks

Alias for field number 9

st_ctime

Alias for field number 14

st_ctimensec

Alias for field number 15

st_dev

Alias for field number 0

st_gid

Alias for field number 5

st_ino

Alias for field number 1

st_mode

Alias for field number 3

st_mtime

Alias for field number 12

st_mtimensec

Alias for field number 13

Alias for field number 2

st_rdev

Alias for field number 6

st_size

Alias for field number 7

st_uid

Alias for field number 4

class angr.state_plugins.StructMode(view)[源代码]

基类:object

__init__(view)[源代码]
class angr.state_plugins.Unicorn(syscall_hooks=None, cache_key=None, unicount=None, symbolic_var_counts=None, symbolic_inst_counts=None, concretized_asts=None, always_concretize=None, never_concretize=None, concretize_at=None, concretization_threshold_memory=None, concretization_threshold_registers=None, concretization_threshold_instruction=None, cooldown_symbolic_stop=2, cooldown_unsupported_stop=2, cooldown_nonunicorn_blocks=100, cooldown_stop_point=1, max_steps=1000000)[源代码]

基类:SimStatePlugin

setup the unicorn engine for a state

UC_CONFIG = {}
__init__(syscall_hooks=None, cache_key=None, unicount=None, symbolic_var_counts=None, symbolic_inst_counts=None, concretized_asts=None, always_concretize=None, never_concretize=None, concretize_at=None, concretization_threshold_memory=None, concretization_threshold_registers=None, concretization_threshold_instruction=None, cooldown_symbolic_stop=2, cooldown_unsupported_stop=2, cooldown_nonunicorn_blocks=100, cooldown_stop_point=1, max_steps=1000000)[源代码]

Initializes the Unicorn plugin for angr. This plugin handles communication with UnicornEngine.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

set_state(state)[源代码]

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

property uc
static delete_uc()[源代码]
set_last_block_details(details)[源代码]
set_stops(stop_points)[源代码]
set_tracking(track_bbls, track_stack)[源代码]
hook()[源代码]
uncache_region(addr, length)[源代码]
clear_page_cache()[源代码]
setup(syscall_data=None, fd_bytes=None)[源代码]
start(step=None)[源代码]
get_recent_bbl_addrs()[源代码]
get_stop_details()[源代码]
finish(succ_state)[源代码]
destroy(succ_state)[源代码]
set_regs()[源代码]

setting unicorn registers

setup_flags()[源代码]
setup_gdt(fs, gs)[源代码]
read_msr(msr=3221225728)[源代码]
write_msr(val, msr=3221225728)[源代码]
get_regs(succ_state)[源代码]

loading registers from unicorn. If succ_state is not None, update it instead of self.state. Needed when handling symbolic exits in native interface

angr.state_plugins.resource_event(state, exception)[源代码]
class angr.state_plugins.plugin.SimStatePlugin[源代码]

基类: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__()[源代码]
state: SimState
set_state(state)[源代码]

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

set_strongref_state(state)[源代码]
copy(_memo)[源代码]

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!

参数:

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

static memo(f)[源代码]

A decorator function you should apply to copy

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

classmethod register_default(name, xtr=None)[源代码]
init_state()[源代码]

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

class angr.state_plugins.inspect.BP(when='before', enabled=None, condition=None, action=None, **kwargs)[源代码]

基类:object

A breakpoint.

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

Checks state state to see if the breakpoint should fire.

参数:
  • state -- The state.

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

返回:

A boolean representing whether the checkpoint should fire.

fire(state)[源代码]

Trigger the breakpoint.

参数:

state -- The state.

class angr.state_plugins.inspect.SimInspector[源代码]

基类: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__()[源代码]
action(event_type, when, **kwargs)[源代码]

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)[源代码]

Creates and adds a breakpoint which would trigger on event_type. Additional arguments are passed to the BP constructor.

返回:

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.

返回:

The created breakpoint, so that it can be removed later.

add_breakpoint(event_type, bp)[源代码]

Adds a breakpoint which would trigger on event_type.

参数:
  • event_type -- The event type to trigger on

  • bp -- The breakpoint

返回:

The created breakpoint.

remove_breakpoint(event_type, bp=None, filter_func=None)[源代码]

Removes a breakpoint.

参数:
  • 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!

参数:

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

downsize()[源代码]

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

set_state(state)[源代码]

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

state: angr.SimState
class angr.state_plugins.libc.SimStateLibc[源代码]

基类: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__()[源代码]
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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

property errno
ret_errno(val)[源代码]
state: angr.SimState
class angr.state_plugins.posix.PosixDevFS[源代码]

基类:SimMount

get(path)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(_)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

copy(_)[源代码]

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!

参数:

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.posix.PosixProcFS[源代码]

基类:SimMount

The virtual file system mounted at /proc (as of now, on Linux).

get(path)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(_)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

copy(_)[源代码]

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!

参数:

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.posix.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)[源代码]

基类: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)[源代码]
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!

参数:

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()[源代码]

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

set_brk(new_brk)[源代码]
set_state(state)[源代码]

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

open(name, flags, preferred_fd=None)[源代码]

Open a symbolic file. Basically open(2).

参数:
  • 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.

返回:

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)[源代码]
get_fd(fd, create_file=True)[源代码]

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)[源代码]

Same behavior as get_fd(fd), only the result is a concrete integer fd (or -1) instead of a SimFileDescriptor.

close(fd)[源代码]

Closes the given file descriptor (an AST). Returns whether the operation succeeded (a concrete boolean)

fstat(fd)[源代码]
fstat_with_result(sim_fd)[源代码]
sigmask(sigsetsize=None)[源代码]

Gets the current sigmask. If it's blank, a new one is created (of sigsetsize).

参数:

sigsetsize -- the size (in bytes of the sigmask set)

返回:

the sigmask

sigprocmask(how, new_mask, sigsetsize, valid_ptr=True)[源代码]

Updates the signal mask.

参数:
  • 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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

dump_file_by_path(path, **kwargs)[源代码]

Returns the concrete content for a file by path.

参数:
  • path -- file path as string

  • kwargs -- passed to state.solver.eval

返回:

file contents as string

dumps(fd, **kwargs)[源代码]

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.

参数:

fd -- A file descriptor.

返回:

The concrete content.

返回类型:

str

state: angr.SimState
class angr.state_plugins.filesystem.Stat(st_dev, st_ino, st_nlink, st_mode, st_uid, st_gid, st_rdev, st_size, st_blksize, st_blocks, st_atime, st_atimensec, st_mtime, st_mtimensec, st_ctime, st_ctimensec)

基类:tuple

st_atime

Alias for field number 10

st_atimensec

Alias for field number 11

st_blksize

Alias for field number 8

st_blocks

Alias for field number 9

st_ctime

Alias for field number 14

st_ctimensec

Alias for field number 15

st_dev

Alias for field number 0

st_gid

Alias for field number 5

st_ino

Alias for field number 1

st_mode

Alias for field number 3

st_mtime

Alias for field number 12

st_mtimensec

Alias for field number 13

Alias for field number 2

st_rdev

Alias for field number 6

st_size

Alias for field number 7

st_uid

Alias for field number 4

class angr.state_plugins.filesystem.SimFilesystem(files=None, pathsep=None, cwd=None, mountpoints=None)[源代码]

基类:SimStatePlugin

angr's emulated filesystem. Available as state.fs. When constructing, all parameters are optional.

参数:
  • files -- A mapping from filepath to SimFile

  • pathsep -- The character used to separate path elements, default forward slash.

  • cwd -- The path of the current working directory to use

  • mountpoints -- A mapping from filepath to SimMountpoint

变量:
  • pathsep -- The current pathsep

  • cwd -- The current working directory

  • unlinks -- A list of unlink operations, tuples of filename and simfile. Be careful, this list is shallow-copied from successor to successor, so don't mutate anything in it without copying.

__init__(files=None, pathsep=None, cwd=None, mountpoints=None)[源代码]
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!

参数:

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

set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

chdir(path)[源代码]

Changes the current directory to the given path

get(path)[源代码]

Get a file from the filesystem. Returns a SimFile or None.

insert(path, simfile)[源代码]

Insert a file into the filesystem. Returns whether the operation was successful.

delete(path)[源代码]

Remove a file from the filesystem. Returns whether the operation was successful.

This will add a fs_unlink event with the path of the file and also the index into the unlinks list.

mount(path, mount)[源代码]

Add a mountpoint to the filesystem.

unmount(path)[源代码]

Remove a mountpoint from the filesystem.

get_mountpoint(path)[源代码]

Look up the mountpoint servicing the given path.

返回:

A tuple of the mount and a list of path elements traversing from the mountpoint to the specified file.

class angr.state_plugins.filesystem.SimMount[源代码]

基类: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)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path_elements, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path_elements)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(sim_file)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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

class angr.state_plugins.filesystem.SimConcreteFilesystem(pathsep='/')[源代码]

基类:SimMount

Abstract SimMount allowing the user to import files from some external source into the guest

参数:

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

__init__(pathsep='/')[源代码]
get(path_elements)[源代码]

Implement this function to instrument file lookups.

参数:

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

返回:

A SimFile, or None

insert(path_elements, simfile)[源代码]

Implement this function to instrument file creation.

参数:
  • path_elements -- A list of path elements traversing from the mountpoint to the file

  • simfile -- The file to insert

返回:

A bool indicating whether the insert occurred

delete(path_elements)[源代码]

Implement this function to instrument file deletion.

参数:

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

返回:

A bool indicating whether the delete occurred

lookup(sim_file)[源代码]

Look up the path of a SimFile in the mountpoint

参数:

sim_file -- A SimFile object needs to be looked up

返回:

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

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!

参数:

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

set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.filesystem.SimHostFilesystem(host_path=None, **kwargs)[源代码]

基类:SimConcreteFilesystem

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

参数:
  • 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)[源代码]
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!

参数:

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

angr.state_plugins.solver.timed_function(f)[源代码]
angr.state_plugins.solver.enable_timing()[源代码]
angr.state_plugins.solver.disable_timing()[源代码]
angr.state_plugins.solver.error_converter(f)[源代码]
angr.state_plugins.solver.concrete_path_bool(f)[源代码]
angr.state_plugins.solver.concrete_path_not_bool(f)[源代码]
angr.state_plugins.solver.concrete_path_scalar(f)[源代码]
angr.state_plugins.solver.concrete_path_tuple(f)[源代码]
angr.state_plugins.solver.concrete_path_list(f)[源代码]
class angr.state_plugins.solver.SimSolver(solver=None, all_variables=None, temporal_tracked_variables=None, eternal_tracked_variables=None)[源代码]

基类: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)[源代码]
reload_solver(constraints=None)[源代码]

Reloads the solver. Useful when changing solver options.

参数:

constraints (list) -- A new list of constraints to use in the reloaded solver instead of the current one

get_variables(*keys)[源代码]

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)[源代码]

Register a value with the variable tracking system

参数:
  • 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)[源代码]

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)[源代码]

Creates an unconstrained symbol or a default concrete value (0), based on the state options.

参数:
  • 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.

返回:

an unconstrained symbol (or a concrete value of 0).

BVS(name, size, min=None, max=None, stride=None, uninitialized=False, explicit_name=False, key=None, eternal=False, inspect=True, events=True, **kwargs)[源代码]

Creates a bit-vector symbol (i.e., a variable). Other keyword parameters are passed directly on to the constructor of claripy.ast.BV.

参数:
  • 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

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

downsize()[源代码]

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)[源代码]

Evaluate an expression, using the solver if necessary. Returns AST objects.

参数:
  • e -- the expression

  • n -- the number of desired solutions

  • extra_constraints -- extra constraints to apply to the solver

  • exact -- if False, returns approximate solutions

返回:

a tuple of the solutions, in the form of claripy AST nodes

返回类型:

tuple

max(e, extra_constraints=(), exact=None, signed=False)[源代码]

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)[源代码]

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)[源代码]

Return True if v is a solution of expr with the extra constraints, False otherwise.

参数:
  • 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.

返回:

True if v is a solution of expr, False otherwise

is_true(e, extra_constraints=(), exact=None)[源代码]

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.

参数:
  • 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.

返回:

True if v is definitely true, False otherwise

is_false(e, extra_constraints=(), exact=None)[源代码]

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.

参数:
  • 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.

返回:

True if v is definitely false, False otherwise

unsat_core(extra_constraints=())[源代码]

This function returns the unsat core from the backend solver.

参数:

extra_constraints -- Extra constraints (as ASTs) to add to the solver for this solve.

返回:

The unsat core.

satisfiable(extra_constraints=(), exact=None)[源代码]

This function does a constraint check and checks if the solver is in a sat state.

参数:
  • extra_constraints -- Extra constraints (as ASTs) to add to s for this solve

  • exact -- If False, return approximate solutions.

返回:

True if sat, otherwise false

add(*constraints)[源代码]

Add some constraints to the solver.

参数:

constraints -- Pass any constraints that you want to add (ASTs) as varargs.

CastType = ~CastType
eval_upto(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression, using the solver if necessary. Returns primitives as specified by the cast_to parameter. Only certain primitives are supported, check the implementation of _cast_to to see which ones.

参数:
  • e -- the expression

  • n -- the number of desired solutions

  • extra_constraints -- extra constraints to apply to the solver

  • exact -- if False, returns approximate solutions

  • cast_to -- desired type of resulting values

返回:

a tuple of the solutions, in the form of Python primitives

返回类型:

tuple

eval(e, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get any possible solution. The desired output types can be specified using the cast_to parameter. extra_constraints can be used to specify additional constraints the returned values must satisfy.

参数:
  • e -- the expression to get a solution for

  • kwargs -- Any additional kwargs will be passed down to eval_upto

  • cast_to -- desired type of resulting values

抛出:

SimUnsatError -- if no solution could be found satisfying the given constraints

返回:

state: angr.SimState
eval_one(e, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get the only possible solution. Errors if either no or more than one solution is returned. A kwarg parameter default can be specified to be returned instead of failure!

参数:
  • e -- the expression to get a solution for

  • cast_to -- desired type of resulting values

  • default -- A value can be passed as a kwarg here. It will be returned in case of failure.

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if more than one solution was found to satisfy the given constraints

返回:

The value for e

eval_atmost(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get at most n possible solutions. Errors if either none or more than n solutions are returned.

参数:
  • e -- the expression to get a solution for

  • n -- the inclusive upper limit on the number of solutions

  • cast_to -- desired type of resulting values

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if more than n solutions were found to satisfy the given constraints

返回:

The solutions for e

eval_atleast(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get at least n possible solutions. Errors if less than n solutions were found.

参数:
  • e -- the expression to get a solution for

  • n -- the inclusive lower limit on the number of solutions

  • cast_to -- desired type of resulting values

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if less than n solutions were found to satisfy the given constraints

返回:

The solutions for e

eval_exact(e, n, cast_to=None, **kwargs)[源代码]

Evaluate an expression to get exactly the n possible solutions. Errors if any number of solutions other than n was found to exist.

参数:
  • e -- the expression to get a solution for

  • n -- the inclusive lower limit on the number of solutions

  • cast_to -- desired type of resulting values

  • kwargs -- Any additional kwargs will be passed down to eval_upto

抛出:
  • SimUnsatError -- if no solution could be found satisfying the given constraints

  • SimValueError -- if any number of solutions other than n were found to satisfy the given constraints

返回:

The solutions for e

min_int(e, extra_constraints=(), exact=None, signed=False)

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)

max_int(e, extra_constraints=(), exact=None, signed=False)

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)

unique(e, **kwargs)[源代码]

Returns True if the expression e has only one solution by querying the constraint solver. It does also add that unique solution to the solver's constraints.

symbolic(e)[源代码]

Returns True if the expression e is symbolic.

single_valued(e)[源代码]

Returns True whether e is a concrete value or is a value set with only 1 possible value. This differs from unique in that this does not query the constraint solver.

simplify(e=None)[源代码]

Simplifies e. If e is None, simplifies the constraints of this state.

variables(e)[源代码]

Returns the symbolic variables present in the AST of e.

class angr.state_plugins.log.SimStateLog(log=None)[源代码]

基类:SimStatePlugin

__init__(log=None)[源代码]
property actions
add_event(event_type, **kwargs)[源代码]
add_action(action)[源代码]
extend_actions(new_actions)[源代码]
events_of_type(event_type)[源代码]
actions_of_type(action_type)[源代码]
property fresh_constraints
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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

clear()[源代码]
class angr.state_plugins.callstack.CallStack(call_site_addr=0, func_addr=0, stack_ptr=0, ret_addr=0, jumpkind='Ijk_Call', next_frame=None, invoke_return_variable=None)[源代码]

基类:SimStatePlugin

Stores the address of the function you're in and the value of SP at the VERY BOTTOM of the stack, i.e. points to the return address.

参数:

next_frame (CallStack | None)

__init__(call_site_addr=0, func_addr=0, stack_ptr=0, ret_addr=0, jumpkind='Ijk_Call', next_frame=None, invoke_return_variable=None)[源代码]
参数:

next_frame (CallStack | None)

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!

参数:

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

set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

property current_function_address

Address of the current function.

返回:

the address of the function

返回类型:

int

property current_stack_pointer

Get the value of the stack pointer.

返回:

Value of the stack pointer

返回类型:

int

property current_return_target

Get the return target.

返回:

The address of return target.

返回类型:

int

static stack_suffix_to_string(stack_suffix)[源代码]

Convert a stack suffix to a human-readable string representation. :param tuple stack_suffix: The stack suffix. :return: A string representation :rtype: str

property top

Returns the element at the top of the callstack without removing it.

返回:

A CallStack.

push(cf)[源代码]

Push the frame cf onto the stack. Return the new stack.

pop()[源代码]

Pop the top frame from the stack. Return the new stack.

call(callsite_addr, addr, retn_target=None, stack_pointer=None)[源代码]

Push a stack frame into the call stack. This method is called when calling a function in CFG recovery.

参数:
  • callsite_addr (int) -- Address of the call site

  • addr (int) -- Address of the call target

  • retn_target (int or None) -- Address of the return target

  • stack_pointer (int) -- Value of the stack pointer

返回:

None

ret(retn_target=None)[源代码]

Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery.

参数:

retn_target (int) -- The target to return to.

返回:

None

dbg_repr()[源代码]

Debugging representation of this CallStack object.

返回:

Details of this CalLStack

返回类型:

str

stack_suffix(context_sensitivity_level)[源代码]

Generate the stack suffix. A stack suffix can be used as the key to a SimRun in CFG recovery.

参数:

context_sensitivity_level (int) -- Level of context sensitivity.

返回:

A tuple of stack suffix.

返回类型:

tuple

class angr.state_plugins.callstack.CallStackAction(callstack_hash, callstack_depth, action, callframe=None, ret_site_addr=None)[源代码]

基类:object

Used in callstack backtrace, which is a history of callstacks along a path, to record individual actions occurred each time the callstack is changed.

__init__(callstack_hash, callstack_depth, action, callframe=None, ret_site_addr=None)[源代码]
class angr.state_plugins.light_registers.SimLightRegisters(reg_map=None, registers=None)[源代码]

基类:SimStatePlugin

__init__(reg_map=None, registers=None)[源代码]
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!

参数:

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

set_state(state)[源代码]

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

resolve_register(offset, size)[源代码]
load(offset, size=None, **kwargs)[源代码]
store(offset, value, size=None, endness=None, **kwargs)[源代码]
class angr.state_plugins.history.SimStateHistory(parent=None, clone=None)[源代码]

基类:SimStatePlugin

This class keeps track of historically-relevant information for paths.

STRONGREF_STATE = True
__init__(parent=None, clone=None)[源代码]
jump_guard: claripy.ast.BV | None
jumpkind: str | None
init_state()[源代码]

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

set_strongref_state(state)[源代码]
property addr
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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!

参数:

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

trim()[源代码]

Discard the ancestry of this state.

filter_actions(start_block_addr=None, end_block_addr=None, block_stmt=None, insn_addr=None, read_from=None, write_to=None)[源代码]

Filter self.actions based on some common parameters.

[start_block_addr, end_block_addr]

参数:
  • start_block_addr -- Only return actions generated in blocks starting at this address.

  • end_block_addr -- Only return actions generated in blocks ending at this address.

  • block_stmt -- Only return actions generated in the nth statement of each block.

  • insn_addr -- Only return actions generated in the assembly instruction at this address.

  • read_from -- Only return actions that perform a read from the specified location.

  • write_to -- Only return actions that perform a write to the specified location.

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

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

demote()[源代码]

Demotes this history node, causing it to drop the strong state reference.

reachable()[源代码]
add_event(event_type, **kwargs)[源代码]
add_action(action)[源代码]
extend_actions(new_actions)[源代码]
subscribe_actions()[源代码]
property recent_constraints
property recent_actions
property block_count
property lineage
property parents
property events: Reversible[SimEvent]
property actions: Reversible[SimAction]
property jumpkinds: Reversible[str]
property jump_guards: Reversible[Bool]
property jump_targets
property jump_sources
property descriptions: Reversible[str]
property bbl_addrs: Reversible[int]
property ins_addrs: Reversible[int]
property stack_actions
closest_common_ancestor(other)[源代码]

Find the common ancestor between this history node and 'other'.

参数:

other -- the PathHistory to find a common ancestor with.

返回:

the common ancestor SimStateHistory, or None if there isn't one

constraints_since(other)[源代码]

Returns the constraints that have been accumulated since other.

参数:

other -- a prior PathHistory object

返回:

a list of constraints

make_child()[源代码]
state: angr.SimState
class angr.state_plugins.history.TreeIter(start, end=None)[源代码]

基类:object

__init__(start, end=None)[源代码]
property hardcopy
count(v)[源代码]

Count occurrences of value v in the entire history. Note that the subclass must implement the __reversed__ method, otherwise an exception will be thrown. :param object v: The value to look for :return: The number of occurrences :rtype: int

class angr.state_plugins.history.HistoryIter(start, end=None)[源代码]

基类:TreeIter

class angr.state_plugins.history.LambdaAttrIter(start, f, **kwargs)[源代码]

基类:TreeIter

__init__(start, f, **kwargs)[源代码]
class angr.state_plugins.history.LambdaIterIter(start, f, reverse=True, **kwargs)[源代码]

基类:LambdaAttrIter

__init__(start, f, reverse=True, **kwargs)[源代码]
class angr.state_plugins.gdb.GDB(omit_fp=False, adjust_stack=False)[源代码]

基类:SimStatePlugin

Initialize or update a state from gdb dumps of the stack, heap, registers and data (or arbitrary) segments.

__init__(omit_fp=False, adjust_stack=False)[源代码]
参数:
  • omit_fp -- The frame pointer register is used for something else. (i.e. --omit_frame_pointer)

  • adjust_stack -- Use different stack addresses than the gdb session (not recommended).

set_stack(stack_dump, stack_top)[源代码]

Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command :

dump binary memory [stack_dump] [begin_addr] [end_addr]

We set the stack to the same addresses as the gdb session to avoid pointers corruption.

参数:
  • stack_dump -- The dump file.

  • stack_top -- The address of the top of the stack in the gdb session.

set_heap(heap_dump, heap_base)[源代码]

Heap dump is a dump of the heap from gdb, i.e. the result of the following gdb command:

dump binary memory [stack_dump] [begin] [end]

参数:
  • heap_dump -- The dump file.

  • heap_base -- The start address of the heap in the gdb session.

set_data(addr, data_dump)[源代码]

Update any data range (most likely use is the data segments of loaded objects)

set_regs(regs_dump)[源代码]

Initialize register values within the state

参数:

regs_dump -- The output of info registers in gdb.

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!

参数:

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.cgc.SimStateCGC[源代码]

基类:SimStatePlugin

This state plugin keeps track of CGC state.

EBADF = 1
EFAULT = 2
EINVAL = 3
ENOMEM = 4
ENOSYS = 5
EPIPE = 6
FD_SETSIZE = 1024
max_allocation = 268435456
__init__()[源代码]
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!

参数:

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

peek_input()[源代码]
discard_input(num_bytes)[源代码]
peek_output()[源代码]
discard_output(num_bytes)[源代码]
addr_invalid(a)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

get_max_sinkhole(length)[源代码]

Find a sinkhole which is large enough to support length bytes.

This uses first-fit. The first sinkhole (ordered in descending order by their address) which can hold length bytes is chosen. If there are more than length bytes in the sinkhole, a new sinkhole is created representing the remaining bytes while the old sinkhole is removed.

add_sinkhole(address, length)[源代码]

Add a sinkhole.

Allow the possibility for the program to reuse the memory represented by the address length pair.

state: angr.SimState

This file contains objects to track additional information during a trace or modify symbolic variables during a trace.

The ChallRespInfo plugin tracks variables in stdin and stdout to enable handling of challenge response It handles atoi/int2str in a special manner since path constraints will usually prevent their values from being modified

The Zen plugin simplifies expressions created from variables in the flag page (losing some accuracy) to avoid situations where they become to complex for z3, but the actual equation doesn't matter much. This can happen in challenge response if all of the values in the flag page are multiplied together before being printed.

class angr.state_plugins.trace_additions.FormatInfo[源代码]

基类:object

copy()[源代码]
compute(state)[源代码]
get_type()[源代码]
class angr.state_plugins.trace_additions.FormatInfoStrToInt(addr, func_name, str_arg_num, base, base_arg, allows_negative)[源代码]

基类:FormatInfo

__init__(addr, func_name, str_arg_num, base, base_arg, allows_negative)[源代码]
copy()[源代码]
compute(state)[源代码]
get_type()[源代码]
class angr.state_plugins.trace_additions.FormatInfoIntToStr(addr, func_name, int_arg_num, str_dst_num, base, base_arg)[源代码]

基类:FormatInfo

__init__(addr, func_name, int_arg_num, str_dst_num, base, base_arg)[源代码]
copy()[源代码]
compute(state)[源代码]
get_type()[源代码]
class angr.state_plugins.trace_additions.FormatInfoDontConstrain(addr, func_name, check_symbolic_arg)[源代码]

基类:FormatInfo

__init__(addr, func_name, check_symbolic_arg)[源代码]
copy()[源代码]
compute(state)[源代码]
get_type()[源代码]
angr.state_plugins.trace_additions.int2base(x, base)[源代码]
angr.state_plugins.trace_additions.generic_info_hook(state)[源代码]
angr.state_plugins.trace_additions.end_info_hook(state)[源代码]
angr.state_plugins.trace_additions.exit_hook(state)[源代码]
angr.state_plugins.trace_additions.syscall_hook(state)[源代码]
angr.state_plugins.trace_additions.constraint_hook(state)[源代码]
class angr.state_plugins.trace_additions.ChallRespInfo[源代码]

基类:SimStatePlugin

This state plugin keeps track of the reads and writes to symbolic addresses

__init__()[源代码]
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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

static get_byte(var_name)[源代码]
lookup_original(replacement)[源代码]
pop_from_backup()[源代码]
get_stdin_indices(variable)[源代码]
get_stdout_indices(variable)[源代码]
get_real_len(input_val, base, result_bv, allows_negative)[源代码]
get_possible_len(input_val, base, allows_negative)[源代码]
get_same_length_constraints()[源代码]
static atoi_dumps(state, require_same_length=True)[源代码]
static prep_tracer(state, format_infos=None)[源代码]
angr.state_plugins.trace_additions.zen_hook(state, expr)[源代码]
angr.state_plugins.trace_additions.zen_memory_write(state)[源代码]
angr.state_plugins.trace_additions.zen_register_write(state)[源代码]
class angr.state_plugins.trace_additions.ZenPlugin(max_depth=13)[源代码]

基类:SimStatePlugin

__init__(max_depth=13)[源代码]
static get_flag_rand_args(expr)[源代码]
get_expr_depth(expr)[源代码]
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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

get_flag_bytes(ast)[源代码]
filter_constraints(constraints)[源代码]
analyze_transmit(state, buf)[源代码]
static prep_tracer(state)[源代码]
class angr.state_plugins.globals.SimStateGlobals(backer=None)[源代码]

基类:SimStatePlugin

__init__(backer=None)[源代码]
set_state(state)[源代码]

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

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

keys()[源代码]
values()[源代码]
items()[源代码]
get(k, alt=None)[源代码]
pop(k, alt=None)[源代码]
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!

参数:

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.uc_manager.SimUCManager(man=None)[源代码]

基类:SimStatePlugin

__init__(man=None)[源代码]
assign(dst_addr_ast)[源代码]

Assign a new region for under-constrained symbolic execution.

参数:

dst_addr_ast -- the symbolic AST which address of the new allocated region will be assigned to.

返回:

as ast of memory address that points to a new region

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!

参数:

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

get_alloc_depth(addr)[源代码]
返回类型:

int | None

参数:

addr (int | Base)

set_alloc_depth(addr, depth)[源代码]
参数:
is_bounded(ast)[源代码]

Test whether an AST is bounded by any existing constraint in the related solver.

参数:

ast -- an claripy.AST object

返回:

True if there is at least one related constraint, False otherwise

set_state(state)[源代码]

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

class angr.state_plugins.scratch.SimStateScratch(scratch=None)[源代码]

基类:SimStatePlugin

Implements the scratch state plugin.

__init__(scratch=None)[源代码]
property priv
push_priv(priv)[源代码]
pop_priv()[源代码]
set_tyenv(tyenv)[源代码]
tmp_expr(tmp)[源代码]

Returns the Claripy expression of a VEX temp value.

参数:
  • tmp -- the number of the tmp

  • simplify -- simplify the tmp before returning it

返回:

a Claripy expression of the tmp

store_tmp(tmp, content, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=None, **kwargs)[源代码]

Stores a Claripy expression in a VEX temp value. If in symbolic mode, this involves adding a constraint for the tmp's symbolic variable.

参数:
  • tmp -- the number of the tmp

  • content -- a Claripy expression of the content

  • reg_deps -- the register dependencies of the content

  • tmp_deps -- the temporary value dependencies of the content

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

clear()[源代码]
class angr.state_plugins.preconstrainer.SimStatePreconstrainer(constrained_addrs=None)[源代码]

基类:SimStatePlugin

This state plugin manages the concept of preconstraining - adding constraints which you would like to remove later.

参数:

constrained_addrs -- SimActions for memory operations whose addresses should be constrained during crash analysis

__init__(constrained_addrs=None)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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!

参数:

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

preconstrain(value, variable)[源代码]

Add a preconstraint that variable == value to the state.

参数:
  • value -- The concrete value. Can be a bitvector or a bytestring or an integer.

  • variable -- The BVS to preconstrain.

preconstrain_file(content, simfile, set_length=False)[源代码]

Preconstrain the contents of a file.

参数:
  • content -- The content to preconstrain the file to. Can be a bytestring or a list thereof.

  • simfile -- The actual simfile to preconstrain

preconstrain_flag_page(magic_content)[源代码]

Preconstrain the data in the flag page.

参数:

magic_content -- The content of the magic page as a bytestring.

remove_preconstraints(to_composite_solver=True, simplify=True)[源代码]

Remove the preconstraints from the state.

If you are using the zen plugin, this will also use that to filter the constraints.

参数:
  • to_composite_solver -- Whether to convert the replacement solver to a composite solver. You probably want this if you're switching from tracing to symbolic analysis.

  • simplify -- Whether to simplify the resulting set of constraints.

reconstrain()[源代码]

Split the solver. If any of the subsolvers time out after a short timeout (10 seconds), re-add the preconstraints associated with each of its variables. Hopefully these constraints still allow us to do meaningful things to the state.

class angr.state_plugins.unicorn_engine.MEM_PATCH[源代码]

基类:Structure

struct mem_update_t

address

Structure/Union member

length

Structure/Union member

next

Structure/Union member

class angr.state_plugins.unicorn_engine.TRANSMIT_RECORD[源代码]

基类:Structure

struct transmit_record_t

count

Structure/Union member

data

Structure/Union member

fd

Structure/Union member

class angr.state_plugins.unicorn_engine.TaintEntityEnum[源代码]

基类:object

taint_entity_enum_t

TAINT_ENTITY_REG = 0
TAINT_ENTITY_TMP = 1
TAINT_ENTITY_MEM = 2
TAINT_ENTITY_NONE = 3
class angr.state_plugins.unicorn_engine.MemoryValue[源代码]

基类:Structure

struct memory_value_t

address

Structure/Union member

is_value_set

Structure/Union member

is_value_symbolic

Structure/Union member

value

Structure/Union member

class angr.state_plugins.unicorn_engine.RegisterValue[源代码]

基类:Structure

struct register_value_t

offset

Structure/Union member

size

Structure/Union member

value

Structure/Union member

class angr.state_plugins.unicorn_engine.VEXStmtDetails[源代码]

基类:Structure

struct sym_vex_stmt_details_t

has_memory_dep

Structure/Union member

memory_values

Structure/Union member

memory_values_count

Structure/Union member

stmt_idx

Structure/Union member

class angr.state_plugins.unicorn_engine.BlockDetails[源代码]

基类:Structure

struct sym_block_details_ret_t

block_addr

Structure/Union member

block_size

Structure/Union member

block_trace_ind

Structure/Union member

has_symbolic_exit

Structure/Union member

register_values

Structure/Union member

register_values_count

Structure/Union member

symbolic_vex_stmts

Structure/Union member

symbolic_vex_stmts_count

Structure/Union member

class angr.state_plugins.unicorn_engine.STOP[源代码]

基类:object

enum stop_t

STOP_NORMAL = 0
STOP_STOPPOINT = 1
STOP_ERROR = 2
STOP_SYSCALL = 3
STOP_EXECNONE = 4
STOP_ZEROPAGE = 5
STOP_NOSTART = 6
STOP_SEGFAULT = 7
STOP_ZERO_DIV = 8
STOP_NODECODE = 9
STOP_HLT = 10
STOP_VEX_LIFT_FAILED = 11
STOP_SYMBOLIC_PC = 12
STOP_SYMBOLIC_READ_ADDR = 13
STOP_SYMBOLIC_READ_SYMBOLIC_TRACKING_DISABLED = 14
STOP_SYMBOLIC_WRITE_ADDR = 15
STOP_SYMBOLIC_BLOCK_EXIT_CONDITION = 16
STOP_SYMBOLIC_BLOCK_EXIT_TARGET = 17
STOP_UNSUPPORTED_STMT_PUTI = 18
STOP_UNSUPPORTED_STMT_STOREG = 19
STOP_UNSUPPORTED_STMT_LOADG = 20
STOP_UNSUPPORTED_STMT_CAS = 21
STOP_UNSUPPORTED_STMT_LLSC = 22
STOP_UNSUPPORTED_STMT_DIRTY = 23
STOP_UNSUPPORTED_EXPR_GETI = 24
STOP_UNSUPPORTED_STMT_UNKNOWN = 25
STOP_UNSUPPORTED_EXPR_UNKNOWN = 26
STOP_UNKNOWN_MEMORY_WRITE_SIZE = 27
STOP_SYSCALL_ARM = 28
STOP_X86_CPUID = 29
stop_message = {0: 'Reached maximum steps', 1: 'Hit a stop point', 2: 'Something wrong', 3: 'Unable to handle syscall', 4: 'Fetching empty page', 5: 'Accessing zero page', 6: 'Failed to start', 7: 'Permissions or mapping error', 8: 'Divide by zero', 9: 'Instruction decoding error', 10: 'hlt instruction encountered', 11: 'Failed to lift block to VEX', 12: 'Instruction pointer became symbolic', 13: 'Attempted to read from symbolic address', 14: 'Attempted to read symbolic data from memory but symbolic tracking is disabled', 15: 'Attempted to write to symbolic address', 16: "Guard condition of block's exit statement is symbolic", 17: 'Target of default exit of block is symbolic', 18: 'Symbolic taint propagation for PutI statement not yet supported', 19: 'Symbolic taint propagation for StoreG statement not yet supported', 20: 'Symbolic taint propagation for LoadG statement not yet supported', 21: 'Symbolic taint propagation for CAS statement not yet supported', 22: 'Symbolic taint propagation for LLSC statement not yet supported', 23: 'Symbolic taint propagation for Dirty statement not yet supported', 24: 'Symbolic taint propagation for GetI expression not yet supported', 25: 'Canoo propagate symbolic taint for unsupported VEX statement type', 26: 'Cannot propagate symbolic taint for unsupported VEX expression', 27: 'Unicorn failed to determine size of memory write', 28: 'ARM syscalls are currently not supported by SimEngineUnicorn', 29: 'Block executes cpuid which should be handled in VEX engine'}
symbolic_stop_reasons = {12, 13, 14, 15, 16, 17, 28, 29}
unsupported_reasons = {11, 18, 19, 20, 21, 22, 23, 25, 26}
static name_stop(num)[源代码]
static get_stop_msg(stop_reason)[源代码]
class angr.state_plugins.unicorn_engine.StopDetails[源代码]

基类:Structure

struct stop_details_t

block_addr

Structure/Union member

block_size

Structure/Union member

stop_reason

Structure/Union member

class angr.state_plugins.unicorn_engine.SimOSEnum[源代码]

基类:object

enum simos_t

SIMOS_CGC = 0
SIMOS_LINUX = 1
SIMOS_OTHER = 2
exception angr.state_plugins.unicorn_engine.MemoryMappingError[源代码]

基类:Exception

exception angr.state_plugins.unicorn_engine.AccessingZeroPageError[源代码]

基类:MemoryMappingError

exception angr.state_plugins.unicorn_engine.FetchingZeroPageError[源代码]

基类:MemoryMappingError

exception angr.state_plugins.unicorn_engine.SegfaultError[源代码]

基类:MemoryMappingError

exception angr.state_plugins.unicorn_engine.MixedPermissonsError[源代码]

基类:MemoryMappingError

class angr.state_plugins.unicorn_engine.AggressiveConcretizationAnnotation(addr)[源代码]

基类:SimplificationAvoidanceAnnotation

__init__(addr)[源代码]
class angr.state_plugins.unicorn_engine.Uniwrapper(arch, cache_key, thumb=False)[源代码]

基类:Uc

__init__(arch, cache_key, thumb=False)[源代码]
hook_add(htype, callback, user_data=None, begin=1, end=0, arg1=0)[源代码]
hook_del(h)[源代码]
mem_map(addr, size, perms=7)[源代码]
mem_map_ptr(addr, size, perms, ptr)[源代码]
mem_unmap(addr, size)[源代码]
mem_reset()[源代码]
hook_reset()[源代码]
reset()[源代码]
class angr.state_plugins.unicorn_engine.Unicorn(syscall_hooks=None, cache_key=None, unicount=None, symbolic_var_counts=None, symbolic_inst_counts=None, concretized_asts=None, always_concretize=None, never_concretize=None, concretize_at=None, concretization_threshold_memory=None, concretization_threshold_registers=None, concretization_threshold_instruction=None, cooldown_symbolic_stop=2, cooldown_unsupported_stop=2, cooldown_nonunicorn_blocks=100, cooldown_stop_point=1, max_steps=1000000)[源代码]

基类:SimStatePlugin

setup the unicorn engine for a state

UC_CONFIG = {}
__init__(syscall_hooks=None, cache_key=None, unicount=None, symbolic_var_counts=None, symbolic_inst_counts=None, concretized_asts=None, always_concretize=None, never_concretize=None, concretize_at=None, concretization_threshold_memory=None, concretization_threshold_registers=None, concretization_threshold_instruction=None, cooldown_symbolic_stop=2, cooldown_unsupported_stop=2, cooldown_nonunicorn_blocks=100, cooldown_stop_point=1, max_steps=1000000)[源代码]

Initializes the Unicorn plugin for angr. This plugin handles communication with UnicornEngine.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

set_state(state)[源代码]

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

property uc
static delete_uc()[源代码]
set_last_block_details(details)[源代码]
set_stops(stop_points)[源代码]
set_tracking(track_bbls, track_stack)[源代码]
hook()[源代码]
uncache_region(addr, length)[源代码]
clear_page_cache()[源代码]
setup(syscall_data=None, fd_bytes=None)[源代码]
start(step=None)[源代码]
get_recent_bbl_addrs()[源代码]
get_stop_details()[源代码]
finish(succ_state)[源代码]
destroy(succ_state)[源代码]
set_regs()[源代码]

setting unicorn registers

setup_flags()[源代码]
setup_gdt(fs, gs)[源代码]
read_msr(msr=3221225728)[源代码]
write_msr(val, msr=3221225728)[源代码]
get_regs(succ_state)[源代码]

loading registers from unicorn. If succ_state is not None, update it instead of self.state. Needed when handling symbolic exits in native interface

state: angr.SimState
class angr.state_plugins.loop_data.SimStateLoopData(back_edge_trip_counts=None, header_trip_counts=None, current_loop=None)[源代码]

基类:SimStatePlugin

This class keeps track of loop-related information for states. Note that we have 2 counters for loop iterations (trip counts): the first recording the number of times one of the back edges (or continue edges) of a loop is taken, whereas the second recording the number of times the loop header (or loop entry) is executed. These 2 counters may differ since compilers usually optimize loops hence completely change the loop structure at the binary level. This is supposed to be used with LoopSeer exploration technique, which monitors loop execution. For the moment, the only thing we want to analyze is loop trip counts, but nothing prevents us from extending this plugin for other loop analyses.

__init__(back_edge_trip_counts=None, header_trip_counts=None, current_loop=None)[源代码]
参数:
  • back_edge_trip_counts -- Dictionary that stores back edge based trip counts for each loop. Keys are address of loop headers.

  • header_trip_counts -- Dictionary that stores header based trip counts for each loop. Keys are address of loop headers.

  • current_loop -- List of currently running loops. Each element is a tuple (loop object, list of loop exits).

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

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!

参数:

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.javavm_classloader.SimJavaVmClassloader(initialized_classes=None)[源代码]

基类:SimStatePlugin

JavaVM Classloader is used as an interface for resolving and initializing Java classes.

__init__(initialized_classes=None)[源代码]
get_class(class_name, init_class=False, step_func=None)[源代码]

Get a class descriptor for the class.

参数:
  • class_name (str) -- Name of class.

  • init_class (bool) -- Whether the class initializer <clinit> should be executed.

  • step_func (func) -- Callback function executed at every step of the simulation manager during the execution of the main <clinit> method

get_superclass(class_)[源代码]

Get the superclass of the class.

get_class_hierarchy(base_class)[源代码]

Walks up the class hierarchy and returns a list of all classes between base class (inclusive) and java.lang.Object (exclusive).

is_class_initialized(class_)[源代码]

Indicates whether the classes initializing method <clinit> was already executed on the state.

init_class(class_, step_func=None)[源代码]

This method simulates the loading of a class by the JVM, during which parts of the class (e.g. static fields) are initialized. For this, we run the class initializer method <clinit> (if available) and update the state accordingly.

Note: Initialization is skipped, if the class has already been

initialized (or if it's not loaded in CLE).

property initialized_classes

List of all initialized classes.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.jni_references.SimStateJNIReferences(local_refs=None, global_refs=None)[源代码]

基类:SimStatePlugin

Management of the mapping between opaque JNI references and the corresponding Java objects.

__init__(local_refs=None, global_refs=None)[源代码]
lookup(opaque_ref)[源代码]

Lookups the object that was used for creating the reference.

create_new_reference(obj, global_ref=False)[源代码]

Create a new reference thats maps to the given object.

参数:
  • obj -- Object which gets referenced.

  • global_ref (bool) -- Whether a local or global reference is created.

clear_local_references()[源代码]

Clear all local references.

delete_reference(opaque_ref, global_ref=False)[源代码]

Delete the stored mapping of a reference.

参数:
  • opaque_ref -- Reference which should be removed.

  • global_ref (bool) -- Whether opaque_ref is a local or global reference.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.heap.PTChunk(base, sim_state, heap=None)[源代码]

基类: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

变量:
  • 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)[源代码]
get_size()[源代码]

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

get_data_size()[源代码]

Returns the size of the data portion of a chunk.

set_size(size, is_free=None)[源代码]

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.

参数:
  • size -- size of the chunk

  • is_free -- boolean indicating the chunk's freeness

set_prev_freeness(is_free)[源代码]

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

参数:

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

is_prev_free()[源代码]

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.

返回:

True if the previous chunk is free; False otherwise

prev_size()[源代码]

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()[源代码]

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

data_ptr()[源代码]

Returns the address of the payload of the chunk.

next_chunk()[源代码]

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

返回:

The following chunk, or None if applicable

prev_chunk()[源代码]

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.

返回:

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

fwd_chunk()[源代码]

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.

返回:

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

set_fwd_chunk(fwd)[源代码]

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

参数:

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

bck_chunk()[源代码]

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.

返回:

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

set_bck_chunk(bck)[源代码]

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

参数:

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

class angr.state_plugins.heap.PTChunkIterator(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]

基类:object

__init__(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]
class angr.state_plugins.heap.SimHeapBase(heap_base=None, heap_size=None)[源代码]

基类:SimStatePlugin

This is the base heap class that all heap implementations should subclass. It defines a few handlers for common heap functions (the libc memory management functions). Heap implementations are expected to override these functions regardless of whether they implement the SimHeapLibc interface. For an example, see the SimHeapBrk implementation, which is based on the original libc SimProcedure implementations.

变量:
  • 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

__init__(heap_base=None, heap_size=None)[源代码]
copy(memo)[源代码]

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!

参数:

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

init_state()[源代码]

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

class angr.state_plugins.heap.SimHeapBrk(heap_base=None, heap_size=None)[源代码]

基类: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).

变量:

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)[源代码]
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!

参数:

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

allocate(sim_size)[源代码]

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.

参数:

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

返回:

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

release(sim_size)[源代码]

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.

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.heap.SimHeapLibc(heap_base=None, heap_size=None)[源代码]

基类:SimHeapBase

A class of heap that implements the major libc heap management functions.

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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

class angr.state_plugins.heap.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]

基类: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.

变量:
  • 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)[源代码]
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!

参数:

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

chunks()[源代码]

Returns an iterator over all the chunks in the heap.

allocated_chunks()[源代码]

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

free_chunks()[源代码]

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

chunk_from_mem(ptr)[源代码]

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.

参数:

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

返回:

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

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

init_state()[源代码]

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

class angr.state_plugins.heap.heap_base.SimHeapBase(heap_base=None, heap_size=None)[源代码]

基类:SimStatePlugin

This is the base heap class that all heap implementations should subclass. It defines a few handlers for common heap functions (the libc memory management functions). Heap implementations are expected to override these functions regardless of whether they implement the SimHeapLibc interface. For an example, see the SimHeapBrk implementation, which is based on the original libc SimProcedure implementations.

变量:
  • 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

__init__(heap_base=None, heap_size=None)[源代码]
copy(memo)[源代码]

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!

参数:

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

init_state()[源代码]

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

class angr.state_plugins.heap.heap_brk.SimHeapBrk(heap_base=None, heap_size=None)[源代码]

基类: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).

变量:

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)[源代码]
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!

参数:

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

allocate(sim_size)[源代码]

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.

参数:

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

返回:

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

release(sim_size)[源代码]

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.

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.state_plugins.heap.heap_freelist.Chunk(base, sim_state)[源代码]

基类:object

The sort of chunk as would typically be found in a freelist-style heap implementation. Provides a representation of a chunk via a view into the memory plugin. Chunks may be adjacent, in different senses, to as many as four other chunks. For any given chunk, two of these chunks are adjacent to it in memory, and are referred to as the "previous" and "next" chunks throughout this implementation. For any given free chunk, there may also be two significant chunks that are adjacent to it in some linked list of free chunks. These chunks are referred to the "backward" and "forward" chunks relative to the chunk in question.

变量:
  • base -- the location of the base of the chunk in memory

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

__init__(base, sim_state)[源代码]
get_size()[源代码]

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

get_data_size()[源代码]

Returns the size of the data portion of a chunk.

set_size(size)[源代码]

Sets the size of the chunk, preserving any flags.

data_ptr()[源代码]

Returns the address of the payload of the chunk.

is_free()[源代码]

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

next_chunk()[源代码]

Returns the chunk immediately following (and adjacent to) this one.

prev_chunk()[源代码]

Returns the chunk immediately prior (and adjacent) to this one.

fwd_chunk()[源代码]

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

set_fwd_chunk(fwd)[源代码]

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

参数:

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

bck_chunk()[源代码]

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

set_bck_chunk(bck)[源代码]

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

参数:

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

class angr.state_plugins.heap.heap_freelist.SimHeapFreelist(heap_base=None, heap_size=None)[源代码]

基类:SimHeapLibc

A freelist-style heap implementation. Distinguishing features of such heaps include chunks containing heap metadata in addition to user data and at least (but often more than) one linked list of free chunks.

chunks()[源代码]

Returns an iterator over all the chunks in the heap.

allocated_chunks()[源代码]

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

free_chunks()[源代码]

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

chunk_from_mem(ptr)[源代码]

Given a pointer to a user payload, return the chunk associated with that payload.

参数:

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

返回:

the associated heap chunk

print_heap_state()[源代码]
print_all_chunks()[源代码]
class angr.state_plugins.heap.heap_libc.SimHeapLibc(heap_base=None, heap_size=None)[源代码]

基类:SimHeapBase

A class of heap that implements the major libc heap management functions.

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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

class angr.state_plugins.heap.heap_ptmalloc.PTChunk(base, sim_state, heap=None)[源代码]

基类: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

变量:
  • 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)[源代码]
get_size()[源代码]

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

get_data_size()[源代码]

Returns the size of the data portion of a chunk.

set_size(size, is_free=None)[源代码]

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.

参数:
  • size -- size of the chunk

  • is_free -- boolean indicating the chunk's freeness

set_prev_freeness(is_free)[源代码]

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

参数:

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

is_prev_free()[源代码]

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.

返回:

True if the previous chunk is free; False otherwise

prev_size()[源代码]

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()[源代码]

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

data_ptr()[源代码]

Returns the address of the payload of the chunk.

next_chunk()[源代码]

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

返回:

The following chunk, or None if applicable

prev_chunk()[源代码]

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.

返回:

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

fwd_chunk()[源代码]

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.

返回:

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

set_fwd_chunk(fwd)[源代码]

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

参数:

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

bck_chunk()[源代码]

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.

返回:

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

set_bck_chunk(bck)[源代码]

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

参数:

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

class angr.state_plugins.heap.heap_ptmalloc.PTChunkIterator(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]

基类:object

__init__(chunk, cond=<function PTChunkIterator.<lambda>>)[源代码]
class angr.state_plugins.heap.heap_ptmalloc.SimHeapPTMalloc(heap_base=None, heap_size=None)[源代码]

基类: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.

变量:
  • 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)[源代码]
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!

参数:

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

chunks()[源代码]

Returns an iterator over all the chunks in the heap.

allocated_chunks()[源代码]

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

free_chunks()[源代码]

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

chunk_from_mem(ptr)[源代码]

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.

参数:

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

返回:

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

malloc(sim_size)[源代码]

A somewhat faithful implementation of libc malloc.

参数:

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

返回:

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

free(ptr)[源代码]

A somewhat faithful implementation of libc free.

参数:

ptr -- the location in memory to be freed

calloc(sim_nmemb, sim_size)[源代码]

A somewhat faithful implementation of libc calloc.

参数:
  • sim_nmemb -- the number of elements to allocated

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

返回:

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

realloc(ptr, size)[源代码]

A somewhat faithful implementation of libc realloc.

参数:
  • ptr -- the location in memory to be reallocated

  • size -- the new size desired for the allocation

返回:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

init_state()[源代码]

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

angr.state_plugins.heap.utils.concretize(x, solver, sym_handler)[源代码]

For now a lot of naive concretization is done when handling heap metadata to keep things manageable. This idiom showed up a lot as a result, so to reduce code repetition this function uses a callback to handle the one or two operations that varied across invocations.

参数:
  • x -- the item to be concretized

  • solver -- the solver to evaluate the item with

  • sym_handler -- the handler to be used when the item may take on more than one value

返回:

a concrete value for the item

class angr.state_plugins.symbolizer.SimSymbolizer[源代码]

基类:SimStatePlugin

The symbolizer state plugin ensures that pointers that are stored in memory are symbolic. This allows for the tracking of and reasoning over these pointers (for example, to reason about memory disclosure).

__init__()[源代码]
init_state()[源代码]

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

set_symbolization_for_all_pages()[源代码]

Sets the symbolizer to symbolize pointers to all pages as they are written to memory..

set_symbolized_target_range(base, length)[源代码]

All pointers to the target range will be symbolized as they are written to memory.

Due to optimizations, the _pages_ containing this range will be set as symbolization targets, not just the range itself.

resymbolize()[源代码]

Re-symbolizes all pointers in memory. This can be called to symbolize any pointers to target regions that were written (and not mangled beyond recognition) before symbolization was set.

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!

参数:

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.debug_variables.SimDebugVariable(state, addr, var_type)[源代码]

基类:object

A SimDebugVariable will get dynamically created when queriyng for variable in a state with the SimDebugVariablePlugin. It features a link to the state, an address and a type.

参数:
__init__(state, addr, var_type)[源代码]
参数:
static from_cle_variable(state, cle_variable, dwarf_cfa)[源代码]
返回类型:

SimDebugVariable

参数:
property mem_untyped: SimMemView
property mem: SimMemView
property string: SimMemView
with_type(sim_type)[源代码]
返回类型:

SimMemView

参数:

sim_type (SimType)

property resolvable
property resolved
property concrete
store(value)[源代码]
property deref: SimDebugVariable
array(i)[源代码]
返回类型:

SimDebugVariable

member(member_name)[源代码]
返回类型:

SimDebugVariable

参数:

member_name (str)

class angr.state_plugins.debug_variables.SimDebugVariablePlugin[源代码]

基类:SimStatePlugin

This is the plugin you'll use to interact with (global/local) program variables. These variables have a name and a visibility scope which depends on the pc address of the state. With this plugin, you can access/modify the value of such variable or find its memory address. For creating program variables, or for importing them from cle, see the knowledge plugin debug_variables. Run p.kb.dvars.load_from_dwarf() before using this plugin.

示例

>>> p = angr.Project("various_variables", load_debug_info=True)
>>> p.kb.dvars.load_from_dwarf()
>>> state =  # navigate to the state you want
>>> state.dvars.get_variable("pointer2").deref.mem
<int (32 bits) <BV32 0x1> at 0x404020>
get_variable(var_name)[源代码]

Returns the visible variable (if any) with name var_name based on the current state.ip.

返回类型:

SimDebugVariable

参数:

var_name (str)

property dwarf_cfa

Returns the current cfa computation. Set this property to the correct value if needed.

property dwarf_cfa_approx

Storage

class angr.storage.DefaultMemory(*args, **kwargs)[源代码]

基类:HexDumperMixin, SmartFindMixin, UnwrapperMixin, NameResolutionMixin, DataNormalizationMixin, SimplificationMixin, InspectMixinHigh, ActionsMixinHigh, UnderconstrainedMixin, SizeConcretizationMixin, SizeNormalizationMixin, AddressConcretizationMixin, ActionsMixinLow, ConditionalMixin, ConvenientMappingsMixin, DirtyAddrsMixin, StackAllocationMixin, ConcreteBackerMixin, ClemoryBackerMixin, DictBackerMixin, PrivilegedPagingMixin, UltraPagesMixin, DefaultFillerMixin, SymbolicMergerMixin, PagedMemoryMixin

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

基类: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.

参数:
  • 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.

变量:

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)[源代码]
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)[源代码]

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)[源代码]

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

read(pos, size, **kwargs)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.storage.SimMemoryObject(obj, base, endness, length=None, byte_width=8)[源代码]

基类:object

A SimMemoryObject is a reference to a byte or several bytes in a specific object in memory. It should be used only by the bottom layer of memory.

__init__(obj, base, endness, length=None, byte_width=8)[源代码]
is_bytes
base
object: BV | FP
length
endness
size()[源代码]
property variables
property symbolic
property last_addr
concrete_bytes(offset, size)[源代码]
返回类型:

bytes | None

参数:
includes(x)[源代码]
bytes_at(addr, length, allow_concrete=False, endness='Iend_BE')[源代码]
class angr.state_plugins.view.SimRegNameView[源代码]

基类:SimStatePlugin

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

get(reg_name)[源代码]
class angr.state_plugins.view.SimMemView(ty=None, addr=None, state=None)[源代码]

基类:SimStatePlugin

This is a convenient interface with which you can access a program's memory.

The interface works like this:

  • You first use [array index notation] to specify the address you'd like to load from

  • If at that address is a pointer, you may access the deref property to return a SimMemView at the address present in memory.

  • You then specify a type for the data by simply accessing a property of that name. For a list of supported types, look at state.mem.types.

  • You can then refine the type. Any type may support any refinement it likes. Right now the only refinements supported are that you may access any member of a struct by its member name, and you may index into a string or array to access that element.

  • If the address you specified initially points to an array of that type, you can say .array(n) to view the data as an array of n elements.

  • Finally, extract the structured data with .resolved or .concrete. .resolved will return bitvector values, while .concrete will return integer, string, array, etc values, whatever best represents the data.

  • Alternately, you may store a value to memory, by assigning to the chain of properties that you've constructed. Note that because of the way python works, x = s.mem[...].prop; x = val will NOT work, you must say s.mem[...].prop = val.

For example:

>>> s.mem[0x601048].long
<long (64 bits) <BV64 0x4008d0> at 0x601048>
>>> s.mem[0x601048].long.resolved
<BV64 0x4008d0>
>>> s.mem[0x601048].deref
<<untyped> <unresolvable> at 0x4008d0>
>>> s.mem[0x601048].deref.string.concrete
'SOSNEAKY'
__init__(ty=None, addr=None, state=None)[源代码]
set_state(state)[源代码]

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

types: ClassVar[dict] = {'CharT': char, 'FILE_t': struct FILE_t, '_Bool': bool, '_ENTRY': struct _ENTRY, '_IO_codecvt': struct _IO_codecvt, '_IO_iconv_t': struct _IO_iconv_t, '_IO_lock_t': struct pthread_mutex_t, '_IO_marker': struct _IO_marker, '_IO_wide_data': struct _IO_wide_data, '__clock_t': uint32_t, '__dev_t': uint64_t, '__gid_t': unsigned int, '__ino64_t': unsigned long long, '__ino_t': unsigned long, '__int128': int128_t, '__int256': int256_t, '__mbstate_t': struct __mbstate_t, '__mode_t': unsigned int, '__nlink_t': unsigned int, '__off64_t': long long, '__off_t': long, '__pid_t': int, '__suseconds_t': int64_t, '__time_t': long, '__uid_t': unsigned int, '_obstack_chunk': struct _obstack_chunk, 'aiocb': struct aiocb, 'aiocb64': struct aiocb64, 'aioinit': struct aioinit, 'argp': struct argp, 'argp_child': struct argp_child, 'argp_option': struct argp_option, 'argp_parser_t': (int, char*, struct argp_state*) -> int, 'argp_state': struct argp_state, 'basic_string': string_t, 'bool': bool, 'byte': uint8_t, 'cc_t': char, 'char': char, 'clock_t': uint32_t, 'crypt_data': struct crypt_data, 'dirent': struct dirent, 'dirent64': struct dirent64, 'double': double, 'drand48_data': struct <anon>, 'dword': uint32_t, 'error_t': int, 'exit_status': struct exit_status, 'float': float, 'fstab': struct fstab, 'group': struct group, 'hostent': struct hostent, 'hsearch_data': struct hsearch_data, 'if_nameindex': struct if_nameindex, 'in_addr': struct in_addr, 'in_port_t': uint16_t, 'ino64_t': unsigned long long, 'ino_t': unsigned long, 'int': int, 'int16_t': int16_t, 'int32_t': int32_t, 'int64_t': int64_t, 'int8_t': int8_t, 'iovec': struct <anon>, 'itimerval': struct itimerval, 'lconv': struct lconv, 'long': long, 'long double': double, 'long int': long, 'long long': long long, 'long long int': long long, 'long signed': long, 'long unsigned int': unsigned long, 'mallinfo': struct mallinfo, 'mallinfo2': struct mallinfo2, 'mntent': struct mntent, 'netent': struct netent, 'ntptimeval': struct ntptimeval, 'obstack': struct obstack, 'off64_t': long long, 'off_t': long, 'option': struct option, 'passwd': struct passwd, 'pid_t': int, 'printf_info': struct printf_info, 'protoent': struct protoent, 'ptrdiff_t': long, 'qword': uint64_t, 'random_data': struct <anon>, 'rlim64_t': uint64_t, 'rlim_t': unsigned long, 'rlimit': struct rlimit, 'rlimit64': struct rlimit64, 'rusage': struct rusage, 'sa_family_t': unsigned short, 'sched_param': struct sched_param, 'sembuf': struct sembuf, 'servent': struct servent, 'sgttyb': struct sgttyb, 'short': short, 'short int': short, 'sigevent': struct sigevent, 'signed': int, 'signed char': char, 'signed int': int, 'signed long': long, 'signed long int': long, 'signed long long': long long, 'signed long long int': long long, 'signed short': short, 'signed short int': short, 'sigstack': struct sigstack, 'sigval': union sigval { sival_int int; sival_ptr void*; }, 'size_t': size_t, 'sockaddr': struct sockaddr, 'sockaddr_in': struct sockaddr_in, 'speed_t': long, 'ssize': size_t, 'ssize_t': size_t, 'stat': struct stat, 'stat64': struct stat64, 'string': string_t, 'struct iovec': struct iovec, 'struct timespec': struct timespec, 'struct timeval': struct timeval, 'tcflag_t': unsigned long, 'termios': struct termios, 'time_t': long, 'timespec': struct timeval, 'timeval': struct timeval, 'timex': struct timex, 'timezone': struct timezone, 'tm': struct tm, 'tms': struct tms, 'uint16_t': uint16_t, 'uint32_t': uint32_t, 'uint64_t': uint64_t, 'uint8_t': uint8_t, 'uintptr_t': unsigned long, 'unsigned': unsigned int, 'unsigned __int128': uint128_t, 'unsigned __int256': uint256_t, 'unsigned char': char, 'unsigned int': unsigned int, 'unsigned long': unsigned long, 'unsigned long int': unsigned long, 'unsigned long long': unsigned long long, 'unsigned long long int': unsigned long long, 'unsigned short': unsigned short, 'unsigned short int': unsigned short, 'utimbuf': struct utimbuf, 'utmp': struct utmp, 'utmpx': struct utmx, 'utsname': struct utsname, 'va_list': struct va_list[1], 'void': void, 'vtimes': struct vtimes, 'wchar_t': short, 'winsize': struct winsize, 'word': uint16_t, 'wstring': wstring_t}
state: angr.SimState = None
struct: StructMode
with_type(sim_type)[源代码]

Returns a copy of the SimMemView with a type.

参数:

sim_type (SimType) -- The new type.

返回类型:

SimMemView

返回:

The typed SimMemView copy.

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

property resolvable
property resolved
property concrete
property deref: SimMemView
array(n)[源代码]
返回类型:

SimMemView

member(member_name)[源代码]

If self is a struct and member_name is a member of the struct, return that member element. Otherwise raise an exception.

返回类型:

SimMemView

参数:

member_name (str)

store(value)[源代码]
class angr.state_plugins.view.StructMode(view)[源代码]

基类:object

__init__(view)[源代码]
class angr.storage.file.Flags[源代码]

基类:object

O_RDONLY = 0
O_WRONLY = 1
O_RDWR = 2
O_ACCMODE = 3
O_APPEND = 1024
O_ASYNC = 8192
O_CLOEXEC = 524288
O_CREAT = 64
O_DIRECT = 16384
O_DIRECTORY = 65536
O_DSYNC = 4096
O_EXCL = 128
O_LARGEFILE = 32768
O_NOATIME = 262144
O_NOCTTY = 256
O_NOFOLLOW = 131072
O_NONBLOCK = 2048
O_NDELAY = 2048
O_PATH = 2097152
O_SYNC = 1052672
O_TMPFILE = 4259840
O_TRUNC = 512
class angr.storage.file.SimFileBase(name=None, writable=True, ident=None, concrete=False, file_exists=True, **kwargs)[源代码]

基类: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.

变量:
  • 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)[源代码]
static make_ident(name)[源代码]
concretize(**kwargs)[源代码]

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)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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

state: angr.SimState
class angr.storage.file.SimFile(name=None, content=None, size=None, has_end=None, seekable=True, writable=True, ident=None, concrete=None, **kwargs)[源代码]

基类: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.

参数:
  • 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.

变量:

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)[源代码]
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)[源代码]

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)[源代码]

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

read(pos, size, **kwargs)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.storage.file.SimFileStream(name=None, content=None, pos=0, **kwargs)[源代码]

基类: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.

参数:
  • 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.

变量:

pos -- The current position in the file.

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

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

read(pos, size, **kwargs)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

class angr.storage.file.SimPackets(name, write_mode=None, content=None, writable=True, ident=None, **kwargs)[源代码]

基类: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.

参数:
  • 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.

变量:
  • 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)[源代码]
set_state(state)[源代码]

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)[源代码]

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

read(pos, size, **kwargs)[源代码]

Read a packet from the stream.

参数:
  • 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.

返回:

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)[源代码]

Write a packet to the stream.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.storage.file.SimPacketsStream(name, pos=0, **kwargs)[源代码]

基类: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.

参数:
  • 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.

变量:

pos -- The current position in the file.

__init__(name, pos=0, **kwargs)[源代码]
read(pos, size, **kwargs)[源代码]

Read a packet from the stream.

参数:
  • 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.

返回:

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)[源代码]

Write a packet to the stream.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

class angr.storage.file.SimFileDescriptorBase[源代码]

基类:SimStatePlugin

The base class for implementations of POSIX file descriptors.

All file descriptors should respect the CONCRETIZE_SYMBOLIC_{READ,WRITE}_SIZES state options.

read(pos, size, **kwargs)[源代码]

Reads some data from the file, storing it into memory.

参数:
  • pos -- The address to read data from file

  • size -- The requested length of the read

返回:

The real length of the read

write(pos, size, **kwargs)[源代码]

Writes some data, loaded from the state, into the file.

参数:
  • pos -- The address to read the data to write from in memory

  • size -- The requested size of the write

返回:

The real length of the write

read_data(size, **kwargs)[源代码]

Reads some data from the file, returning the data.

参数:

size -- The requested length of the read

返回:

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

write_data(data, size=None, **kwargs)[源代码]

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

参数:
  • data -- A bitvector to write into the file

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

返回:

The real length of the write

seek(offset, whence='start')[源代码]

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

参数:
  • 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"

返回:

A symbolic boolean describing whether the seek succeeded or not

tell()[源代码]

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

eof()[源代码]

Return the EOF status. May be a symbolic boolean.

size()[源代码]

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.

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.

concretize(**kwargs)[源代码]

Return a concretizeation of the data in the underlying file. Has different return types to represent different data structures on a per-class basis.

Any arguments passed to this will be passed onto state.solver.eval.

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.

class angr.storage.file.SimFileDescriptor(simfile, flags=0)[源代码]

基类: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.

变量:
  • 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)[源代码]
read_data(size, **kwargs)[源代码]

Reads some data from the file, returning the data.

参数:

size -- The requested length of the read

返回:

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

write_data(data, size=None, **kwargs)[源代码]

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

参数:
  • data -- A bitvector to write into the file

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

返回:

The real length of the write

seek(offset, whence='start')[源代码]

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

参数:
  • 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"

返回:

A symbolic boolean describing whether the seek succeeded or not

eof()[源代码]

Return the EOF status. May be a symbolic boolean.

tell()[源代码]

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

size()[源代码]

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)[源代码]

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)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.storage.file.SimFileDescriptorDuplex(read_file, write_file)[源代码]

基类: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.

参数:
  • read_file -- The SimFile to read from

  • write_file -- The SimFile to write to

__init__(read_file, write_file)[源代码]
read_data(size, **kwargs)[源代码]

Reads some data from the file, returning the data.

参数:

size -- The requested length of the read

返回:

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

write_data(data, size=None, **kwargs)[源代码]

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

参数:
  • data -- A bitvector to write into the file

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

返回:

The real length of the write

set_state(state)[源代码]

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

eof()[源代码]

Return the EOF status. May be a symbolic boolean.

tell()[源代码]

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

seek(offset, whence='start')[源代码]

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

参数:
  • 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"

返回:

A symbolic boolean describing whether the seek succeeded or not

size()[源代码]

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)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.storage.file.SimPacketsSlots(name, read_sizes, ident=None, **kwargs)[源代码]

基类:SimFileBase

SimPacketsSlots is the new SimDialogue, if you've ever seen that before.

The idea is that in some cases, the only thing you really care about is getting the lengths of reads right, and some of them should be short reads, and some of them should be truncated. You provide to this class a list of read lengths, and it figures out the length of each read, and delivers some content.

This class will NOT respect the position argument you pass it - this storage is not stateless.

seekable = False
__init__(name, read_sizes, ident=None, **kwargs)[源代码]
concretize(**kwargs)[源代码]

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)[源代码]

Read some data from the file.

参数:
  • pos -- The offset in the file to read from.

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

返回:

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)[源代码]

Write some data to the file.

参数:
  • 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.

返回:

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(_)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

angr.storage.memory_object.obj_bit_size(o)[源代码]
class angr.storage.memory_object.SimMemoryObject(obj, base, endness, length=None, byte_width=8)[源代码]

基类:object

A SimMemoryObject is a reference to a byte or several bytes in a specific object in memory. It should be used only by the bottom layer of memory.

__init__(obj, base, endness, length=None, byte_width=8)[源代码]
is_bytes
base
object: BV | FP
length
endness
size()[源代码]
property variables
property symbolic
property last_addr
concrete_bytes(offset, size)[源代码]
返回类型:

bytes | None

参数:
includes(x)[源代码]
bytes_at(addr, length, allow_concrete=False, endness='Iend_BE')[源代码]
class angr.storage.memory_object.SimLabeledMemoryObject(obj, base, endness, length=None, byte_width=8, label=None)[源代码]

基类:SimMemoryObject

SimLabeledMemoryObject is a SimMemoryObject with a label

__init__(obj, base, endness, length=None, byte_width=8, label=None)[源代码]
label
angr.storage.memory_object.bv_slice(value, offset, size, rev, bw)[源代码]

Extremely cute utility to pretend you've serialized a value to stored bytes, sliced it a la python slicing, and then deserialized those bytes to an integer again.

参数:
  • value (BV) -- The bitvector to slice

  • offset (int) -- The byte offset from the first stored byte to slice from, or a negative offset from the end.

  • size (int) -- The number of bytes to return. If None, return all bytes from the offset to the end. If larger than the number of bytes from the offset to the end, return all bytes from the offset to the end.

  • rev (bool) -- Whether the pretend-serialization should be little-endian

  • bw (int) -- The byte width

返回类型:

BV

返回:

The new bitvector

class angr.concretization_strategies.SimConcretizationStrategy(filter=None, exact=True)[源代码]

基类:object

Concretization strategies control the resolution of symbolic memory indices in SimuVEX. By subclassing this class and setting it as a concretization strategy (on state.memory.read_strategies and state.memory.write_strategies), SimuVEX's memory index concretization behavior can be modified.

__init__(filter=None, exact=True)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

concretize(memory, addr, **kwargs)[源代码]

Concretizes the address into a list of values. If this strategy cannot handle this address, returns None.

copy()[源代码]

Returns a copy of the strategy, if there is data that should be kept separate between states. If not, returns self.

merge(others)[源代码]

Merges this strategy with others (if there is data that should be kept separate between states. If not, is a no-op.

class angr.concretization_strategies.SimConcretizationStrategyAny(filter=None, exact=True)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that returns any single solution.

class angr.concretization_strategies.SimConcretizationStrategyControlledData(limit, fixed_addrs, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that constraints the address to controlled data. Controlled data consists of symbolic data and the addresses given as arguments. memory.

__init__(limit, fixed_addrs, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.SimConcretizationStrategyEval(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves an address into some limited number of solutions. Always handles the concretization, but only returns a maximum of limit number of solutions. Therefore, should only be used as the fallback strategy.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.SimConcretizationStrategyMax(max_addr=None)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that returns the maximum address.

参数:

max_addr (int | None)

__init__(max_addr=None)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

  • max_addr (int | None)

class angr.concretization_strategies.SimConcretizationStrategyNonzero(filter=None, exact=True)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that returns any non-zero solution.

class angr.concretization_strategies.SimConcretizationStrategyNonzeroRange(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves a range in a non-zero location.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.SimConcretizationStrategyNorepeats(repeat_expr, repeat_constraints=None, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves addresses, without repeating.

__init__(repeat_expr, repeat_constraints=None, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

copy()[源代码]

Returns a copy of the strategy, if there is data that should be kept separate between states. If not, returns self.

merge(others)[源代码]

Merges this strategy with others (if there is data that should be kept separate between states. If not, is a no-op.

class angr.concretization_strategies.SimConcretizationStrategyNorepeatsRange(repeat_expr, min=None, granularity=None, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves a range, with no repeats.

__init__(repeat_expr, min=None, granularity=None, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

copy()[源代码]

Returns a copy of the strategy, if there is data that should be kept separate between states. If not, returns self.

merge(others)[源代码]

Merges this strategy with others (if there is data that should be kept separate between states. If not, is a no-op.

class angr.concretization_strategies.SimConcretizationStrategyRange(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves addresses to a range.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.SimConcretizationStrategySingle(filter=None, exact=True)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that ensures a single solution for an address.

class angr.concretization_strategies.SimConcretizationStrategySolutions(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves an address into some limited number of solutions.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.SimConcretizationStrategyUnlimitedRange(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves addresses to a range without checking if the number of possible addresses is within the limit.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

Memory Mixins

class angr.storage.memory_mixins.AbstractMemory(*args, **kwargs)[源代码]

基类:UnwrapperMixin, NameResolutionMixin, DataNormalizationMixin, SimplificationMixin, InspectMixinHigh, ActionsMixinHigh, UnderconstrainedMixin, SizeConcretizationMixin, SizeNormalizationMixin, ActionsMixinLow, ConditionalMixin, RegionedAddressConcretizationMixin, RegionedMemoryMixin

class angr.storage.memory_mixins.AbstractMergerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

AbstractMergerMixin handles merging initialized values.

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.ActionsMixinHigh(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, condition=None, fallback=None, disable_actions=False, action=None, **kwargs)[源代码]
store(addr, data, size=None, *, disable_actions=False, action=None, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.ActionsMixinLow(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, action=None, **kwargs)[源代码]
store(addr, data, size=None, *, action=None, **kwargs)[源代码]
参数:

action (SimActionData | None)

class angr.storage.memory_mixins.AddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]

基类:MemoryMixin

The address concretization mixin allows symbolic reads and writes to be handled sanely by dispatching them as a number of conditional concrete reads/writes. It provides a "concretization strategies" interface allowing the process of serializing symbolic addresses into concrete ones to be specified.

__init__(read_strategies=None, write_strategies=None, **kwargs)[源代码]
set_state(state)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

concretize_write_addr(addr, strategies=None, condition=None)[源代码]

Concretizes an address meant for writing.

参数:
  • addr -- An expression for the address.

  • strategies -- A list of concretization strategies (to override the default).

  • condition -- Any extra constraints that should be observed when determining address satisfiability

返回:

A list of concrete addresses.

concretize_read_addr(addr, strategies=None, condition=None)[源代码]

Concretizes an address meant for reading.

参数:
  • addr -- An expression for the address.

  • strategies -- A list of concretization strategies (to override the default).

返回:

A list of concrete addresses.

load(addr, size=None, *, condition=None, **kwargs)[源代码]
store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
permissions(addr, permissions=None, **kwargs)[源代码]
map_region(addr, length, permissions, **kwargs)[源代码]
unmap_region(addr, length, **kwargs)[源代码]
concrete_load(addr, size, writing=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

返回:

A memoryview into the loaded bytes.

class angr.storage.memory_mixins.ClemoryBackerMixin(cle_memory_backer=None, **kwargs)[源代码]

基类:PagedMemoryMixin

参数:

cle_memory_backer (None | cle.Loader | cle.Clemory)

__init__(cle_memory_backer=None, **kwargs)[源代码]
参数:

cle_memory_backer (None | Loader | Clemory)

copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.ConcreteBackerMixin(cle_memory_backer=None, **kwargs)[源代码]

基类:ClemoryBackerMixin

参数:

cle_memory_backer (None | cle.Loader | cle.Clemory)

class angr.storage.memory_mixins.ConditionalMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, condition=None, fallback=None, **kwargs)[源代码]
store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.ConvenientMappingsMixin(**kwargs)[源代码]

基类:MemoryMixin

Implements mappings between names and hashes of symbolic variables and these variables themselves.

__init__(**kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

store(addr, data, size=None, **kwargs)[源代码]
get_symbolic_addrs()[源代码]
addrs_for_name(n)[源代码]

Returns addresses that contain expressions that contain a variable named n.

addrs_for_hash(h)[源代码]

Returns addresses that contain expressions that contain a variable with the hash of h.

replace_all(old, new)[源代码]

Replaces all instances of expression old with expression new.

参数:
  • old (BV) -- A claripy expression. Must contain at least one named variable (to make it possible to use the name index for speedup).

  • new (BV) -- The new variable to replace it with.

class angr.storage.memory_mixins.CooperationBase[源代码]

基类:Generic[T]

Any given subclass of this class which is not a subclass of MemoryMixin should have the property that any subclass it which is a subclass of MemoryMixin should all work with the same datatypes

class angr.storage.memory_mixins.DataNormalizationMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Normalizes the data field for a store and the fallback field for a load to be BVs.

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
load(addr, size=None, *, fallback=None, **kwargs)[源代码]
class angr.storage.memory_mixins.DefaultFillerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.DefaultListPagesMemory(*args, **kwargs)[源代码]

基类:HexDumperMixin, SmartFindMixin, UnwrapperMixin, NameResolutionMixin, DataNormalizationMixin, SimplificationMixin, ActionsMixinHigh, UnderconstrainedMixin, SizeConcretizationMixin, SizeNormalizationMixin, InspectMixinHigh, AddressConcretizationMixin, ActionsMixinLow, ConditionalMixin, ConvenientMappingsMixin, DirtyAddrsMixin, StackAllocationMixin, ClemoryBackerMixin, DictBackerMixin, PrivilegedPagingMixin, ListPagesMixin, DefaultFillerMixin, SymbolicMergerMixin, PagedMemoryMixin

class angr.storage.memory_mixins.DefaultMemory(*args, **kwargs)[源代码]

基类:HexDumperMixin, SmartFindMixin, UnwrapperMixin, NameResolutionMixin, DataNormalizationMixin, SimplificationMixin, InspectMixinHigh, ActionsMixinHigh, UnderconstrainedMixin, SizeConcretizationMixin, SizeNormalizationMixin, AddressConcretizationMixin, ActionsMixinLow, ConditionalMixin, ConvenientMappingsMixin, DirtyAddrsMixin, StackAllocationMixin, ConcreteBackerMixin, ClemoryBackerMixin, DictBackerMixin, PrivilegedPagingMixin, UltraPagesMixin, DefaultFillerMixin, SymbolicMergerMixin, PagedMemoryMixin

class angr.storage.memory_mixins.DictBackerMixin(dict_memory_backer=None, **kwargs)[源代码]

基类:PagedMemoryMixin

__init__(dict_memory_backer=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.DirtyAddrsMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.ExplicitFillerMixin(uninitialized_read_handler=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(uninitialized_read_handler=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.FastMemory(uninitialized_read_handler=None, **kwargs)[源代码]

基类:NameResolutionMixin, SimpleInterfaceMixin, SimplificationMixin, InspectMixinHigh, ConditionalMixin, ExplicitFillerMixin, DefaultFillerMixin, SlottedMemoryMixin

class angr.storage.memory_mixins.HexDumperMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

hex_dump(start, size, word_size=4, words_per_row=4, endianness='Iend_BE', symbolic_char='?', unprintable_char='.', solve=False, extra_constraints=None, inspect=False, disable_actions=True)[源代码]

Returns a hex dump as a string. The solver, if enabled, is called once for every byte potentially making this function very slow. It is meant to be used mainly as a "visualization" for debugging.

Warning: May read and display more bytes than size due to rounding. Particularly, if size is less than, or not a multiple of word_size*words_per_line.

参数:
  • start -- starting address from which to print

  • size -- number of bytes to display

  • word_size -- number of bytes to group together as one space-delimited unit

  • words_per_row -- number of words to display per row of output

  • endianness -- endianness to use when displaying each word (ASCII representation is unchanged)

  • symbolic_char -- the character to display when a byte is symbolic and has multiple solutions

  • unprintable_char -- the character to display when a byte is not printable

  • solve -- whether or not to attempt to solve (warning: can be very slow)

  • extra_constraints -- extra constraints to pass to the solver is solve is True

  • inspect -- whether or not to trigger SimInspect breakpoints for the memory load

  • disable_actions -- whether or not to disable SimActions for the memory load

返回:

hex dump as a string

class angr.storage.memory_mixins.HistoryTrackingMixin(*args, **kwargs)[源代码]

基类:RefcountMixin, MemoryMixin

Tracks the history of memory writes.

__init__(*args, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

acquire_unique()[源代码]

Call this function to return a version of this page which can be used for writing, which may or may not be the same object as before. If you use this you must immediately replace the shared reference you previously had with the new unique copy.

parents()[源代码]
changed_bytes(other, **kwargs)[源代码]
返回类型:

set[int] | None

all_bytes_changed_in_history()[源代码]
返回类型:

SegmentList

class angr.storage.memory_mixins.ISPOMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

An implementation of the International Stateless Persons Organisation, a mixin which should be applied as a bottom layer for memories which have no state and must redirect certain operations to a parent memory. Main usecase is for memory region classes which are stored within other memories, such as pages.

参数:
  • memory_id (str | None)

  • endness (str)

set_state(state)[源代码]

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

class angr.storage.memory_mixins.InspectMixinHigh(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, *, condition=None, endness=None, inspect=True, **kwargs)[源代码]
load(addr, size=None, *, condition=None, endness=None, inspect=True, **kwargs)[源代码]
class angr.storage.memory_mixins.JavaVmMemory(memory_id='mem', stack=None, heap=None, vm_static_table=None, load_strategies=None, store_strategies=None, max_array_size=1000, **kwargs)[源代码]

基类:JavaVmMemoryMixin

class angr.storage.memory_mixins.JavaVmMemoryMixin(memory_id='mem', stack=None, heap=None, vm_static_table=None, load_strategies=None, store_strategies=None, max_array_size=1000, **kwargs)[源代码]

基类:MemoryMixin

A memory mixin for JavaVM memory.

__init__(memory_id='mem', stack=None, heap=None, vm_static_table=None, load_strategies=None, store_strategies=None, max_array_size=1000, **kwargs)[源代码]
static get_new_uuid()[源代码]

Generate a unique id within the scope of the JavaVM memory. This, for example, is used for distinguishing memory objects of the same type (e.g. multiple instances of the same class).

store(addr, data, frame=0)[源代码]
load(addr, frame=0, none_if_missing=False)[源代码]
push_stack_frame()[源代码]
pop_stack_frame()[源代码]
property stack
store_array_element(array, idx, value)[源代码]
store_array_elements(array, start_idx, data)[源代码]

Stores either a single element or a range of elements in the array.

参数:
  • array -- Reference to the array.

  • start_idx -- Starting index for the store.

  • data -- Either a single value or a list of values.

load_array_element(array, idx)[源代码]
load_array_elements(array, start_idx, no_of_elements)[源代码]

Loads either a single element or a range of elements from the array.

参数:
  • array -- Reference to the array.

  • start_idx -- Starting index for the load.

  • no_of_elements -- Number of elements to load.

concretize_store_idx(idx, strategies=None)[源代码]

Concretizes a store index.

参数:
  • idx -- An expression for the index.

  • strategies -- A list of concretization strategies (to override the default).

  • min_idx -- Minimum value for a concretized index (inclusive).

  • max_idx -- Maximum value for a concretized index (exclusive).

返回:

A list of concrete indexes.

concretize_load_idx(idx, strategies=None)[源代码]

Concretizes a load index.

参数:
  • idx -- An expression for the index.

  • strategies -- A list of concretization strategies (to override the default).

  • min_idx -- Minimum value for a concretized index (inclusive).

  • max_idx -- Maximum value for a concretized index (exclusive).

返回:

A list of concrete indexes.

set_state(state)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

class angr.storage.memory_mixins.KeyValueMemory(*args, **kwargs)[源代码]

基类:KeyValueMemoryMixin

class angr.storage.memory_mixins.KeyValueMemoryMixin(*args, **kwargs)[源代码]

基类:MemoryMixin

KeyValueMemoryMixin is a mixin that provides a simple key-value store for memory.

__init__(*args, **kwargs)[源代码]
load(addr, size=None, none_if_missing=False, **kwargs)[源代码]
store(addr, data, type_=None, **kwargs)[源代码]
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!

参数:

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

class angr.storage.memory_mixins.LabelMergerMixin(*args, **kwargs)[源代码]

基类:MemoryMixin

A memory mixin for merging labels. Labels come from SimLabeledMemoryObject.

__init__(*args, **kwargs)[源代码]
copy(memo=None)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.LabeledMemory(*args, top_func=None, **kwargs)[源代码]

基类:SizeNormalizationMixin, ListPagesWithLabelsMixin, DefaultFillerMixin, TopMergerMixin, LabelMergerMixin, PagedMemoryMixin

LabeledMemory is used in static analysis. It allows storing values with labels, such as Definition.

class angr.storage.memory_mixins.ListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]

基类:MemoryObjectMixin, PageBase

This class implements a page memory mixin with lists as the main content store.

__init__(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, endness=None, page_addr=None, memory=None, cooperate=False, **kwargs)[源代码]
store(addr, data, size=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None, page_addr=None, memory=None, changed_offsets=None)[源代码]

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)

参数:
  • others (list[ListPage]) -- 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

  • page_addr (int | None)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

changed_bytes(other, page_addr=None)[源代码]
参数:
class angr.storage.memory_mixins.ListPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

PAGE_TYPE

ListPage 的别名

class angr.storage.memory_mixins.ListPagesWithLabelsMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:LabeledPagesMixin, ListPagesMixin

class angr.storage.memory_mixins.MVListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]

基类:MemoryObjectSetMixin, PageBase

MVListPage allows storing multiple values at the same location.

Each store() may take a value or multiple values. Each load() returns an iterator of all values stored at that location.

__init__(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

返回类型:

MVListPage

load(addr, size=None, endness=None, page_addr=None, memory=None, cooperate=False, **kwargs)[源代码]
返回类型:

list[tuple[int, Union[SimMemoryObject, SimLabeledMemoryObject]]]

store(addr, data, size=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None, *, page_addr, memory, changed_offsets=None)[源代码]

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)

参数:
  • others (list[MVListPage]) -- 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

  • page_addr (int)

  • memory (MemoryMixin)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

compare(other, page_addr=None, memory=None, changed_offsets=None)[源代码]
返回类型:

bool

参数:
changed_bytes(other, page_addr=None)[源代码]
参数:
content_gen(index)[源代码]
class angr.storage.memory_mixins.MVListPagesMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]

基类:PagedMemoryMixin

PAGE_TYPE

MVListPage 的别名

__init__(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]
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!

参数:

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

class angr.storage.memory_mixins.MVListPagesWithLabelsMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]

基类:LabeledPagesMixin, MVListPagesMixin

class angr.storage.memory_mixins.MemoryObjectMixin[源代码]

基类:CooperationBase[SimMemoryObject]

Uses SimMemoryObjects in region storage. With this, load will return a list of tuple (address, MO) and store will take a MO.

class angr.storage.memory_mixins.MemoryRegionMetaMixin(related_function_addr=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(related_function_addr=None, **kwargs)[源代码]
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!

参数:

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

property is_stack
property related_function_addr
get_abstract_locations(addr, size)[源代码]

Get a list of abstract locations that is within the range of [addr, addr + size]

This implementation is pretty slow. But since this method won't be called frequently, we can live with the bad implementation for now.

参数:
  • addr -- Starting address of the memory region.

  • size -- Size of the memory region, in bytes.

返回:

A list of covered AbstractLocation objects, or an empty list if there is none.

store(addr, data, size=None, *, bbl_addr=None, stmt_id=None, ins_addr=None, endness=None, **kwargs)[源代码]
load(addr, size=None, *, bbl_addr=None, stmt_idx=None, ins_addr=None, **kwargs)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

dbg_print(indent=0)[源代码]

Print out debugging information

class angr.storage.memory_mixins.MultiValueMergerMixin(*args, element_limit=5, annotation_limit=256, top_func=None, is_top_func=None, phi_maker=None, merge_into_top=True, **kwargs)[源代码]

基类:MemoryMixin

__init__(*args, element_limit=5, annotation_limit=256, top_func=None, is_top_func=None, phi_maker=None, merge_into_top=True, **kwargs)[源代码]
copy(memo=None)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.MultiValuedMemory(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]

基类:SizeNormalizationMixin, MVListPagesMixin, DefaultFillerMixin, MultiValueMergerMixin, PagedMemoryMixin, PagedMemoryMultiValueMixin

class angr.storage.memory_mixins.NameResolutionMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

This mixin allows you to provide register names as load addresses, and will automatically translate this to an offset and size.

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
load(addr, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.PageBase(*args, **kwargs)[源代码]

基类:HistoryTrackingMixin, RefcountMixin, CooperationBase, ISPOMixin, PermissionsMixin, MemoryMixin

This is a fairly succinct definition of the contract between PagedMemoryMixin and its constituent pages:

  • Pages must implement the MemoryMixin model for loads, stores, copying, merging, etc

  • However, loading/storing may not necessarily use the same data domain as PagedMemoryMixin. In order to do more efficient loads/stores across pages, we use the CooperationBase interface which allows the page class to determine how to generate and unwrap the objects which are actually stored.

  • To support COW, we use the RefcountMixin and the ISPOMixin (which adds the contract element that memory=self be passed to every method call)

  • Pages have permissions associated with them, stored in the PermissionsMixin.

Read the docstrings for each of the constituent classes to understand the nuances of their functionalities

class angr.storage.memory_mixins.PagedMemoryMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:Generic[PageType], MemoryMixin[int | BV | SimActionObject, BV, int | BV | SimActionObject]

A bottom-level storage mechanism. Dispatches reads to individual pages, the type of which is the PAGE_TYPE class variable.

SUPPORTS_CONCRETE_LOAD: bool = True
PAGE_TYPE: type[PageType]
__init__(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, *, endness=None, **kwargs)[源代码]
参数:
  • addr (int)

  • size (int | None)

store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
参数:
  • addr (int)

  • size (int | None)

erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

compare(other)[源代码]
返回类型:

bool

参数:

other (PagedMemoryMixin)

permissions(addr, permissions=None, **kwargs)[源代码]
map_region(addr, length, permissions, *, init_zero=False, **kwargs)[源代码]
unmap_region(addr, length, **kwargs)[源代码]
concrete_load(addr, size, writing=False, *, with_bitmap=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

  • with_bitmap (bool)

返回:

A memoryview into the loaded bytes.

changed_bytes(other)[源代码]
返回类型:

set[int]

changed_pages(other)[源代码]
返回类型:

dict[int, set[int] | None]

copy_contents(dst, src, size, condition=None, **kwargs)[源代码]

Override this method to provide faster copying of large chunks of data.

参数:
  • dst -- The destination of copying.

  • src -- The source of copying.

  • size -- The size of copying.

  • condition -- The storing condition.

  • kwargs -- Other parameters.

返回:

None

flush_pages(white_list)[源代码]

Flush all pages not included in the white_list by removing their pages. Note, this will not wipe them from memory if they were backed by a memory_backer, it will simply reset them to their initial state. Returns the list of pages that were cleared consisting of (addr, length) tuples. :type white_list: :param white_list: white list of regions in the form of (start, end) to exclude from the flush :return: a list of memory page ranges that were flushed :rtype: list

class angr.storage.memory_mixins.PagedMemoryMultiValueMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Implement optimizations and fast accessors for the MultiValues-variant of Paged Memory.

参数:
  • memory_id (str | None)

  • endness (str)

load_annotations(addr, size, **kwargs)[源代码]
参数:
class angr.storage.memory_mixins.PermissionsMixin(permissions=None, **kwargs)[源代码]

基类:MemoryMixin

This mixin adds a permissions_bits field and properties for extracting the read/write/exec permissions. It does NOT add permissions checking.

参数:

permissions (int | claripy.ast.BV | None)

__init__(permissions=None, **kwargs)[源代码]
参数:

permissions (int | BV | None)

copy(memo)[源代码]

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!

参数:

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

property perm_read
property perm_write
property perm_exec
class angr.storage.memory_mixins.PrivilegedPagingMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

A mixin for paged memory models which will raise SimSegfaultExceptions if STRICT_PAGE_ACCESS is enabled and a segfault condition is detected.

Segfault conditions include: - getting a page for reading which is non-readable - getting a page for writing which is non-writable - creating a page

The latter condition means that this should be inserted under any mixins which provide other implementations of _initialize_page.

class angr.storage.memory_mixins.RefcountMixin(**kwargs)[源代码]

基类:MemoryMixin

This mixin adds a locked reference counter and methods to manipulate it, to facilitate copy-on-write optimizations.

__init__(**kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

acquire_unique()[源代码]

Call this function to return a version of this page which can be used for writing, which may or may not be the same object as before. If you use this you must immediately replace the shared reference you previously had with the new unique copy.

acquire_shared()[源代码]

Call this function to indicate that this page has had a reference added to it and must be copied before it can be acquired uniquely again. Creating the object implicitly starts it with one shared reference.

返回类型:

None

release_shared()[源代码]

Call this function to indicate that this page has had a shared reference to it released

返回类型:

None

class angr.storage.memory_mixins.RegionCategoryMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

property category

reg, mem, or file.

Type:

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

class angr.storage.memory_mixins.RegionedAddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(read_strategies=None, write_strategies=None, **kwargs)[源代码]
set_state(state)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

class angr.storage.memory_mixins.RegionedMemory(related_function_addr=None, **kwargs)[源代码]

基类:RegionCategoryMixin, MemoryRegionMetaMixin, StaticFindMixin, UnwrapperMixin, NameResolutionMixin, DataNormalizationMixin, SimplificationMixin, SizeConcretizationMixin, SizeNormalizationMixin, AddressConcretizationMixin, ConvenientMappingsMixin, DirtyAddrsMixin, ClemoryBackerMixin, DictBackerMixin, UltraPagesMixin, DefaultFillerMixin, AbstractMergerMixin, PagedMemoryMixin

class angr.storage.memory_mixins.RegionedMemoryMixin(write_targets_limit=2048, read_targets_limit=4096, stack_region_map=None, generic_region_map=None, stack_size=65536, cle_memory_backer=None, dict_memory_backer=None, regioned_memory_cls=None, **kwargs)[源代码]

基类:MemoryMixin

Regioned memory. This mixin manages multiple memory regions. Each address is represented as a tuple of (region ID, offset into the region), which is called a regioned address.

Converting absolute addresses into regioned addresses: We map an absolute address to a region by looking up which region this address belongs to in the region map. Currently this is only enabled for stack. Heap support has not landed yet.

When start analyzing a function, the user should call set_stack_address_mapping() to create a new region mapping. Likewise, when exiting from a function, the user should cancel the previous mapping by calling unset_stack_address_mapping().

参数:
  • write_targets_limit (int)

  • read_targets_limit (int)

  • stack_region_map (RegionMap | None)

  • generic_region_map (RegionMap | None)

  • stack_size (int)

  • cle_memory_backer (Optional | None)

  • dict_memory_backer (dict | None)

  • regioned_memory_cls (type | None)

__init__(write_targets_limit=2048, read_targets_limit=4096, stack_region_map=None, generic_region_map=None, stack_size=65536, cle_memory_backer=None, dict_memory_backer=None, regioned_memory_cls=None, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, *, endness=None, condition=None, **kwargs)[源代码]
参数:
  • size (int | BV | None)

  • condition (Bool | None)

store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
参数:

size (int | None)

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

find(addr, data, max_search, **kwargs)[源代码]
参数:

addr (int | Bits)

set_state(state)[源代码]

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

replace_all(old, new)[源代码]
参数:
set_stack_address_mapping(absolute_address, region_id, related_function_address=None)[源代码]

Create a new mapping between an absolute address (which is the base address of a specific stack frame) and a region ID.

参数:
  • absolute_address (int) -- The absolute memory address.

  • region_id (str) -- The region ID.

  • related_function_address (Optional[int]) -- Related function address.

unset_stack_address_mapping(absolute_address)[源代码]

Remove a stack mapping.

参数:

absolute_address (int) -- An absolute memory address that is the base address of the stack frame to destroy.

stack_id(function_address)[源代码]

Return a memory region ID for a function. If the default region ID exists in the region mapping, an integer will appended to the region name. In this way we can handle recursive function calls, or a function that appears more than once in the call frame.

This also means that stack_id() should only be called when creating a new stack frame for a function. You are not supposed to call this function every time you want to map a function address to a stack ID.

参数:

function_address (int) -- Address of the function.

返回类型:

str

返回:

ID of the new memory region.

set_stack_size(size)[源代码]
参数:

size (int)

class angr.storage.memory_mixins.SimpleInterfaceMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, endness=None, condition=None, fallback=None, **kwargs)[源代码]
store(addr, data, size=None, *, endness=None, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.SimplificationMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.SizeConcretizationMixin(concretize_symbolic_write_size=False, max_concretize_count=256, max_symbolic_size=4194304, raise_memory_limit_error=False, size_limit=257, **kwargs)[源代码]

基类:MemoryMixin

This mixin allows memory to process symbolic sizes. It will not touch any sizes which are not ASTs with non-BVV ops. Assumes that the data is a BV.

  • symbolic load sizes will be concretized as their maximum and a warning will be logged

  • symbolic store sizes will be dispatched as several conditional stores with concrete sizes

参数:
  • concretize_symbolic_write_size (bool)

  • max_concretize_count (int | None)

  • max_symbolic_size (int)

  • raise_memory_limit_error (bool)

  • size_limit (int)

__init__(concretize_symbolic_write_size=False, max_concretize_count=256, max_symbolic_size=4194304, raise_memory_limit_error=False, size_limit=257, **kwargs)[源代码]
参数:
  • concretize_symbolic_write_size (bool)

  • max_concretize_count (int | None)

  • max_symbolic_size (int)

  • raise_memory_limit_error (bool)

  • size_limit (int)

copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, **kwargs)[源代码]
store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.SizeNormalizationMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Provides basic services related to normalizing sizes. After this mixin, sizes will always be a plain int. Assumes that the data is a BV.

  • load will throw a TypeError if no size is provided

  • store will default to len(data)//byte_width if no size is provided

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.SlottedMemoryMixin(width=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(width=None, **kwargs)[源代码]
set_state(state)[源代码]

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

copy(memo)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

load(addr, size=None, *, endness=None, **kwargs)[源代码]
store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
changed_bytes(other)[源代码]
class angr.storage.memory_mixins.SmartFindMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Memory mixin providing basic searching over concrete and symbolic data.

参数:
  • memory_id (str | None)

  • endness (str)

find(addr, data, max_search, *, default=None, endness=None, chunk_size=None, max_symbolic_bytes=None, condition=None, char_size=1, **kwargs)[源代码]
class angr.storage.memory_mixins.SpecialFillerMixin(special_memory_filler=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(special_memory_filler=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.StackAllocationMixin(stack_end=None, stack_size=None, stack_perms=None, **kwargs)[源代码]

基类:PagedMemoryMixin

This mixin adds automatic allocation for a stack region based on the stack_end and stack_size parameters.

__init__(stack_end=None, stack_size=None, stack_perms=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

allocate_stack_pages(addr, size, **kwargs)[源代码]

Pre-allocates pages for the stack without triggering any logic related to reading from them.

参数:
  • addr (int) -- The highest address that should be mapped

  • size (int) -- The number of bytes to be allocated. byte 1 is the one at addr, byte 2 is the one before that, and so on.

返回:

A list of the new page objects

class angr.storage.memory_mixins.StaticFindMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:SmartFindMixin

Implements data finding for abstract memory.

参数:
  • memory_id (str | None)

  • endness (str)

find(addr, data, max_search, *, default=None, endness=None, chunk_size=None, max_symbolic_bytes=None, condition=None, char_size=1, **kwargs)[源代码]
class angr.storage.memory_mixins.SymbolicMergerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.TopMergerMixin(*args, top_func=None, **kwargs)[源代码]

基类:MemoryMixin

A memory mixin for merging values in memory to TOP.

__init__(*args, top_func=None, **kwargs)[源代码]
copy(memo=None)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.UltraPage(memory=None, init_zero=False, **kwargs)[源代码]

基类:MemoryObjectMixin, PageBase

Default page implementation

SUPPORTS_CONCRETE_LOAD: bool = True
__init__(memory=None, init_zero=False, **kwargs)[源代码]
classmethod new_from_shared(data, memory=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, page_addr=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
store(addr, data, size=None, endness=None, memory=None, page_addr=None, cooperate=False, **kwargs)[源代码]
参数:
merge(others, merge_conditions, common_ancestor=None, page_addr=None, memory=None, changed_offsets=None)[源代码]

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)

参数:
  • others (list[UltraPage]) -- 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

  • page_addr (int | None)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

concrete_load(addr, size, writing=False, with_bitmap=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

返回:

A memoryview into the loaded bytes.

changed_bytes(other, page_addr=None)[源代码]
返回类型:

set[int]

replace_all_with_offsets(offsets, old, new, memory=None)[源代码]
参数:
class angr.storage.memory_mixins.UltraPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

PAGE_TYPE

UltraPage 的别名

class angr.storage.memory_mixins.UnderconstrainedMixin(*args, **kwargs)[源代码]

基类:MemoryMixin

__init__(*args, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.UnwrapperMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

This mixin processes SimActionObjects by passing on their .ast field.

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
load(addr, size=None, *, condition=None, fallback=None, **kwargs)[源代码]
find(addr, data, max_search, *, default=None, **kwargs)[源代码]
copy_contents(dst, src, size, condition=None, **kwargs)[源代码]

Override this method to provide faster copying of large chunks of data.

参数:
  • dst -- The destination of copying.

  • src -- The source of copying.

  • size -- The size of copying.

  • condition -- The storing condition.

  • kwargs -- Other parameters.

返回:

None

class angr.storage.memory_mixins.name_resolution_mixin.NameResolutionMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

This mixin allows you to provide register names as load addresses, and will automatically translate this to an offset and size.

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
load(addr, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.smart_find_mixin.SmartFindMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Memory mixin providing basic searching over concrete and symbolic data.

参数:
  • memory_id (str | None)

  • endness (str)

find(addr, data, max_search, *, default=None, endness=None, chunk_size=None, max_symbolic_bytes=None, condition=None, char_size=1, **kwargs)[源代码]
class angr.storage.memory_mixins.default_filler_mixin.DefaultFillerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.default_filler_mixin.SpecialFillerMixin(special_memory_filler=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(special_memory_filler=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.default_filler_mixin.ExplicitFillerMixin(uninitialized_read_handler=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(uninitialized_read_handler=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.bvv_conversion_mixin.DataNormalizationMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Normalizes the data field for a store and the fallback field for a load to be BVs.

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
load(addr, size=None, *, fallback=None, **kwargs)[源代码]
class angr.storage.memory_mixins.hex_dumper_mixin.HexDumperMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

hex_dump(start, size, word_size=4, words_per_row=4, endianness='Iend_BE', symbolic_char='?', unprintable_char='.', solve=False, extra_constraints=None, inspect=False, disable_actions=True)[源代码]

Returns a hex dump as a string. The solver, if enabled, is called once for every byte potentially making this function very slow. It is meant to be used mainly as a "visualization" for debugging.

Warning: May read and display more bytes than size due to rounding. Particularly, if size is less than, or not a multiple of word_size*words_per_line.

参数:
  • start -- starting address from which to print

  • size -- number of bytes to display

  • word_size -- number of bytes to group together as one space-delimited unit

  • words_per_row -- number of words to display per row of output

  • endianness -- endianness to use when displaying each word (ASCII representation is unchanged)

  • symbolic_char -- the character to display when a byte is symbolic and has multiple solutions

  • unprintable_char -- the character to display when a byte is not printable

  • solve -- whether or not to attempt to solve (warning: can be very slow)

  • extra_constraints -- extra constraints to pass to the solver is solve is True

  • inspect -- whether or not to trigger SimInspect breakpoints for the memory load

  • disable_actions -- whether or not to disable SimActions for the memory load

返回:

hex dump as a string

class angr.storage.memory_mixins.underconstrained_mixin.UnderconstrainedMixin(*args, **kwargs)[源代码]

基类:MemoryMixin

__init__(*args, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.simple_interface_mixin.SimpleInterfaceMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, endness=None, condition=None, fallback=None, **kwargs)[源代码]
store(addr, data, size=None, *, endness=None, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.actions_mixin.ActionsMixinHigh(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, condition=None, fallback=None, disable_actions=False, action=None, **kwargs)[源代码]
store(addr, data, size=None, *, disable_actions=False, action=None, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.actions_mixin.ActionsMixinLow(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, action=None, **kwargs)[源代码]
store(addr, data, size=None, *, action=None, **kwargs)[源代码]
参数:

action (SimActionData | None)

class angr.storage.memory_mixins.symbolic_merger_mixin.SymbolicMergerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.size_resolution_mixin.SizeNormalizationMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

Provides basic services related to normalizing sizes. After this mixin, sizes will always be a plain int. Assumes that the data is a BV.

  • load will throw a TypeError if no size is provided

  • store will default to len(data)//byte_width if no size is provided

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.size_resolution_mixin.SizeConcretizationMixin(concretize_symbolic_write_size=False, max_concretize_count=256, max_symbolic_size=4194304, raise_memory_limit_error=False, size_limit=257, **kwargs)[源代码]

基类:MemoryMixin

This mixin allows memory to process symbolic sizes. It will not touch any sizes which are not ASTs with non-BVV ops. Assumes that the data is a BV.

  • symbolic load sizes will be concretized as their maximum and a warning will be logged

  • symbolic store sizes will be dispatched as several conditional stores with concrete sizes

参数:
  • concretize_symbolic_write_size (bool)

  • max_concretize_count (int | None)

  • max_symbolic_size (int)

  • raise_memory_limit_error (bool)

  • size_limit (int)

__init__(concretize_symbolic_write_size=False, max_concretize_count=256, max_symbolic_size=4194304, raise_memory_limit_error=False, size_limit=257, **kwargs)[源代码]
参数:
  • concretize_symbolic_write_size (bool)

  • max_concretize_count (int | None)

  • max_symbolic_size (int)

  • raise_memory_limit_error (bool)

  • size_limit (int)

copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, **kwargs)[源代码]
store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.dirty_addrs_mixin.DirtyAddrsMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.address_concretization_mixin.MultiwriteAnnotation[源代码]

基类:Annotation

property eliminatable

Returns whether this annotation can be eliminated in a simplification.

返回:

True if eliminatable, False otherwise

property relocateable
class angr.storage.memory_mixins.address_concretization_mixin.AddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]

基类:MemoryMixin

The address concretization mixin allows symbolic reads and writes to be handled sanely by dispatching them as a number of conditional concrete reads/writes. It provides a "concretization strategies" interface allowing the process of serializing symbolic addresses into concrete ones to be specified.

__init__(read_strategies=None, write_strategies=None, **kwargs)[源代码]
set_state(state)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

concretize_write_addr(addr, strategies=None, condition=None)[源代码]

Concretizes an address meant for writing.

参数:
  • addr -- An expression for the address.

  • strategies -- A list of concretization strategies (to override the default).

  • condition -- Any extra constraints that should be observed when determining address satisfiability

返回:

A list of concrete addresses.

concretize_read_addr(addr, strategies=None, condition=None)[源代码]

Concretizes an address meant for reading.

参数:
  • addr -- An expression for the address.

  • strategies -- A list of concretization strategies (to override the default).

返回:

A list of concrete addresses.

load(addr, size=None, *, condition=None, **kwargs)[源代码]
store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
permissions(addr, permissions=None, **kwargs)[源代码]
map_region(addr, length, permissions, **kwargs)[源代码]
unmap_region(addr, length, **kwargs)[源代码]
concrete_load(addr, size, writing=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

返回:

A memoryview into the loaded bytes.

class angr.storage.memory_mixins.clouseau_mixin.InspectMixinHigh(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, *, condition=None, endness=None, inspect=True, **kwargs)[源代码]
load(addr, size=None, *, condition=None, endness=None, inspect=True, **kwargs)[源代码]
class angr.storage.memory_mixins.conditional_store_mixin.ConditionalMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

load(addr, size=None, *, condition=None, fallback=None, **kwargs)[源代码]
store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
class angr.storage.memory_mixins.label_merger_mixin.LabelMergerMixin(*args, **kwargs)[源代码]

基类:MemoryMixin

A memory mixin for merging labels. Labels come from SimLabeledMemoryObject.

__init__(*args, **kwargs)[源代码]
copy(memo=None)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.simplification_mixin.SimplificationMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, **kwargs)[源代码]
class angr.storage.memory_mixins.unwrapper_mixin.UnwrapperMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

This mixin processes SimActionObjects by passing on their .ast field.

参数:
  • memory_id (str | None)

  • endness (str)

store(addr, data, size=None, *, condition=None, **kwargs)[源代码]
load(addr, size=None, *, condition=None, fallback=None, **kwargs)[源代码]
find(addr, data, max_search, *, default=None, **kwargs)[源代码]
copy_contents(dst, src, size, condition=None, **kwargs)[源代码]

Override this method to provide faster copying of large chunks of data.

参数:
  • dst -- The destination of copying.

  • src -- The source of copying.

  • size -- The size of copying.

  • condition -- The storing condition.

  • kwargs -- Other parameters.

返回:

None

class angr.storage.memory_mixins.convenient_mappings_mixin.ConvenientMappingsMixin(**kwargs)[源代码]

基类:MemoryMixin

Implements mappings between names and hashes of symbolic variables and these variables themselves.

__init__(**kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

store(addr, data, size=None, **kwargs)[源代码]
get_symbolic_addrs()[源代码]
addrs_for_name(n)[源代码]

Returns addresses that contain expressions that contain a variable named n.

addrs_for_hash(h)[源代码]

Returns addresses that contain expressions that contain a variable with the hash of h.

replace_all(old, new)[源代码]

Replaces all instances of expression old with expression new.

参数:
  • old (BV) -- A claripy expression. Must contain at least one named variable (to make it possible to use the name index for speedup).

  • new (BV) -- The new variable to replace it with.

class angr.storage.memory_mixins.paged_memory.pages.mv_list_page.MVListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]

基类:MemoryObjectSetMixin, PageBase

MVListPage allows storing multiple values at the same location.

Each store() may take a value or multiple values. Each load() returns an iterator of all values stored at that location.

__init__(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

返回类型:

MVListPage

load(addr, size=None, endness=None, page_addr=None, memory=None, cooperate=False, **kwargs)[源代码]
返回类型:

list[tuple[int, Union[SimMemoryObject, SimLabeledMemoryObject]]]

store(addr, data, size=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None, *, page_addr, memory, changed_offsets=None)[源代码]

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)

参数:
  • others (list[MVListPage]) -- 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

  • page_addr (int)

  • memory (MemoryMixin)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

compare(other, page_addr=None, memory=None, changed_offsets=None)[源代码]
返回类型:

bool

参数:
changed_bytes(other, page_addr=None)[源代码]
参数:
content_gen(index)[源代码]
class angr.storage.memory_mixins.paged_memory.pages.multi_values.MultiValues(v=None, offset_to_values=None)[源代码]

基类:Generic[MVType]

Represents a byte vector where each byte can have one or multiple values.

As an implementation optimization (so that we do not create excessive sets and dicts), self._single_value stores a claripy AST when this MultiValues object represents only one value at offset 0.

参数:
__init__(v=None, offset_to_values=None)[源代码]
参数:
add_value(offset, value)[源代码]
返回类型:

None

参数:
  • offset (int)

  • value (MVType)

one_value(strip_annotations=False)[源代码]
返回类型:

Optional[TypeVar(MVType, bound= BV | FP)]

参数:

strip_annotations (bool)

merge(mv)[源代码]
返回类型:

MultiValues[TypeVar(MVType, bound= BV | FP)]

参数:

mv (MultiValues[MVType])

keys()[源代码]
返回类型:

set[int]

values()[源代码]
返回类型:

Iterator[set[TypeVar(MVType, bound= BV | FP)]]

items()[源代码]
返回类型:

Iterator[tuple[int, set[TypeVar(MVType, bound= BV | FP)]]]

count()[源代码]
返回类型:

int

extract(offset, length, endness)[源代码]
返回类型:

MultiValues[BV]

参数:
concat(other)[源代码]
返回类型:

MultiValues[BV]

参数:
angr.storage.memory_mixins.paged_memory.pages.multi_values.mv_is_bv(mv)[源代码]
返回类型:

TypeGuard[MultiValues[BV]]

参数:

mv (MultiValues[Any])

angr.storage.memory_mixins.paged_memory.pages.multi_values.mv_is_fp(mv)[源代码]
返回类型:

TypeGuard[MultiValues[FP]]

参数:

mv (MultiValues[Any])

class angr.storage.memory_mixins.top_merger_mixin.TopMergerMixin(*args, top_func=None, **kwargs)[源代码]

基类:MemoryMixin

A memory mixin for merging values in memory to TOP.

__init__(*args, top_func=None, **kwargs)[源代码]
copy(memo=None)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.multi_value_merger_mixin.MultiValueMergerMixin(*args, element_limit=5, annotation_limit=256, top_func=None, is_top_func=None, phi_maker=None, merge_into_top=True, **kwargs)[源代码]

基类:MemoryMixin

__init__(*args, element_limit=5, annotation_limit=256, top_func=None, is_top_func=None, phi_maker=None, merge_into_top=True, **kwargs)[源代码]
copy(memo=None)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.PagedMemoryMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:Generic[PageType], MemoryMixin[int | BV | SimActionObject, BV, int | BV | SimActionObject]

A bottom-level storage mechanism. Dispatches reads to individual pages, the type of which is the PAGE_TYPE class variable.

SUPPORTS_CONCRETE_LOAD: bool = True
PAGE_TYPE: type[PageType]
__init__(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, *, endness=None, **kwargs)[源代码]
参数:
  • addr (int)

  • size (int | None)

store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
参数:
  • addr (int)

  • size (int | None)

erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

compare(other)[源代码]
返回类型:

bool

参数:

other (PagedMemoryMixin)

permissions(addr, permissions=None, **kwargs)[源代码]
map_region(addr, length, permissions, *, init_zero=False, **kwargs)[源代码]
unmap_region(addr, length, **kwargs)[源代码]
concrete_load(addr, size, writing=False, *, with_bitmap=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

  • with_bitmap (bool)

返回:

A memoryview into the loaded bytes.

changed_bytes(other)[源代码]
返回类型:

set[int]

changed_pages(other)[源代码]
返回类型:

dict[int, set[int] | None]

copy_contents(dst, src, size, condition=None, **kwargs)[源代码]

Override this method to provide faster copying of large chunks of data.

参数:
  • dst -- The destination of copying.

  • src -- The source of copying.

  • size -- The size of copying.

  • condition -- The storing condition.

  • kwargs -- Other parameters.

返回:

None

flush_pages(white_list)[源代码]

Flush all pages not included in the white_list by removing their pages. Note, this will not wipe them from memory if they were backed by a memory_backer, it will simply reset them to their initial state. Returns the list of pages that were cleared consisting of (addr, length) tuples. :type white_list: :param white_list: white list of regions in the form of (start, end) to exclude from the flush :return: a list of memory page ranges that were flushed :rtype: list

state: angr.SimState
class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.LabeledPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

load_with_labels(addr, size=None, endness=None, **kwargs)[源代码]
返回类型:

tuple[Base, tuple[tuple[int, int, int, Any]]]

参数:
  • addr (int)

  • size (int | None)

class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.ListPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

PAGE_TYPE

ListPage 的别名

class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.MVListPagesMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]

基类:PagedMemoryMixin

PAGE_TYPE

MVListPage 的别名

__init__(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]
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!

参数:

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

class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.ListPagesWithLabelsMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:LabeledPagesMixin, ListPagesMixin

class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.MVListPagesWithLabelsMixin(*args, skip_missing_values_during_merging=False, **kwargs)[源代码]

基类:LabeledPagesMixin, MVListPagesMixin

class angr.storage.memory_mixins.paged_memory.paged_memory_mixin.UltraPagesMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

PAGE_TYPE

UltraPage 的别名

class angr.storage.memory_mixins.paged_memory.page_backer_mixins.NotMemoryview(obj, offset, size)[源代码]

基类:object

__init__(obj, offset, size)[源代码]
class angr.storage.memory_mixins.paged_memory.page_backer_mixins.ClemoryBackerMixin(cle_memory_backer=None, **kwargs)[源代码]

基类:PagedMemoryMixin

参数:

cle_memory_backer (None | cle.Loader | cle.Clemory)

__init__(cle_memory_backer=None, **kwargs)[源代码]
参数:

cle_memory_backer (None | Loader | Clemory)

copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.paged_memory.page_backer_mixins.ConcreteBackerMixin(cle_memory_backer=None, **kwargs)[源代码]

基类:ClemoryBackerMixin

参数:

cle_memory_backer (None | cle.Loader | cle.Clemory)

class angr.storage.memory_mixins.paged_memory.page_backer_mixins.DictBackerMixin(dict_memory_backer=None, **kwargs)[源代码]

基类:PagedMemoryMixin

__init__(dict_memory_backer=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

class angr.storage.memory_mixins.paged_memory.stack_allocation_mixin.StackAllocationMixin(stack_end=None, stack_size=None, stack_perms=None, **kwargs)[源代码]

基类:PagedMemoryMixin

This mixin adds automatic allocation for a stack region based on the stack_end and stack_size parameters.

__init__(stack_end=None, stack_size=None, stack_perms=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

allocate_stack_pages(addr, size, **kwargs)[源代码]

Pre-allocates pages for the stack without triggering any logic related to reading from them.

参数:
  • addr (int) -- The highest address that should be mapped

  • size (int) -- The number of bytes to be allocated. byte 1 is the one at addr, byte 2 is the one before that, and so on.

返回:

A list of the new page objects

class angr.storage.memory_mixins.paged_memory.privileged_mixin.PrivilegedPagingMixin(page_size=4096, default_permissions=3, permissions_map=None, page_kwargs=None, **kwargs)[源代码]

基类:PagedMemoryMixin

A mixin for paged memory models which will raise SimSegfaultExceptions if STRICT_PAGE_ACCESS is enabled and a segfault condition is detected.

Segfault conditions include: - getting a page for reading which is non-readable - getting a page for writing which is non-writable - creating a page

The latter condition means that this should be inserted under any mixins which provide other implementations of _initialize_page.

class angr.storage.memory_mixins.paged_memory.pages.CooperationBase[源代码]

基类:Generic[T]

Any given subclass of this class which is not a subclass of MemoryMixin should have the property that any subclass it which is a subclass of MemoryMixin should all work with the same datatypes

class angr.storage.memory_mixins.paged_memory.pages.HistoryTrackingMixin(*args, **kwargs)[源代码]

基类:RefcountMixin, MemoryMixin

Tracks the history of memory writes.

__init__(*args, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

acquire_unique()[源代码]

Call this function to return a version of this page which can be used for writing, which may or may not be the same object as before. If you use this you must immediately replace the shared reference you previously had with the new unique copy.

parents()[源代码]
changed_bytes(other, **kwargs)[源代码]
返回类型:

set[int] | None

all_bytes_changed_in_history()[源代码]
返回类型:

SegmentList

class angr.storage.memory_mixins.paged_memory.pages.ISPOMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

An implementation of the International Stateless Persons Organisation, a mixin which should be applied as a bottom layer for memories which have no state and must redirect certain operations to a parent memory. Main usecase is for memory region classes which are stored within other memories, such as pages.

参数:
  • memory_id (str | None)

  • endness (str)

set_state(state)[源代码]

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

class angr.storage.memory_mixins.paged_memory.pages.ListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]

基类:MemoryObjectMixin, PageBase

This class implements a page memory mixin with lists as the main content store.

__init__(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, endness=None, page_addr=None, memory=None, cooperate=False, **kwargs)[源代码]
store(addr, data, size=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None, page_addr=None, memory=None, changed_offsets=None)[源代码]

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)

参数:
  • others (list[ListPage]) -- 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

  • page_addr (int | None)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

changed_bytes(other, page_addr=None)[源代码]
参数:
class angr.storage.memory_mixins.paged_memory.pages.MVListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]

基类:MemoryObjectSetMixin, PageBase

MVListPage allows storing multiple values at the same location.

Each store() may take a value or multiple values. Each load() returns an iterator of all values stored at that location.

__init__(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

返回类型:

MVListPage

load(addr, size=None, endness=None, page_addr=None, memory=None, cooperate=False, **kwargs)[源代码]
返回类型:

list[tuple[int, Union[SimMemoryObject, SimLabeledMemoryObject]]]

store(addr, data, size=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None, *, page_addr, memory, changed_offsets=None)[源代码]

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)

参数:
  • others (list[MVListPage]) -- 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

  • page_addr (int)

  • memory (MemoryMixin)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

compare(other, page_addr=None, memory=None, changed_offsets=None)[源代码]
返回类型:

bool

参数:
changed_bytes(other, page_addr=None)[源代码]
参数:
content_gen(index)[源代码]
class angr.storage.memory_mixins.paged_memory.pages.MemoryObjectMixin[源代码]

基类:CooperationBase[SimMemoryObject]

Uses SimMemoryObjects in region storage. With this, load will return a list of tuple (address, MO) and store will take a MO.

class angr.storage.memory_mixins.paged_memory.pages.PageBase(*args, **kwargs)[源代码]

基类:HistoryTrackingMixin, RefcountMixin, CooperationBase, ISPOMixin, PermissionsMixin, MemoryMixin

This is a fairly succinct definition of the contract between PagedMemoryMixin and its constituent pages:

  • Pages must implement the MemoryMixin model for loads, stores, copying, merging, etc

  • However, loading/storing may not necessarily use the same data domain as PagedMemoryMixin. In order to do more efficient loads/stores across pages, we use the CooperationBase interface which allows the page class to determine how to generate and unwrap the objects which are actually stored.

  • To support COW, we use the RefcountMixin and the ISPOMixin (which adds the contract element that memory=self be passed to every method call)

  • Pages have permissions associated with them, stored in the PermissionsMixin.

Read the docstrings for each of the constituent classes to understand the nuances of their functionalities

class angr.storage.memory_mixins.paged_memory.pages.PermissionsMixin(permissions=None, **kwargs)[源代码]

基类:MemoryMixin

This mixin adds a permissions_bits field and properties for extracting the read/write/exec permissions. It does NOT add permissions checking.

参数:

permissions (int | claripy.ast.BV | None)

__init__(permissions=None, **kwargs)[源代码]
参数:

permissions (int | BV | None)

copy(memo)[源代码]

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!

参数:

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

property perm_read
property perm_write
property perm_exec
class angr.storage.memory_mixins.paged_memory.pages.RefcountMixin(**kwargs)[源代码]

基类:MemoryMixin

This mixin adds a locked reference counter and methods to manipulate it, to facilitate copy-on-write optimizations.

__init__(**kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

acquire_unique()[源代码]

Call this function to return a version of this page which can be used for writing, which may or may not be the same object as before. If you use this you must immediately replace the shared reference you previously had with the new unique copy.

acquire_shared()[源代码]

Call this function to indicate that this page has had a reference added to it and must be copied before it can be acquired uniquely again. Creating the object implicitly starts it with one shared reference.

返回类型:

None

release_shared()[源代码]

Call this function to indicate that this page has had a shared reference to it released

返回类型:

None

class angr.storage.memory_mixins.paged_memory.pages.UltraPage(memory=None, init_zero=False, **kwargs)[源代码]

基类:MemoryObjectMixin, PageBase

Default page implementation

SUPPORTS_CONCRETE_LOAD: bool = True
__init__(memory=None, init_zero=False, **kwargs)[源代码]
classmethod new_from_shared(data, memory=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, page_addr=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
store(addr, data, size=None, endness=None, memory=None, page_addr=None, cooperate=False, **kwargs)[源代码]
参数:
merge(others, merge_conditions, common_ancestor=None, page_addr=None, memory=None, changed_offsets=None)[源代码]

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)

参数:
  • others (list[UltraPage]) -- 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

  • page_addr (int | None)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

concrete_load(addr, size, writing=False, with_bitmap=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

返回:

A memoryview into the loaded bytes.

changed_bytes(other, page_addr=None)[源代码]
返回类型:

set[int]

state: angr.SimState
replace_all_with_offsets(offsets, old, new, memory=None)[源代码]
参数:
class angr.storage.memory_mixins.paged_memory.pages.refcount_mixin.RefcountMixin(**kwargs)[源代码]

基类:MemoryMixin

This mixin adds a locked reference counter and methods to manipulate it, to facilitate copy-on-write optimizations.

__init__(**kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

acquire_unique()[源代码]

Call this function to return a version of this page which can be used for writing, which may or may not be the same object as before. If you use this you must immediately replace the shared reference you previously had with the new unique copy.

acquire_shared()[源代码]

Call this function to indicate that this page has had a reference added to it and must be copied before it can be acquired uniquely again. Creating the object implicitly starts it with one shared reference.

返回类型:

None

release_shared()[源代码]

Call this function to indicate that this page has had a shared reference to it released

返回类型:

None

class angr.storage.memory_mixins.paged_memory.pages.permissions_mixin.PermissionsMixin(permissions=None, **kwargs)[源代码]

基类:MemoryMixin

This mixin adds a permissions_bits field and properties for extracting the read/write/exec permissions. It does NOT add permissions checking.

参数:

permissions (int | claripy.ast.BV | None)

__init__(permissions=None, **kwargs)[源代码]
参数:

permissions (int | BV | None)

copy(memo)[源代码]

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!

参数:

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

property perm_read
property perm_write
property perm_exec
class angr.storage.memory_mixins.paged_memory.pages.history_tracking_mixin.HistoryTrackingMixin(*args, **kwargs)[源代码]

基类:RefcountMixin, MemoryMixin

Tracks the history of memory writes.

__init__(*args, **kwargs)[源代码]
store(addr, data, size=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

acquire_unique()[源代码]

Call this function to return a version of this page which can be used for writing, which may or may not be the same object as before. If you use this you must immediately replace the shared reference you previously had with the new unique copy.

parents()[源代码]
changed_bytes(other, **kwargs)[源代码]
返回类型:

set[int] | None

all_bytes_changed_in_history()[源代码]
返回类型:

SegmentList

class angr.storage.memory_mixins.paged_memory.pages.ispo_mixin.ISPOMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

An implementation of the International Stateless Persons Organisation, a mixin which should be applied as a bottom layer for memories which have no state and must redirect certain operations to a parent memory. Main usecase is for memory region classes which are stored within other memories, such as pages.

参数:
  • memory_id (str | None)

  • endness (str)

set_state(state)[源代码]

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

class angr.storage.memory_mixins.paged_memory.pages.cooperation.CooperationBase[源代码]

基类:Generic[T]

Any given subclass of this class which is not a subclass of MemoryMixin should have the property that any subclass it which is a subclass of MemoryMixin should all work with the same datatypes

class angr.storage.memory_mixins.paged_memory.pages.cooperation.MemoryObjectMixin[源代码]

基类:CooperationBase[SimMemoryObject]

Uses SimMemoryObjects in region storage. With this, load will return a list of tuple (address, MO) and store will take a MO.

class angr.storage.memory_mixins.paged_memory.pages.cooperation.MemoryObjectSetMixin[源代码]

基类:CooperationBase

Uses sets of SimMemoryObjects in region storage.

class angr.storage.memory_mixins.paged_memory.pages.cooperation.BasicClaripyCooperation[源代码]

基类:CooperationBase

Mix this (along with PageBase) into a storage class which supports loading and storing claripy bitvectors and it will be able to work as a page in the paged memory model.

class angr.storage.memory_mixins.paged_memory.pages.list_page.ListPage(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]

基类:MemoryObjectMixin, PageBase

This class implements a page memory mixin with lists as the main content store.

__init__(memory=None, content=None, sinkhole=None, mo_cmp=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, endness=None, page_addr=None, memory=None, cooperate=False, **kwargs)[源代码]
store(addr, data, size=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
erase(addr, size=None, **kwargs)[源代码]

Set [addr:addr+size) to uninitialized. In many cases this will be faster than overwriting those locations with new values. This is commonly used during static data flow analysis.

参数:
  • addr -- The address to start erasing.

  • size -- The number of bytes for erasing.

返回类型:

None

返回:

None

merge(others, merge_conditions, common_ancestor=None, page_addr=None, memory=None, changed_offsets=None)[源代码]

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)

参数:
  • others (list[ListPage]) -- 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

  • page_addr (int | None)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

changed_bytes(other, page_addr=None)[源代码]
参数:
class angr.storage.memory_mixins.paged_memory.pages.ultra_page.UltraPage(memory=None, init_zero=False, **kwargs)[源代码]

基类:MemoryObjectMixin, PageBase

Default page implementation

SUPPORTS_CONCRETE_LOAD: bool = True
__init__(memory=None, init_zero=False, **kwargs)[源代码]
classmethod new_from_shared(data, memory=None, **kwargs)[源代码]
copy(memo)[源代码]

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!

参数:

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

load(addr, size=None, page_addr=None, endness=None, memory=None, cooperate=False, **kwargs)[源代码]
store(addr, data, size=None, endness=None, memory=None, page_addr=None, cooperate=False, **kwargs)[源代码]
参数:
merge(others, merge_conditions, common_ancestor=None, page_addr=None, memory=None, changed_offsets=None)[源代码]

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)

参数:
  • others (list[UltraPage]) -- 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

  • page_addr (int | None)

  • changed_offsets (set[int] | None)

返回:

True if the state plugins are actually merged.

返回类型:

bool

concrete_load(addr, size, writing=False, with_bitmap=False, **kwargs)[源代码]

Set SUPPORTS_CONCRETE_LOAD to True and implement concrete_load if reading concrete bytes is faster in this memory model.

参数:
  • addr -- The address to load from.

  • size -- Size of the memory read.

  • writing

返回:

A memoryview into the loaded bytes.

changed_bytes(other, page_addr=None)[源代码]
返回类型:

set[int]

state: angr.SimState
replace_all_with_offsets(offsets, old, new, memory=None)[源代码]
参数:
class angr.storage.memory_mixins.regioned_memory.AbstractMergerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

AbstractMergerMixin handles merging initialized values.

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.regioned_memory.MemoryRegionMetaMixin(related_function_addr=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(related_function_addr=None, **kwargs)[源代码]
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!

参数:

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

property is_stack
property related_function_addr
get_abstract_locations(addr, size)[源代码]

Get a list of abstract locations that is within the range of [addr, addr + size]

This implementation is pretty slow. But since this method won't be called frequently, we can live with the bad implementation for now.

参数:
  • addr -- Starting address of the memory region.

  • size -- Size of the memory region, in bytes.

返回:

A list of covered AbstractLocation objects, or an empty list if there is none.

store(addr, data, size=None, *, bbl_addr=None, stmt_id=None, ins_addr=None, endness=None, **kwargs)[源代码]
load(addr, size=None, *, bbl_addr=None, stmt_idx=None, ins_addr=None, **kwargs)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

dbg_print(indent=0)[源代码]

Print out debugging information

class angr.storage.memory_mixins.regioned_memory.RegionCategoryMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

property category

reg, mem, or file.

Type:

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

class angr.storage.memory_mixins.regioned_memory.RegionedAddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(read_strategies=None, write_strategies=None, **kwargs)[源代码]
set_state(state)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

class angr.storage.memory_mixins.regioned_memory.RegionedMemoryMixin(write_targets_limit=2048, read_targets_limit=4096, stack_region_map=None, generic_region_map=None, stack_size=65536, cle_memory_backer=None, dict_memory_backer=None, regioned_memory_cls=None, **kwargs)[源代码]

基类:MemoryMixin

Regioned memory. This mixin manages multiple memory regions. Each address is represented as a tuple of (region ID, offset into the region), which is called a regioned address.

Converting absolute addresses into regioned addresses: We map an absolute address to a region by looking up which region this address belongs to in the region map. Currently this is only enabled for stack. Heap support has not landed yet.

When start analyzing a function, the user should call set_stack_address_mapping() to create a new region mapping. Likewise, when exiting from a function, the user should cancel the previous mapping by calling unset_stack_address_mapping().

__init__(write_targets_limit=2048, read_targets_limit=4096, stack_region_map=None, generic_region_map=None, stack_size=65536, cle_memory_backer=None, dict_memory_backer=None, regioned_memory_cls=None, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, *, endness=None, condition=None, **kwargs)[源代码]
参数:
  • size (int | BV | None)

  • condition (Bool | None)

store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
参数:

size (int | None)

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

find(addr, data, max_search, **kwargs)[源代码]
参数:

addr (int | Bits)

set_state(state)[源代码]

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

replace_all(old, new)[源代码]
参数:
set_stack_address_mapping(absolute_address, region_id, related_function_address=None)[源代码]

Create a new mapping between an absolute address (which is the base address of a specific stack frame) and a region ID.

参数:
  • absolute_address (int) -- The absolute memory address.

  • region_id (str) -- The region ID.

  • related_function_address (Optional[int]) -- Related function address.

unset_stack_address_mapping(absolute_address)[源代码]

Remove a stack mapping.

参数:

absolute_address (int) -- An absolute memory address that is the base address of the stack frame to destroy.

stack_id(function_address)[源代码]

Return a memory region ID for a function. If the default region ID exists in the region mapping, an integer will appended to the region name. In this way we can handle recursive function calls, or a function that appears more than once in the call frame.

This also means that stack_id() should only be called when creating a new stack frame for a function. You are not supposed to call this function every time you want to map a function address to a stack ID.

参数:

function_address (int) -- Address of the function.

返回类型:

str

返回:

ID of the new memory region.

set_stack_size(size)[源代码]
参数:

size (int)

class angr.storage.memory_mixins.regioned_memory.StaticFindMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:SmartFindMixin

Implements data finding for abstract memory.

参数:
  • memory_id (str | None)

  • endness (str)

find(addr, data, max_search, *, default=None, endness=None, chunk_size=None, max_symbolic_bytes=None, condition=None, char_size=1, **kwargs)[源代码]
class angr.storage.memory_mixins.regioned_memory.regioned_memory_mixin.RegionedMemoryMixin(write_targets_limit=2048, read_targets_limit=4096, stack_region_map=None, generic_region_map=None, stack_size=65536, cle_memory_backer=None, dict_memory_backer=None, regioned_memory_cls=None, **kwargs)[源代码]

基类:MemoryMixin

Regioned memory. This mixin manages multiple memory regions. Each address is represented as a tuple of (region ID, offset into the region), which is called a regioned address.

Converting absolute addresses into regioned addresses: We map an absolute address to a region by looking up which region this address belongs to in the region map. Currently this is only enabled for stack. Heap support has not landed yet.

When start analyzing a function, the user should call set_stack_address_mapping() to create a new region mapping. Likewise, when exiting from a function, the user should cancel the previous mapping by calling unset_stack_address_mapping().

__init__(write_targets_limit=2048, read_targets_limit=4096, stack_region_map=None, generic_region_map=None, stack_size=65536, cle_memory_backer=None, dict_memory_backer=None, regioned_memory_cls=None, **kwargs)[源代码]
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!

参数:

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

load(addr, size=None, *, endness=None, condition=None, **kwargs)[源代码]
参数:
  • size (int | BV | None)

  • condition (Bool | None)

store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
参数:

size (int | None)

merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

find(addr, data, max_search, **kwargs)[源代码]
参数:

addr (int | Bits)

set_state(state)[源代码]

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

replace_all(old, new)[源代码]
参数:
set_stack_address_mapping(absolute_address, region_id, related_function_address=None)[源代码]

Create a new mapping between an absolute address (which is the base address of a specific stack frame) and a region ID.

参数:
  • absolute_address (int) -- The absolute memory address.

  • region_id (str) -- The region ID.

  • related_function_address (Optional[int]) -- Related function address.

unset_stack_address_mapping(absolute_address)[源代码]

Remove a stack mapping.

参数:

absolute_address (int) -- An absolute memory address that is the base address of the stack frame to destroy.

stack_id(function_address)[源代码]

Return a memory region ID for a function. If the default region ID exists in the region mapping, an integer will appended to the region name. In this way we can handle recursive function calls, or a function that appears more than once in the call frame.

This also means that stack_id() should only be called when creating a new stack frame for a function. You are not supposed to call this function every time you want to map a function address to a stack ID.

参数:

function_address (int) -- Address of the function.

返回类型:

str

返回:

ID of the new memory region.

set_stack_size(size)[源代码]
参数:

size (int)

class angr.storage.memory_mixins.regioned_memory.region_data.AddressWrapper(region, region_base_addr, address, is_on_stack, function_address)[源代码]

基类:object

AddressWrapper is used in SimAbstractMemory, which provides extra meta information for an address (or a ValueSet object) that is normalized from an integer/BVV/StridedInterval.

参数:
  • region (str)

  • region_base_addr (int)

  • is_on_stack (bool)

  • function_address (int | None)

__init__(region, region_base_addr, address, is_on_stack, function_address)[源代码]

Constructor for the class AddressWrapper.

参数:
  • region (str) -- Name of the memory regions it belongs to.

  • region_base_addr (int) -- Base address of the memory region

  • address -- An address (not a ValueSet object).

  • is_on_stack (bool) -- Whether this address is on a stack region or not.

  • function_address (int | None) -- Related function address (if any).

region
region_base_addr
address
is_on_stack
function_address
to_valueset(state)[源代码]

Convert to a ValueSet instance

参数:

state -- A state

返回:

The converted ValueSet instance

class angr.storage.memory_mixins.regioned_memory.region_data.RegionDescriptor(region_id, base_address, related_function_address=None)[源代码]

基类:object

Descriptor for a memory region ID.

__init__(region_id, base_address, related_function_address=None)[源代码]
region_id
base_address
related_function_address
class angr.storage.memory_mixins.regioned_memory.region_data.RegionMap(is_stack)[源代码]

基类:object

Mostly used in SimAbstractMemory, RegionMap stores a series of mappings between concrete memory address ranges and memory regions, like stack frames and heap regions.

__init__(is_stack)[源代码]

Constructor

参数:

is_stack -- Whether this is a region map for stack frames or not. Different strategies apply for stack regions.

property is_empty
property stack_base
property region_ids
copy(memo=None, **kwargs)
map(absolute_address, region_id, related_function_address=None)[源代码]

Add a mapping between an absolute address and a region ID. If this is a stack region map, all stack regions beyond (lower than) this newly added regions will be discarded.

参数:
  • absolute_address -- An absolute memory address.

  • region_id -- ID of the memory region.

  • related_function_address -- A related function address, mostly used for stack regions.

unmap_by_address(absolute_address)[源代码]

Removes a mapping based on its absolute address.

参数:

absolute_address -- An absolute address

absolutize(region_id, relative_address)[源代码]

Convert a relative address in some memory region to an absolute address.

参数:
  • region_id -- The memory region ID

  • relative_address -- The relative memory offset in that memory region

返回:

An absolute address if converted, or an exception is raised when region id does not exist.

relativize(absolute_address, target_region_id=None)[源代码]

Convert an absolute address to the memory offset in a memory region.

Note that if an address belongs to heap region is passed in to a stack region map, it will be converted to an offset included in the closest stack frame, and vice versa for passing a stack address to a heap region. Therefore you should only pass in address that belongs to the same category (stack or non-stack) of this region map.

参数:

absolute_address -- An absolute memory address

返回:

A tuple of the closest region ID, the relative offset, and the related function address.

class angr.storage.memory_mixins.regioned_memory.region_category_mixin.RegionCategoryMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

参数:
  • memory_id (str | None)

  • endness (str)

property category

reg, mem, or file.

Type:

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

class angr.storage.memory_mixins.regioned_memory.static_find_mixin.StaticFindMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:SmartFindMixin

Implements data finding for abstract memory.

参数:
  • memory_id (str | None)

  • endness (str)

find(addr, data, max_search, *, default=None, endness=None, chunk_size=None, max_symbolic_bytes=None, condition=None, char_size=1, **kwargs)[源代码]
class angr.storage.memory_mixins.regioned_memory.abstract_address_descriptor.AbstractAddressDescriptor[源代码]

基类:object

AbstractAddressDescriptor describes a list of region+offset tuples. It provides a convenient way for accessing the cardinality (the total number of addresses) without enumerating or creating all addresses in static mode.

__init__()[源代码]
property cardinality
add_regioned_address(region, addr)[源代码]
参数:
clear()[源代码]
class angr.storage.memory_mixins.regioned_memory.region_meta_mixin.Segment(offset, size=0)[源代码]

基类:object

Segment represents a continuous memory region.

__init__(offset, size=0)[源代码]
class angr.storage.memory_mixins.regioned_memory.region_meta_mixin.AbstractLocation(bbl_key, stmt_id, region_id, segment_list=None, region_offset=None, size=None)[源代码]

基类:object

AbstractLocation represents a location in memory.

__init__(bbl_key, stmt_id, region_id, segment_list=None, region_offset=None, size=None)[源代码]
property basicblock_key
property statement_id
property region
property segments
update(region_offset, size)[源代码]
copy()[源代码]
merge(other)[源代码]
class angr.storage.memory_mixins.regioned_memory.region_meta_mixin.MemoryRegionMetaMixin(related_function_addr=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(related_function_addr=None, **kwargs)[源代码]
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!

参数:

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

property is_stack
property related_function_addr
get_abstract_locations(addr, size)[源代码]

Get a list of abstract locations that is within the range of [addr, addr + size]

This implementation is pretty slow. But since this method won't be called frequently, we can live with the bad implementation for now.

参数:
  • addr -- Starting address of the memory region.

  • size -- Size of the memory region, in bytes.

返回:

A list of covered AbstractLocation objects, or an empty list if there is none.

store(addr, data, size=None, *, bbl_addr=None, stmt_id=None, ins_addr=None, endness=None, **kwargs)[源代码]
load(addr, size=None, *, bbl_addr=None, stmt_idx=None, ins_addr=None, **kwargs)[源代码]
merge(others, merge_conditions, common_ancestor=None)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

widen(others)[源代码]

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.

参数:

others -- the other state plugin

返回:

True if the state plugin is actually widened.

返回类型:

bool

dbg_print(indent=0)[源代码]

Print out debugging information

class angr.storage.memory_mixins.regioned_memory.abstract_merger_mixin.AbstractMergerMixin(memory_id=None, endness='Iend_BE')[源代码]

基类:MemoryMixin

AbstractMergerMixin handles merging initialized values.

参数:
  • memory_id (str | None)

  • endness (str)

class angr.storage.memory_mixins.regioned_memory.regioned_address_concretization_mixin.RegionedAddressConcretizationMixin(read_strategies=None, write_strategies=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(read_strategies=None, write_strategies=None, **kwargs)[源代码]
set_state(state)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

class angr.storage.memory_mixins.slotted_memory.SlottedMemoryMixin(width=None, **kwargs)[源代码]

基类:MemoryMixin

__init__(width=None, **kwargs)[源代码]
set_state(state)[源代码]

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

copy(memo)[源代码]

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!

参数:

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)[源代码]

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)

参数:
  • 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

返回:

True if the state plugins are actually merged.

返回类型:

bool

load(addr, size=None, *, endness=None, **kwargs)[源代码]
store(addr, data, size=None, *, endness=None, **kwargs)[源代码]
changed_bytes(other)[源代码]

Concretization Strategies

class angr.concretization_strategies.single.SimConcretizationStrategySingle(filter=None, exact=True)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that ensures a single solution for an address.

class angr.concretization_strategies.eval.SimConcretizationStrategyEval(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves an address into some limited number of solutions. Always handles the concretization, but only returns a maximum of limit number of solutions. Therefore, should only be used as the fallback strategy.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.norepeats.SimConcretizationStrategyNorepeats(repeat_expr, repeat_constraints=None, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves addresses, without repeating.

__init__(repeat_expr, repeat_constraints=None, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

copy()[源代码]

Returns a copy of the strategy, if there is data that should be kept separate between states. If not, returns self.

merge(others)[源代码]

Merges this strategy with others (if there is data that should be kept separate between states. If not, is a no-op.

class angr.concretization_strategies.solutions.SimConcretizationStrategySolutions(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves an address into some limited number of solutions.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.nonzero_range.SimConcretizationStrategyNonzeroRange(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves a range in a non-zero location.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.range.SimConcretizationStrategyRange(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves addresses to a range.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.max.SimConcretizationStrategyMax(max_addr=None)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that returns the maximum address.

参数:

max_addr (int | None)

__init__(max_addr=None)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

  • max_addr (int | None)

class angr.concretization_strategies.norepeats_range.SimConcretizationStrategyNorepeatsRange(repeat_expr, min=None, granularity=None, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves a range, with no repeats.

__init__(repeat_expr, min=None, granularity=None, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

copy()[源代码]

Returns a copy of the strategy, if there is data that should be kept separate between states. If not, returns self.

merge(others)[源代码]

Merges this strategy with others (if there is data that should be kept separate between states. If not, is a no-op.

class angr.concretization_strategies.nonzero.SimConcretizationStrategyNonzero(filter=None, exact=True)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that returns any non-zero solution.

class angr.concretization_strategies.any.SimConcretizationStrategyAny(filter=None, exact=True)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that returns any single solution.

class angr.concretization_strategies.controlled_data.SimConcretizationStrategyControlledData(limit, fixed_addrs, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that constraints the address to controlled data. Controlled data consists of symbolic data and the addresses given as arguments. memory.

__init__(limit, fixed_addrs, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

class angr.concretization_strategies.unlimited_range.SimConcretizationStrategyUnlimitedRange(limit, **kwargs)[源代码]

基类:SimConcretizationStrategy

Concretization strategy that resolves addresses to a range without checking if the number of possible addresses is within the limit.

__init__(limit, **kwargs)[源代码]

Initializes the base SimConcretizationStrategy.

参数:
  • filter -- A function, taking arguments of (SimMemory, claripy.AST) that determines if this strategy can handle resolving the provided AST.

  • exact -- A flag (default: True) that determines if the convenience resolution functions provided by this class use exact or approximate resolution.

Simulation Manager

class angr.sim_manager.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)[源代码]

基类: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.

参数:
  • 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.

变量:
  • 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)[源代码]
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)[源代码]

Mulpyplex across several stashes.

参数:

stashes -- the stashes to mulpyplex

返回:

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

copy(deep=False)[源代码]

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)[源代码]

Use an exploration technique with this SimulationManager.

Techniques can be found in angr.exploration_techniques.

参数:

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

返回:

The technique that was added, for convenience

remove_technique(tech)[源代码]

Remove an exploration technique from a list of active techniques.

参数:

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)[源代码]

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)[源代码]

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.

参数:
  • 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.

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

complete()[源代码]

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)[源代码]

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.

参数:
  • 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:

参数:
  • 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

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

step_state(state, successor_func=None, error_list=None, **run_args)[源代码]

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

filter(state, filter_func=None)[源代码]

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

selector(state, selector_func=None)[源代码]

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

successors(state, successor_func=None, **run_args)[源代码]

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

prune(filter_func=None, from_stash='active', to_stash='pruned')[源代码]

Prune unsatisfiable states from a stash.

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

populate(stash, states)[源代码]

Populate a stash with a collection of states.

参数:
  • stash -- A stash to populate.

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

absorb(simgr)[源代码]

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)[源代码]

Move states from one stash to another.

参数:
  • 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)

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

stash(filter_func=None, from_stash='active', to_stash='stashed')[源代码]

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

unstash(filter_func=None, to_stash='active', from_stash='stashed')[源代码]

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

drop(filter_func=None, stash='active')[源代码]

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

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

apply(state_func=None, stash_func=None, stash='active', to_stash=None)[源代码]

Applies a given function to a given stash.

参数:
  • 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.

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

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

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.

参数:
  • 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')

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

merge(merge_func=None, merge_key=None, stash='active', prune=True)[源代码]

Merge the states in a given stash.

参数:
  • 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

返回:

The simulation manager, for chaining.

返回类型:

SimulationManager

class angr.sim_manager.ErrorRecord(state, error, traceback)[源代码]

基类:object

A container class for a state and an error that was thrown during its execution. You can find these in SimulationManager.errored.

变量:
  • state -- The state that encountered an error, at the point in time just before the erroring step began.

  • error -- The error that was thrown.

  • traceback -- The traceback for the error that was thrown.

__init__(state, error, traceback)[源代码]
debug()[源代码]

Launch a postmortem debug shell at the site of the error.

reraise()[源代码]
class angr.state_hierarchy.StateHierarchy[源代码]

基类: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__()[源代码]
get_ref(obj)[源代码]
dead_ref(ref)[源代码]
defer_cleanup()[源代码]
add_state(s)[源代码]
add_history(h)[源代码]
simplify()[源代码]
full_simplify()[源代码]
lineage(h)[源代码]

Returns the lineage of histories leading up to h.

all_successors(h)[源代码]
history_successors(h)[源代码]
history_predecessors(h)[源代码]
history_contains(h)[源代码]
unreachable_state(state)[源代码]
unreachable_history(h)[源代码]
most_mergeable(states)[源代码]

Find the "most mergeable" set of states from those provided.

参数:

states -- a list of states

返回:

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

Exploration Techniques

class angr.exploration_techniques.DFS(deferred_stash='deferred')[源代码]

基类:ExplorationTechnique

Depth-first search.

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

__init__(deferred_stash='deferred')[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.Bucketizer[源代码]

基类:ExplorationTechnique

Loop bucketization: Pick log(n) paths out of n possible paths, and stash (or drop) everything else.

successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.CallFunctionGoal(function, arguments)[源代码]

基类:BaseGoal

A goal that prioritizes states reaching certain function, and optionally with specific arguments. Note that constraints on arguments (and on function address as well) have to be identifiable on an accurate CFG. For example, you may have a CallFunctionGoal saying "call printf with the first argument being 'Hello, world'", and CFGEmulated must be able to figure our the first argument to printf is in fact "Hello, world", not some symbolic strings that will be constrained to "Hello, world" during symbolic execution (or simulation, however you put it).

REQUIRE_CFG_STATES = True
__init__(function, arguments)[源代码]
check(cfg, state, peek_blocks)[源代码]

Check if the specified function will be reached with certain arguments.

参数:
  • cfg

  • state

  • peek_blocks

返回:

check_state(state)[源代码]

Check if the specific function is reached with certain arguments

参数:

state (angr.SimState) -- The state to check

返回:

True if the function is reached with certain arguments, False otherwise.

返回类型:

bool

class angr.exploration_techniques.Director(peek_blocks=100, peek_functions=5, goals=None, cfg_keep_states=False, goal_satisfied_callback=None, num_fallback_states=5)[源代码]

基类:ExplorationTechnique

An exploration technique for directed symbolic execution.

A control flow graph (using CFGEmulated) is built and refined during symbolic execution. Each time the execution reaches a block that is outside of the CFG, the CFG recovery will be triggered with that state, with a maximum recovery depth (100 by default). If we see a basic block during state stepping that is not yet in the control flow graph, we go back to control flow graph recovery and "peek" more blocks forward.

When stepping a simulation manager, all states are categorized into three different categories:

  • Might reach the destination within the peek depth. Those states are prioritized.

  • Will not reach the destination within the peek depth. Those states are de-prioritized. However, there is a little chance for those states to be explored as well in order to prevent over-fitting.

__init__(peek_blocks=100, peek_functions=5, goals=None, cfg_keep_states=False, goal_satisfied_callback=None, num_fallback_states=5)[源代码]

Constructor.

step(simgr, stash='active', **kwargs)[源代码]
参数:
  • simgr

  • stash

  • kwargs

返回:

add_goal(goal)[源代码]

Add a goal.

参数:

goal (BaseGoal) -- The goal to add.

返回:

None

class angr.exploration_techniques.DrillerCore(trace, fuzz_bitmap=None)[源代码]

基类:ExplorationTechnique

An exploration technique that symbolically follows an input looking for new state transitions.

It has to be used with Tracer exploration technique. Results are put in 'diverted' stash.

__init__(trace, fuzz_bitmap=None)[源代码]

:param trace : The basic block trace. :type fuzz_bitmap: :param fuzz_bitmap: AFL's bitmap of state transitions. Defaults to saying every transition is worth satisfying.

setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.ExecuteAddressGoal(addr)[源代码]

基类:BaseGoal

A goal that prioritizes states reaching (or are likely to reach) certain address in some specific steps.

__init__(addr)[源代码]
check(cfg, state, peek_blocks)[源代码]

Check if the specified address will be executed

参数:
  • cfg

  • state

  • peek_blocks (int)

返回:

返回类型:

bool

check_state(state)[源代码]

Check if the current address is the target address.

参数:

state (angr.SimState) -- The state to check.

返回:

True if the current address is the target address, False otherwise.

返回类型:

bool

class angr.exploration_techniques.ExplorationTechnique[源代码]

基类:object

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

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__()[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
filter(simgr, state, **kwargs)[源代码]

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.

参数:
selector(simgr, state, **kwargs)[源代码]

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.

参数:
step_state(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
complete(simgr)[源代码]

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.

参数:

simgr (angr.SimulationManager)

class angr.exploration_techniques.Explorer(find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False)[源代码]

基类:ExplorationTechnique

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

The "find" and "avoid" parameters may be any of:

  • An address to find

  • A set or list of addresses to find

  • A function that takes a path and returns whether or not it matches.

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

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

__init__(find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False)[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
filter(simgr, state, **kwargs)[源代码]

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.

参数:
complete(simgr)[源代码]

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.

参数:

simgr (angr.SimulationManager)

class angr.exploration_techniques.LengthLimiter(max_length, drop=False)[源代码]

基类:ExplorationTechnique

Length limiter on paths.

__init__(max_length, drop=False)[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.LocalLoopSeer(bound=None, bound_reached=None, discard_stash='spinning')[源代码]

基类:ExplorationTechnique

LocalLoopSeer monitors exploration and maintains all loop-related data without relying on a control flow graph.

__init__(bound=None, bound_reached=None, discard_stash='spinning')[源代码]
参数:
  • bound -- Limit the number of iterations a loop may be executed.

  • bound_reached -- If provided, should be a function that takes the LoopSeer and the succ_state. Will be called when loop execution reach the given bound. Default to moving states that exceed the loop limit to a discard stash.

  • discard_stash -- Name of the stash containing states exceeding the loop limit.

setup(simgr)[源代码]

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

参数:

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

filter(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.LoopSeer(cfg=None, functions=None, loops=None, use_header=False, bound=None, bound_reached=None, discard_stash='spinning', limit_concrete_loops=True)[源代码]

基类:ExplorationTechnique

This exploration technique monitors exploration and maintains all loop-related data (well, currently it is just the loop trip counts, but feel free to add something else).

__init__(cfg=None, functions=None, loops=None, use_header=False, bound=None, bound_reached=None, discard_stash='spinning', limit_concrete_loops=True)[源代码]
参数:
  • cfg -- Normalized CFG is required.

  • functions -- Function(s) containing the loop(s) to be analyzed.

  • loops -- Specific group of Loop(s) to be analyzed, if this is None we run the LoopFinder analysis.

  • use_header -- Whether to use header based trip counter to compare with the bound limit.

  • bound -- Limit the number of iterations a loop may be executed.

  • bound_reached -- If provided, should be a function that takes the LoopSeer and the succ_state. Will be called when loop execution reach the given bound. Default to moving states that exceed the loop limit to a discard stash.

  • discard_stash -- Name of the stash containing states exceeding the loop limit.

  • limit_concrete_loops -- If False, do not limit a loop back-edge if it is the only successor (Defaults to True to maintain the original behavior)

setup(simgr)[源代码]

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

参数:

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

filter(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.ManualMergepoint(address, wait_counter=10, prune=True)[源代码]

基类:ExplorationTechnique

__init__(address, wait_counter=10, prune=True)[源代码]
setup(simgr)[源代码]

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

参数:

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

mark_nofilter(simgr, stash)[源代码]
mark_okfilter(simgr, stash)[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.MemoryWatcher(min_memory=512, memory_stash='lowmem')[源代码]

基类:ExplorationTechnique

Memory Watcher

参数:
  • min_memory (int,optional) -- Minimum amount of free memory in MB before stopping execution (default: 95% memory use)

  • memory_stash (str, optional) -- What to call the low memory stash (default: 'lowmem')

At each step, keep an eye on how much memory is left on the system. Stash off states to effectively stop execution if we're below a given threshold.

__init__(min_memory=512, memory_stash='lowmem')[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.Oppologist[源代码]

基类:ExplorationTechnique

The Oppologist is an exploration technique that forces uncooperative code through qemu.

__init__()[源代码]
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.Slicecutor(annotated_cfg, force_taking_exit=False, force_sat=False)[源代码]

基类:ExplorationTechnique

The Slicecutor is an exploration that executes provided code slices.

参数:

force_sat (bool)

__init__(annotated_cfg, force_taking_exit=False, force_sat=False)[源代码]

All parameters except annotated_cfg are optional.

参数:
  • annotated_cfg -- The AnnotatedCFG that provides the code slice.

  • force_taking_exit -- Set to True if you want to create a successor based on our slice in case of unconstrained successors.

  • force_sat (bool) -- If a branch specified by the slice is unsatisfiable, set this option to True if you want to force it to be satisfiable and be taken anyway.

setup(simgr)[源代码]

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

参数:

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

filter(simgr, state, **kwargs)[源代码]

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.

参数:
step_state(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.Spiller(src_stash='active', min=5, max=10, staging_stash='spill_stage', staging_min=10, staging_max=20, pickle_callback=None, unpickle_callback=None, post_pickle_callback=None, priority_key=None, vault=None, states_collection=None)[源代码]

基类:ExplorationTechnique

Automatically spill states out. It can spill out states to a different stash, spill them out to ANA, or first do the former and then (after enough states) the latter.

__init__(src_stash='active', min=5, max=10, staging_stash='spill_stage', staging_min=10, staging_max=20, pickle_callback=None, unpickle_callback=None, post_pickle_callback=None, priority_key=None, vault=None, states_collection=None)[源代码]

Initializes the spiller.

参数:
  • max -- the number of states that are not spilled

  • src_stash -- the stash from which to spill states (default: active)

  • staging_stash -- the stash to which to spill states (default: "spill_stage")

  • staging_max -- the number of states that can be in the staging stash before things get spilled to ANA (default: None. If staging_stash is set, then this means unlimited, and ANA will not be used).

  • priority_key -- a function that takes a state and returns its numerical priority (MAX_INT is lowest priority). By default, self.state_priority will be used, which prioritizes by object ID.

  • vault -- an angr.Vault object to handle storing and loading of states. If not provided, an angr.vaults.VaultShelf will be created with a temporary file.

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
static state_priority(state)[源代码]
class angr.exploration_techniques.StochasticSearch(start_state, restart_prob=0.0001)[源代码]

基类:ExplorationTechnique

Stochastic Search.

Will only keep one path active at a time, any others will be discarded. Before each pass through, weights are randomly assigned to each basic block. These weights form a probability distribution for determining which state remains after splits. When we run out of active paths to step, we start again from the start state.

__init__(start_state, restart_prob=0.0001)[源代码]
参数:
  • start_state -- The initial state from which exploration stems.

  • restart_prob -- The probability of randomly restarting the search (default 0.0001).

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.StubStasher[源代码]

基类:ExplorationTechnique

Stash states that reach a stub SimProcedure.

static post_filter(state)[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.Suggestions[源代码]

基类:ExplorationTechnique

An exploration technique which analyzes failure cases and logs suggestions for how to mitigate them in future analyses.

__init__()[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
static report(state, event)[源代码]
class angr.exploration_techniques.TechniqueBuilder(setup=None, step_state=None, step=None, successors=None, filter=None, selector=None, complete=None)[源代码]

基类:ExplorationTechnique

This meta technique could be used to hook a couple of simulation manager methods without actually creating a new exploration technique, for example:

class SomeComplexAnalysis(Analysis):

def do_something():

simgr = self.project.factory.simulation_manager() simgr.use_tech(ProxyTechnique(step_state=self._step_state)) simgr.run()

def _step_state(self, state):

# Do stuff! pass

In the above example, the _step_state method can access all the necessary stuff, hidden in the analysis instance, without passing that instance to a one-shot-styled exploration technique.

__init__(setup=None, step_state=None, step=None, successors=None, filter=None, selector=None, complete=None)[源代码]
class angr.exploration_techniques.Threading(threads=8, local_stash='thread_local')[源代码]

基类:ExplorationTechnique

Enable multithreading.

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

__init__(threads=8, local_stash='thread_local')[源代码]
step(simgr, stash='active', error_list=None, target_stash=None, **kwargs)[源代码]

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

参数:
inner_step(state, simgr, **kwargs)[源代码]
class angr.exploration_techniques.Timeout(timeout=None)[源代码]

基类:ExplorationTechnique

Timeout exploration technique that stops an active exploration if the run time exceeds a predefined timeout

__init__(timeout=None)[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.Tracer(trace=None, resiliency=False, keep_predecessors=1, crash_addr=None, syscall_data=None, copy_states=False, fast_forward_to_entry=True, mode='strict', aslr=True, follow_unsat=False)[源代码]

基类:ExplorationTechnique

An exploration technique that follows an angr path with a concrete input. The tracing result is the state at the last address of the trace, which can be found in the 'traced' stash.

If the given concrete input makes the program crash, you should provide crash_addr, and the crashing state will be found in the 'crashed' stash.

参数:
  • trace -- The basic block trace.

  • resiliency -- Should we continue to step forward even if qemu and angr disagree?

  • keep_predecessors -- Number of states before the final state we should log.

  • crash_addr -- If the trace resulted in a crash, provide the crashing instruction pointer here, and the 'crashed' stash will be populated with the crashing state.

  • syscall_data -- Data related to various syscalls recorded by tracer for replaying

  • copy_states -- Whether COPY_STATES should be enabled for the tracing state. It is off by default because most tracing workloads benefit greatly from not performing copying. You want to enable it if you want to see the missed states. It will be re-added for the last 2% of the trace in order to set the predecessors list correctly. If you turn this on you may want to enable the LAZY_SOLVES option.

  • mode -- Tracing mode.

  • aslr -- Whether there are aslr slides. if not, tracer uses trace address as state address.

  • follow_unsat -- Whether unsatisfiable states should be treated as potential successors or not.

变量:

predecessors -- A list of states in the history before the final state.

__init__(trace=None, resiliency=False, keep_predecessors=1, crash_addr=None, syscall_data=None, copy_states=False, fast_forward_to_entry=True, mode='strict', aslr=True, follow_unsat=False)[源代码]
set_fd_data(fd_data)[源代码]

Set concrete bytes of various fds read by the program

参数:

fd_data (dict[int, bytes])

setup(simgr)[源代码]

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

参数:

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

complete(simgr)[源代码]

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.

参数:

simgr (angr.SimulationManager)

filter(simgr, state, **kwargs)[源代码]

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.

参数:
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
step_state(simgr, state, **kwargs)[源代码]

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.

参数:
classmethod crash_windup(state, crash_addr)[源代码]
class angr.exploration_techniques.UniqueSearch(similarity_func=None, deferred_stash='deferred')[源代码]

基类:ExplorationTechnique

Unique Search.

Will only keep one path active at a time, any others will be deferred. The state that is explored depends on how unique it is relative to the other deferred states. A path's uniqueness is determined by its average similarity between the other (deferred) paths. Similarity is calculated based on the supplied similarity_func, which by default is: The (L2) distance between the counts of the state addresses in the history of the path.

__init__(similarity_func=None, deferred_stash='deferred')[源代码]
参数:
  • similarity_func -- How to calculate similarity between two states.

  • deferred_stash -- Where to store the deferred states.

setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
static similarity(state_a, state_b)[源代码]

The (L2) distance between the counts of the state addresses in the history of the path. :type state_a: :param state_a: The first state to compare :type state_b: :param state_b: The second state to compare

static sequence_matcher_similarity(state_a, state_b)[源代码]

The difflib.SequenceMatcher ratio between the state addresses in the history of the path. :type state_a: :param state_a: The first state to compare :type state_b: :param state_b: The second state to compare

class angr.exploration_techniques.Veritesting(**options)[源代码]

基类:ExplorationTechnique

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

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

__init__(**options)[源代码]
step_state(simgr, state, successor_func=None, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.timeout.Timeout(timeout=None)[源代码]

基类:ExplorationTechnique

Timeout exploration technique that stops an active exploration if the run time exceeds a predefined timeout

__init__(timeout=None)[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.dfs.DFS(deferred_stash='deferred')[源代码]

基类:ExplorationTechnique

Depth-first search.

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

__init__(deferred_stash='deferred')[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.explorer.Explorer(find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False)[源代码]

基类:ExplorationTechnique

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

The "find" and "avoid" parameters may be any of:

  • An address to find

  • A set or list of addresses to find

  • A function that takes a path and returns whether or not it matches.

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

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

__init__(find=None, avoid=None, find_stash='found', avoid_stash='avoid', cfg=None, num_find=1, avoid_priority=False)[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
filter(simgr, state, **kwargs)[源代码]

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.

参数:
complete(simgr)[源代码]

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.

参数:

simgr (angr.SimulationManager)

class angr.exploration_techniques.lengthlimiter.LengthLimiter(max_length, drop=False)[源代码]

基类:ExplorationTechnique

Length limiter on paths.

__init__(max_length, drop=False)[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.manual_mergepoint.ManualMergepoint(address, wait_counter=10, prune=True)[源代码]

基类:ExplorationTechnique

__init__(address, wait_counter=10, prune=True)[源代码]
setup(simgr)[源代码]

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

参数:

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

mark_nofilter(simgr, stash)[源代码]
mark_okfilter(simgr, stash)[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.spiller.PickledStatesBase[源代码]

基类:object

The base class of pickled states

sort()[源代码]

Sort pickled states.

add(prio, sid)[源代码]

Add a newly pickled state.

参数:
  • prio (int) -- Priority of the state.

  • sid (str) -- Persistent ID of the state.

返回:

None

pop_n(n)[源代码]

Pop the top N states.

参数:

n (int) -- Number of states to take.

返回:

A list of states.

class angr.exploration_techniques.spiller.PickledStatesList[源代码]

基类:PickledStatesBase

List-backed pickled state storage.

__init__()[源代码]
sort()[源代码]

Sort pickled states.

add(prio, sid)[源代码]

Add a newly pickled state.

参数:
  • prio (int) -- Priority of the state.

  • sid (str) -- Persistent ID of the state.

返回:

None

pop_n(n)[源代码]

Pop the top N states.

参数:

n (int) -- Number of states to take.

返回:

A list of states.

class angr.exploration_techniques.spiller.PickledStatesDb(db_str='sqlite:///:memory:')[源代码]

基类:PickledStatesBase

Database-backed pickled state storage.

__init__(db_str='sqlite:///:memory:')[源代码]
sort()[源代码]

Sort pickled states.

add(prio, sid, taken=False, stash='spilled')[源代码]

Add a newly pickled state.

参数:
  • prio (int) -- Priority of the state.

  • sid (str) -- Persistent ID of the state.

返回:

None

pop_n(n, stash='spilled')[源代码]

Pop the top N states.

参数:

n (int) -- Number of states to take.

返回:

A list of states.

get_recent_n(n, stash='spilled')[源代码]
count()[源代码]
class angr.exploration_techniques.spiller.Spiller(src_stash='active', min=5, max=10, staging_stash='spill_stage', staging_min=10, staging_max=20, pickle_callback=None, unpickle_callback=None, post_pickle_callback=None, priority_key=None, vault=None, states_collection=None)[源代码]

基类:ExplorationTechnique

Automatically spill states out. It can spill out states to a different stash, spill them out to ANA, or first do the former and then (after enough states) the latter.

__init__(src_stash='active', min=5, max=10, staging_stash='spill_stage', staging_min=10, staging_max=20, pickle_callback=None, unpickle_callback=None, post_pickle_callback=None, priority_key=None, vault=None, states_collection=None)[源代码]

Initializes the spiller.

参数:
  • max -- the number of states that are not spilled

  • src_stash -- the stash from which to spill states (default: active)

  • staging_stash -- the stash to which to spill states (default: "spill_stage")

  • staging_max -- the number of states that can be in the staging stash before things get spilled to ANA (default: None. If staging_stash is set, then this means unlimited, and ANA will not be used).

  • priority_key -- a function that takes a state and returns its numerical priority (MAX_INT is lowest priority). By default, self.state_priority will be used, which prioritizes by object ID.

  • vault -- an angr.Vault object to handle storing and loading of states. If not provided, an angr.vaults.VaultShelf will be created with a temporary file.

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
static state_priority(state)[源代码]
class angr.exploration_techniques.spiller_db.PickledState(**kwargs)[源代码]

基类:Base

id
priority
taken
stash
timestamp
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.exploration_techniques.threading.Threading(threads=8, local_stash='thread_local')[源代码]

基类:ExplorationTechnique

Enable multithreading.

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

__init__(threads=8, local_stash='thread_local')[源代码]
step(simgr, stash='active', error_list=None, target_stash=None, **kwargs)[源代码]

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

参数:
inner_step(state, simgr, **kwargs)[源代码]
class angr.exploration_techniques.veritesting.Veritesting(**options)[源代码]

基类:ExplorationTechnique

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

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

__init__(**options)[源代码]
step_state(simgr, state, successor_func=None, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.tracer.TracingMode[源代码]

基类:object

变量:
  • Strict -- Strict mode, the default mode, where an exception is raised immediately if tracer's path deviates from the provided trace.

  • Permissive -- Permissive mode, where tracer attempts to force the path back to the provided trace when a deviation happens. This does not always work, especially when the cause of deviation is related to input that will later be used in exploit generation. But, it might work magically sometimes.

  • CatchDesync -- CatchDesync mode, catch desync because of sim_procedures. It might be a sign of something interesting.

Strict = 'strict'
Permissive = 'permissive'
CatchDesync = 'catch_desync'
exception angr.exploration_techniques.tracer.TracerDesyncError(msg, deviating_addr=None, deviating_trace_idx=None)[源代码]

基类:AngrTracerError

An error class to report tracing Tracing desyncronization error

__init__(msg, deviating_addr=None, deviating_trace_idx=None)[源代码]
class angr.exploration_techniques.tracer.RepHook(mnemonic)[源代码]

基类:object

Hook rep movs/stos to speed up constraint solving TODO: This should be made an exploration technique later

__init__(mnemonic)[源代码]
run(state)[源代码]
class angr.exploration_techniques.tracer.Tracer(trace=None, resiliency=False, keep_predecessors=1, crash_addr=None, syscall_data=None, copy_states=False, fast_forward_to_entry=True, mode='strict', aslr=True, follow_unsat=False)[源代码]

基类:ExplorationTechnique

An exploration technique that follows an angr path with a concrete input. The tracing result is the state at the last address of the trace, which can be found in the 'traced' stash.

If the given concrete input makes the program crash, you should provide crash_addr, and the crashing state will be found in the 'crashed' stash.

参数:
  • trace -- The basic block trace.

  • resiliency -- Should we continue to step forward even if qemu and angr disagree?

  • keep_predecessors -- Number of states before the final state we should log.

  • crash_addr -- If the trace resulted in a crash, provide the crashing instruction pointer here, and the 'crashed' stash will be populated with the crashing state.

  • syscall_data -- Data related to various syscalls recorded by tracer for replaying

  • copy_states -- Whether COPY_STATES should be enabled for the tracing state. It is off by default because most tracing workloads benefit greatly from not performing copying. You want to enable it if you want to see the missed states. It will be re-added for the last 2% of the trace in order to set the predecessors list correctly. If you turn this on you may want to enable the LAZY_SOLVES option.

  • mode -- Tracing mode.

  • aslr -- Whether there are aslr slides. if not, tracer uses trace address as state address.

  • follow_unsat -- Whether unsatisfiable states should be treated as potential successors or not.

变量:

predecessors -- A list of states in the history before the final state.

__init__(trace=None, resiliency=False, keep_predecessors=1, crash_addr=None, syscall_data=None, copy_states=False, fast_forward_to_entry=True, mode='strict', aslr=True, follow_unsat=False)[源代码]
set_fd_data(fd_data)[源代码]

Set concrete bytes of various fds read by the program

参数:

fd_data (dict[int, bytes])

setup(simgr)[源代码]

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

参数:

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

complete(simgr)[源代码]

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.

参数:

simgr (angr.SimulationManager)

filter(simgr, state, **kwargs)[源代码]

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.

参数:
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
step_state(simgr, state, **kwargs)[源代码]

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.

参数:
classmethod crash_windup(state, crash_addr)[源代码]
class angr.exploration_techniques.driller_core.DrillerCore(trace, fuzz_bitmap=None)[源代码]

基类:ExplorationTechnique

An exploration technique that symbolically follows an input looking for new state transitions.

It has to be used with Tracer exploration technique. Results are put in 'diverted' stash.

__init__(trace, fuzz_bitmap=None)[源代码]

:param trace : The basic block trace. :type fuzz_bitmap: :param fuzz_bitmap: AFL's bitmap of state transitions. Defaults to saying every transition is worth satisfying.

setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.slicecutor.Slicecutor(annotated_cfg, force_taking_exit=False, force_sat=False)[源代码]

基类:ExplorationTechnique

The Slicecutor is an exploration that executes provided code slices.

参数:

force_sat (bool)

__init__(annotated_cfg, force_taking_exit=False, force_sat=False)[源代码]

All parameters except annotated_cfg are optional.

参数:
  • annotated_cfg -- The AnnotatedCFG that provides the code slice.

  • force_taking_exit -- Set to True if you want to create a successor based on our slice in case of unconstrained successors.

  • force_sat (bool) -- If a branch specified by the slice is unsatisfiable, set this option to True if you want to force it to be satisfiable and be taken anyway.

setup(simgr)[源代码]

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

参数:

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

filter(simgr, state, **kwargs)[源代码]

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.

参数:
step_state(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.director.BaseGoal(sort)[源代码]

基类:object

REQUIRE_CFG_STATES = False
__init__(sort)[源代码]
check(cfg, state, peek_blocks)[源代码]
参数:
返回:

True if we can determine that this condition is definitely satisfiable if the path is taken, False otherwise.

返回类型:

bool

check_state(state)[源代码]

Check if the current state satisfies the goal.

参数:

state (angr.SimState) -- The state to check.

返回:

True if it satisfies the goal, False otherwise.

返回类型:

bool

class angr.exploration_techniques.director.ExecuteAddressGoal(addr)[源代码]

基类:BaseGoal

A goal that prioritizes states reaching (or are likely to reach) certain address in some specific steps.

__init__(addr)[源代码]
check(cfg, state, peek_blocks)[源代码]

Check if the specified address will be executed

参数:
  • cfg

  • state

  • peek_blocks (int)

返回:

返回类型:

bool

check_state(state)[源代码]

Check if the current address is the target address.

参数:

state (angr.SimState) -- The state to check.

返回:

True if the current address is the target address, False otherwise.

返回类型:

bool

class angr.exploration_techniques.director.CallFunctionGoal(function, arguments)[源代码]

基类:BaseGoal

A goal that prioritizes states reaching certain function, and optionally with specific arguments. Note that constraints on arguments (and on function address as well) have to be identifiable on an accurate CFG. For example, you may have a CallFunctionGoal saying "call printf with the first argument being 'Hello, world'", and CFGEmulated must be able to figure our the first argument to printf is in fact "Hello, world", not some symbolic strings that will be constrained to "Hello, world" during symbolic execution (or simulation, however you put it).

REQUIRE_CFG_STATES = True
__init__(function, arguments)[源代码]
check(cfg, state, peek_blocks)[源代码]

Check if the specified function will be reached with certain arguments.

参数:
  • cfg

  • state

  • peek_blocks

返回:

check_state(state)[源代码]

Check if the specific function is reached with certain arguments

参数:

state (angr.SimState) -- The state to check

返回:

True if the function is reached with certain arguments, False otherwise.

返回类型:

bool

class angr.exploration_techniques.director.Director(peek_blocks=100, peek_functions=5, goals=None, cfg_keep_states=False, goal_satisfied_callback=None, num_fallback_states=5)[源代码]

基类:ExplorationTechnique

An exploration technique for directed symbolic execution.

A control flow graph (using CFGEmulated) is built and refined during symbolic execution. Each time the execution reaches a block that is outside of the CFG, the CFG recovery will be triggered with that state, with a maximum recovery depth (100 by default). If we see a basic block during state stepping that is not yet in the control flow graph, we go back to control flow graph recovery and "peek" more blocks forward.

When stepping a simulation manager, all states are categorized into three different categories:

  • Might reach the destination within the peek depth. Those states are prioritized.

  • Will not reach the destination within the peek depth. Those states are de-prioritized. However, there is a little chance for those states to be explored as well in order to prevent over-fitting.

__init__(peek_blocks=100, peek_functions=5, goals=None, cfg_keep_states=False, goal_satisfied_callback=None, num_fallback_states=5)[源代码]

Constructor.

step(simgr, stash='active', **kwargs)[源代码]
参数:
  • simgr

  • stash

  • kwargs

返回:

add_goal(goal)[源代码]

Add a goal.

参数:

goal (BaseGoal) -- The goal to add.

返回:

None

class angr.exploration_techniques.oppologist.Oppologist[源代码]

基类:ExplorationTechnique

The Oppologist is an exploration technique that forces uncooperative code through qemu.

__init__()[源代码]
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.loop_seer.LoopSeer(cfg=None, functions=None, loops=None, use_header=False, bound=None, bound_reached=None, discard_stash='spinning', limit_concrete_loops=True)[源代码]

基类:ExplorationTechnique

This exploration technique monitors exploration and maintains all loop-related data (well, currently it is just the loop trip counts, but feel free to add something else).

__init__(cfg=None, functions=None, loops=None, use_header=False, bound=None, bound_reached=None, discard_stash='spinning', limit_concrete_loops=True)[源代码]
参数:
  • cfg -- Normalized CFG is required.

  • functions -- Function(s) containing the loop(s) to be analyzed.

  • loops -- Specific group of Loop(s) to be analyzed, if this is None we run the LoopFinder analysis.

  • use_header -- Whether to use header based trip counter to compare with the bound limit.

  • bound -- Limit the number of iterations a loop may be executed.

  • bound_reached -- If provided, should be a function that takes the LoopSeer and the succ_state. Will be called when loop execution reach the given bound. Default to moving states that exceed the loop limit to a discard stash.

  • discard_stash -- Name of the stash containing states exceeding the loop limit.

  • limit_concrete_loops -- If False, do not limit a loop back-edge if it is the only successor (Defaults to True to maintain the original behavior)

setup(simgr)[源代码]

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

参数:

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

filter(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.local_loop_seer.LocalLoopSeer(bound=None, bound_reached=None, discard_stash='spinning')[源代码]

基类:ExplorationTechnique

LocalLoopSeer monitors exploration and maintains all loop-related data without relying on a control flow graph.

__init__(bound=None, bound_reached=None, discard_stash='spinning')[源代码]
参数:
  • bound -- Limit the number of iterations a loop may be executed.

  • bound_reached -- If provided, should be a function that takes the LoopSeer and the succ_state. Will be called when loop execution reach the given bound. Default to moving states that exceed the loop limit to a discard stash.

  • discard_stash -- Name of the stash containing states exceeding the loop limit.

setup(simgr)[源代码]

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

参数:

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

filter(simgr, state, **kwargs)[源代码]

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.

参数:
successors(simgr, state, **kwargs)[源代码]

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.

参数:
class angr.exploration_techniques.stochastic.StochasticSearch(start_state, restart_prob=0.0001)[源代码]

基类:ExplorationTechnique

Stochastic Search.

Will only keep one path active at a time, any others will be discarded. Before each pass through, weights are randomly assigned to each basic block. These weights form a probability distribution for determining which state remains after splits. When we run out of active paths to step, we start again from the start state.

__init__(start_state, restart_prob=0.0001)[源代码]
参数:
  • start_state -- The initial state from which exploration stems.

  • restart_prob -- The probability of randomly restarting the search (default 0.0001).

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.unique.UniqueSearch(similarity_func=None, deferred_stash='deferred')[源代码]

基类:ExplorationTechnique

Unique Search.

Will only keep one path active at a time, any others will be deferred. The state that is explored depends on how unique it is relative to the other deferred states. A path's uniqueness is determined by its average similarity between the other (deferred) paths. Similarity is calculated based on the supplied similarity_func, which by default is: The (L2) distance between the counts of the state addresses in the history of the path.

__init__(similarity_func=None, deferred_stash='deferred')[源代码]
参数:
  • similarity_func -- How to calculate similarity between two states.

  • deferred_stash -- Where to store the deferred states.

setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
static similarity(state_a, state_b)[源代码]

The (L2) distance between the counts of the state addresses in the history of the path. :type state_a: :param state_a: The first state to compare :type state_b: :param state_b: The second state to compare

static sequence_matcher_similarity(state_a, state_b)[源代码]

The difflib.SequenceMatcher ratio between the state addresses in the history of the path. :type state_a: :param state_a: The first state to compare :type state_b: :param state_b: The second state to compare

class angr.exploration_techniques.tech_builder.TechniqueBuilder(setup=None, step_state=None, step=None, successors=None, filter=None, selector=None, complete=None)[源代码]

基类:ExplorationTechnique

This meta technique could be used to hook a couple of simulation manager methods without actually creating a new exploration technique, for example:

class SomeComplexAnalysis(Analysis):

def do_something():

simgr = self.project.factory.simulation_manager() simgr.use_tech(ProxyTechnique(step_state=self._step_state)) simgr.run()

def _step_state(self, state):

# Do stuff! pass

In the above example, the _step_state method can access all the necessary stuff, hidden in the analysis instance, without passing that instance to a one-shot-styled exploration technique.

__init__(setup=None, step_state=None, step=None, successors=None, filter=None, selector=None, complete=None)[源代码]
angr.exploration_techniques.common.condition_to_lambda(condition, default=False)[源代码]

Translates an integer, set, list or function into a lambda that checks if state's current basic block matches some condition.

参数:
  • condition -- An integer, set, list or lambda to convert to a lambda.

  • default -- The default return value of the lambda (in case condition is None). Default: false.

返回:

A tuple of two items: a lambda that takes a state and returns the set of addresses that it matched from the condition, and a set that contains the normalized set of addresses to stop at, or None if no addresses were provided statically.

class angr.exploration_techniques.memory_watcher.MemoryWatcher(min_memory=512, memory_stash='lowmem')[源代码]

基类:ExplorationTechnique

Memory Watcher

参数:
  • min_memory (int,optional) -- Minimum amount of free memory in MB before stopping execution (default: 95% memory use)

  • memory_stash (str, optional) -- What to call the low memory stash (default: 'lowmem')

At each step, keep an eye on how much memory is left on the system. Stash off states to effectively stop execution if we're below a given threshold.

__init__(min_memory=512, memory_stash='lowmem')[源代码]
setup(simgr)[源代码]

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

参数:

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

step(simgr, stash='active', **kwargs)[源代码]

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

参数:
class angr.exploration_techniques.bucketizer.Bucketizer[源代码]

基类:ExplorationTechnique

Loop bucketization: Pick log(n) paths out of n possible paths, and stash (or drop) everything else.

successors(simgr, state, **kwargs)[源代码]

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.

参数:
angr.exploration_techniques.suggestions.ast_weight(ast, memo=None)[源代码]
class angr.exploration_techniques.suggestions.Suggestions[源代码]

基类:ExplorationTechnique

An exploration technique which analyzes failure cases and logs suggestions for how to mitigate them in future analyses.

__init__()[源代码]
step(simgr, stash='active', **kwargs)[源代码]

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

参数:
static report(state, event)[源代码]

Simulation Engines

class angr.engines.HeavyResilienceMixin(project, **kwargs)[源代码]

基类:VEXResilienceMixin, ClaripyDataMixin

class angr.engines.HeavyVEXMixin(project)[源代码]

基类:SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEXMixin, VEXLifter

Execution engine based on VEX, Valgrind's IR.

Responds to the following parameters to the step stack:

  • irsb: The PyVEX IRSB object to use for execution. If not provided one will be lifted.

  • skip_stmts: The number of statements to skip in processing

  • last_stmt: Do not execute any statements after this statement

  • whitelist: Only execute statements in this set

  • thumb: Whether the block should be force to be lifted in ARM's THUMB mode.

  • extra_stop_points:

    An extra set of points at which to break basic blocks

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

参数:

project (angr.Project)

process_successors(successors, irsb=None, insn_text=None, insn_bytes=None, thumb=False, size=None, num_inst=None, extra_stop_points=None, opt_level=None, strict_block_end=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.HooksMixin(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

A SimEngine mixin which adds a SimSuccessors handler which will look into the project's hooks and run the hook at the current address.

Will respond to the following parameters provided to the step stack:

  • procedure: A SimProcedure instance to force-run instead of consulting the current hooks

  • ret_to: An address to force-return-to at the end of the procedure

参数:

project (angr.Project)

process_successors(successors, procedure=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.ProcedureEngine(project)[源代码]

基类:ProcedureMixin, SuccessorsMixin

A SimEngine that you may use if you only care about processing SimProcedures. Requires the procedure kwarg to be passed to process.

参数:

project (angr.Project)

process_successors(successors, procedure=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.ProcedureMixin[源代码]

基类:object

A mixin for SimEngine which adds the process_procedure method for calling a SimProcedure and adding its results to a SimSuccessors.

process_procedure(state, successors, procedure, ret_to=None, arguments=None, **kwargs)[源代码]
class angr.engines.SimEngine(project)[源代码]

基类:Generic[StateType, ResultType], SimEngineBase[StateType]

A SimEngine is a class which understands how to perform execution on a state. This is a base class.

参数:

project (angr.Project)

abstract process(state, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:

state (TypeVar(StateType)) -- The state to proceed from

返回类型:

TypeVar(ResultType)

返回:

The result. Whatever you want ;)

class angr.engines.SimEngineFailure(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

参数:

project (angr.Project)

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.SimEngineSyscall(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

A SimEngine mixin which adds a successors handling step that checks if a syscall was just requested and if so handles it as a step.

参数:

project (angr.Project)

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.SimEngineUnicorn(project)[源代码]

基类:SuccessorsMixin

Concrete execution in the Unicorn Engine, a fork of qemu.

Responds to the following parameters in the step stack:

  • step: How many basic blocks we want to execute

  • extra_stop_points: A collection of addresses at which execution should halt

参数:

project (angr.Project)

__init__(project)[源代码]
参数:

project (Project)

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.SimInspectMixin(project, **kwargs)[源代码]

基类:VEXMixin

handle_vex_block(irsb)[源代码]
class angr.engines.SimSuccessors(addr, initial_state)[源代码]

基类:object

This class serves as a categorization of all the kinds of result states that can come from a SimEngine run.

变量:
  • addr (int) -- The address at which execution is taking place, as a python int

  • initial_state -- The initial state for which execution produced these successors

  • engine -- The engine that produced these successors

  • sort -- A string identifying the type of engine that produced these successors

  • processed (bool) -- Whether or not the processing succeeded

  • description (str) -- A textual description of the execution step

参数:
  • addr (int | SootAddressDescriptor | None)

  • initial_state (HeavyState | None)

The successor states produced by this run are categorized into several lists:

变量:
  • artifacts (dict) -- Any analysis byproducts (for example, an IRSB) that were produced during execution

  • successors -- The "normal" successors. IP may be symbolic, but must have reasonable number of solutions

  • unsat_successors -- Any successor which is unsatisfiable after its guard condition is added.

  • all_successors -- successors + unsat_successors

  • flat_successors -- The normal successors, but any symbolic IPs have been concretized. There is one state in this list for each possible value an IP may be concretized to for each successor state.

  • unconstrained_successors -- Any state for which during the flattening process we find too many solutions.

参数:
  • addr (int | SootAddressDescriptor | None)

  • initial_state (HeavyState | None)

A more detailed description of the successor lists may be found here: https://docs.angr.io/core-concepts/simulation#simsuccessors

__init__(addr, initial_state)[源代码]
参数:
classmethod failure()[源代码]
property is_empty
add_successor(state, target, guard, jumpkind, add_guard=True, exit_stmt_idx=None, exit_ins_addr=None, source=None)[源代码]

Add a successor state of the SimRun. This procedure stores method parameters into state.scratch, does some housekeeping, and calls out to helper functions to prepare the state and categorize it into the appropriate successor lists.

参数:
  • state (SimState) -- The successor state.

  • target -- The target (of the jump/call/ret).

  • guard -- The guard expression.

  • jumpkind (str) -- The jumpkind (call, ret, jump, or whatnot).

  • add_guard (bool) -- Whether to add the guard constraint (default: True).

  • exit_stmt_idx (int) -- The ID of the exit statement, an integer by default. 'default' stands for the default exit, and None means it's not from a statement (for example, from a SimProcedure).

  • exit_ins_addr (int) -- The instruction pointer of this exit, which is an integer by default.

  • source (int) -- The source of the jump (i.e., the address of the basic block).

class angr.engines.SootMixin(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

Execution engine based on Soot.

参数:

project (angr.Project)

lift_soot(addr=None, the_binary=None, **kwargs)[源代码]
process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

get_unconstrained_simprocedure()[源代码]
classmethod setup_callsite(state, args, ret_addr, ret_var=None)[源代码]
static setup_arguments(state, args)[源代码]
static prepare_return_state(state, ret_value=None)[源代码]
static terminate_execution(statement, state, successors)[源代码]
static prepare_native_return_state(native_state)[源代码]

Hook target for native function call returns.

Recovers and stores the return value from native memory and toggles the state, s.t. execution continues in the Soot engine.

class angr.engines.SuccessorsMixin(project)[源代码]

基类:SimEngine[SimState[int | SootAddressDescriptor, BV | SootAddressDescriptor], SimSuccessors]

A mixin for SimEngine which implements process to perform common operations related to symbolic execution and dispatches to a process_successors method to fill a SimSuccessors object with the results.

参数:

project (angr.Project)

__init__(project)[源代码]
参数:

project (Project)

process(state, **kwargs)[源代码]

Perform execution with a state.

You should only override this method in a subclass in order to provide the correct method signature and docstring. You should override the _process method to do your actual execution.

参数:
  • state (SimState[int | SootAddressDescriptor, BV | SootAddressDescriptor]) -- The state with which to execute. This state will be copied before modification.

  • inline -- This is an inline execution. Do not bother copying the state.

  • force_addr -- Force execution to pretend that we're working at this concrete address

返回类型:

SimSuccessors

返回:

A SimSuccessors object categorizing the execution's successor states

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.SuperFastpathMixin(*args, **kwargs)[源代码]

基类:VEXSlicingMixin

This mixin implements the superfastpath execution mode, which skips all but the last four instructions.

handle_vex_block(irsb)[源代码]
class angr.engines.TrackActionsMixin(*args, **kwargs)[源代码]

基类:HeavyVEXMixin

__init__(*args, **kwargs)[源代码]
handle_vex_block(irsb)[源代码]
class angr.engines.UberEngine(project)[源代码]

基类:SimEngineFailure, SimEngineSyscall, HooksMixin, SimEngineUnicorn, SuperFastpathMixin, TrackActionsMixin, SimInspectMixin, HeavyResilienceMixin, SootMixin, HeavyVEXMixin

The default execution engine for angr. This engine includes mixins for most common functionality in angr, including VEX IR, unicorn, syscall handling, and simprocedure handling.

For some performance-sensitive applications, you may want to create a custom engine with only the necessary mixins.

参数:

project (angr.Project)

class angr.engines.UberEnginePcode(*args, **kwargs)[源代码]

基类:SimEngineFailure, SimEngineSyscall, HooksMixin, HeavyPcodeMixin

class angr.engines.engine.SimEngineBase(project)[源代码]

基类:Generic[StateType]

Even more basey of a base class for SimEngine. Used as a base by mixins which want access to the project but for which having method process (contained in SimEngine) doesn't make sense

参数:

project (angr.Project)

state: TypeVar(StateType)
__init__(project)[源代码]
参数:

project (Project)

class angr.engines.engine.SimEngine(project)[源代码]

基类:Generic[StateType, ResultType], SimEngineBase[StateType]

A SimEngine is a class which understands how to perform execution on a state. This is a base class.

参数:

project (angr.Project)

abstract process(state, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:

state (TypeVar(StateType)) -- The state to proceed from

返回类型:

TypeVar(ResultType)

返回:

The result. Whatever you want ;)

class angr.engines.engine.SuccessorsMixin(project)[源代码]

基类:SimEngine[SimState[int | SootAddressDescriptor, BV | SootAddressDescriptor], SimSuccessors]

A mixin for SimEngine which implements process to perform common operations related to symbolic execution and dispatches to a process_successors method to fill a SimSuccessors object with the results.

参数:

project (angr.Project)

__init__(project)[源代码]
参数:

project (Project)

process(state, **kwargs)[源代码]

Perform execution with a state.

You should only override this method in a subclass in order to provide the correct method signature and docstring. You should override the _process method to do your actual execution.

参数:
  • state (SimState[int | SootAddressDescriptor, BV | SootAddressDescriptor]) -- The state with which to execute. This state will be copied before modification.

  • inline -- This is an inline execution. Do not bother copying the state.

  • force_addr -- Force execution to pretend that we're working at this concrete address

返回类型:

SimSuccessors

返回:

A SimSuccessors object categorizing the execution's successor states

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.successors.SimSuccessors(addr, initial_state)[源代码]

基类:object

This class serves as a categorization of all the kinds of result states that can come from a SimEngine run.

变量:
  • addr (int) -- The address at which execution is taking place, as a python int

  • initial_state -- The initial state for which execution produced these successors

  • engine -- The engine that produced these successors

  • sort -- A string identifying the type of engine that produced these successors

  • processed (bool) -- Whether or not the processing succeeded

  • description (str) -- A textual description of the execution step

参数:
  • addr (int | SootAddressDescriptor | None)

  • initial_state (HeavyState | None)

The successor states produced by this run are categorized into several lists:

变量:
  • artifacts (dict) -- Any analysis byproducts (for example, an IRSB) that were produced during execution

  • successors -- The "normal" successors. IP may be symbolic, but must have reasonable number of solutions

  • unsat_successors -- Any successor which is unsatisfiable after its guard condition is added.

  • all_successors -- successors + unsat_successors

  • flat_successors -- The normal successors, but any symbolic IPs have been concretized. There is one state in this list for each possible value an IP may be concretized to for each successor state.

  • unconstrained_successors -- Any state for which during the flattening process we find too many solutions.

参数:
  • addr (int | SootAddressDescriptor | None)

  • initial_state (HeavyState | None)

A more detailed description of the successor lists may be found here: https://docs.angr.io/core-concepts/simulation#simsuccessors

__init__(addr, initial_state)[源代码]
参数:
classmethod failure()[源代码]
property is_empty
add_successor(state, target, guard, jumpkind, add_guard=True, exit_stmt_idx=None, exit_ins_addr=None, source=None)[源代码]

Add a successor state of the SimRun. This procedure stores method parameters into state.scratch, does some housekeeping, and calls out to helper functions to prepare the state and categorize it into the appropriate successor lists.

参数:
  • state (SimState) -- The successor state.

  • target -- The target (of the jump/call/ret).

  • guard -- The guard expression.

  • jumpkind (str) -- The jumpkind (call, ret, jump, or whatnot).

  • add_guard (bool) -- Whether to add the guard constraint (default: True).

  • exit_stmt_idx (int) -- The ID of the exit statement, an integer by default. 'default' stands for the default exit, and None means it's not from a statement (for example, from a SimProcedure).

  • exit_ins_addr (int) -- The instruction pointer of this exit, which is an integer by default.

  • source (int) -- The source of the jump (i.e., the address of the basic block).

class angr.engines.procedure.ProcedureMixin[源代码]

基类:object

A mixin for SimEngine which adds the process_procedure method for calling a SimProcedure and adding its results to a SimSuccessors.

process_procedure(state, successors, procedure, ret_to=None, arguments=None, **kwargs)[源代码]
class angr.engines.procedure.ProcedureEngine(project)[源代码]

基类:ProcedureMixin, SuccessorsMixin

A SimEngine that you may use if you only care about processing SimProcedures. Requires the procedure kwarg to be passed to process.

参数:

project (angr.Project)

process_successors(successors, procedure=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.hook.HooksMixin(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

A SimEngine mixin which adds a SimSuccessors handler which will look into the project's hooks and run the hook at the current address.

Will respond to the following parameters provided to the step stack:

  • procedure: A SimProcedure instance to force-run instead of consulting the current hooks

  • ret_to: An address to force-return-to at the end of the procedure

参数:

project (angr.Project)

process_successors(successors, procedure=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.syscall.SimEngineSyscall(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

A SimEngine mixin which adds a successors handling step that checks if a syscall was just requested and if so handles it as a step.

参数:

project (angr.Project)

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.failure.SimEngineFailure(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

参数:

project (angr.Project)

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.vex.ClaripyDataMixin(project, **kwargs)[源代码]

基类:VEXMixin

This mixin provides methods that makes the vex engine process guest code using claripy ASTs as the data domain.

class angr.engines.vex.HeavyResilienceMixin(project, **kwargs)[源代码]

基类:VEXResilienceMixin, ClaripyDataMixin

class angr.engines.vex.HeavyVEXMixin(project)[源代码]

基类:SuccessorsMixin, ClaripyDataMixin, SimStateStorageMixin, VEXMixin, VEXLifter

Execution engine based on VEX, Valgrind's IR.

Responds to the following parameters to the step stack:

  • irsb: The PyVEX IRSB object to use for execution. If not provided one will be lifted.

  • skip_stmts: The number of statements to skip in processing

  • last_stmt: Do not execute any statements after this statement

  • whitelist: Only execute statements in this set

  • thumb: Whether the block should be force to be lifted in ARM's THUMB mode.

  • extra_stop_points:

    An extra set of points at which to break basic blocks

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

参数:

project (angr.Project)

process_successors(successors, irsb=None, insn_text=None, insn_bytes=None, thumb=False, size=None, num_inst=None, extra_stop_points=None, opt_level=None, strict_block_end=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.vex.SimInspectMixin(project, **kwargs)[源代码]

基类:VEXMixin

handle_vex_block(irsb)[源代码]
class angr.engines.vex.SuperFastpathMixin(*args, **kwargs)[源代码]

基类:VEXSlicingMixin

This mixin implements the superfastpath execution mode, which skips all but the last four instructions.

handle_vex_block(irsb)[源代码]
class angr.engines.vex.TrackActionsMixin(*args, **kwargs)[源代码]

基类:HeavyVEXMixin

__init__(*args, **kwargs)[源代码]
handle_vex_block(irsb)[源代码]
class angr.engines.vex.VEXLifter(project, use_cache=None, cache_size=50000, default_opt_level=1, selfmodifying_code=None, single_step=False, default_strict_block_end=False, **kwargs)[源代码]

基类:SimEngineBase

Implements the VEX lifter engine mixin.

__init__(project, use_cache=None, cache_size=50000, default_opt_level=1, selfmodifying_code=None, single_step=False, default_strict_block_end=False, **kwargs)[源代码]
clear_cache()[源代码]
lift_vex(addr=None, state=None, clemory=None, insn_bytes=None, offset=None, arch=None, size=None, num_inst=None, traceflags=0, thumb=False, extra_stop_points=None, opt_level=None, strict_block_end=None, skip_stmts=False, collect_data_refs=False, cross_insn_opt=None, load_from_ro_regions=False, const_prop=False)[源代码]

Lift an IRSB.

There are many possible valid sets of parameters. You at the very least must pass some source of data, some source of an architecture, and some source of an address.

Sources of data in order of priority: insn_bytes, clemory, state

Sources of an address, in order of priority: addr, state

Sources of an architecture, in order of priority: arch, clemory, state

参数:
  • state -- A state to use as a data source.

  • clemory -- A cle.memory.Clemory object to use as a data source.

  • addr -- The address at which to start the block.

  • thumb -- Whether the block should be lifted in ARM's THUMB mode.

  • opt_level -- The VEX optimization level to use. The final IR optimization level is determined by (ordered by priority): - Argument opt_level - opt_level is set to 1 if OPTIMIZE_IR exists in state options - self._default_opt_level

  • insn_bytes -- A string of bytes to use as a data source.

  • offset -- If using insn_bytes, the number of bytes in it to skip over.

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

  • strict_block_end -- Whether to force blocks to end at all conditional branches (default: false)

class angr.engines.vex.VEXMixin(project, **kwargs)[源代码]

基类:SimEngineBase

__init__(project, **kwargs)[源代码]
handle_vex_block(irsb)[源代码]
参数:

irsb (IRSB)

class angr.engines.vex.VEXResilienceMixin(project, **kwargs)[源代码]

基类:VEXMixin

class angr.engines.vex.VEXSlicingMixin(*args, **kwargs)[源代码]

基类:VEXMixin

__init__(*args, **kwargs)[源代码]
process(state, block=None, skip_stmts=0, last_stmt=None, whitelist=None, **kwargs)[源代码]
handle_vex_block(irsb)[源代码]
class angr.engines.soot.SootMixin(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

Execution engine based on Soot.

参数:

project (angr.Project)

lift_soot(addr=None, the_binary=None, **kwargs)[源代码]
process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

get_unconstrained_simprocedure()[源代码]
classmethod setup_callsite(state, args, ret_addr, ret_var=None)[源代码]
static setup_arguments(state, args)[源代码]
static prepare_return_state(state, ret_value=None)[源代码]
static terminate_execution(statement, state, successors)[源代码]
static prepare_native_return_state(native_state)[源代码]

Hook target for native function call returns.

Recovers and stores the return value from native memory and toggles the state, s.t. execution continues in the Soot engine.

class angr.engines.soot.engine.SootMixin(project)[源代码]

基类:SuccessorsMixin, ProcedureMixin

Execution engine based on Soot.

参数:

project (angr.Project)

lift_soot(addr=None, the_binary=None, **kwargs)[源代码]
process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

get_unconstrained_simprocedure()[源代码]
classmethod setup_callsite(state, args, ret_addr, ret_var=None)[源代码]
static setup_arguments(state, args)[源代码]
static prepare_return_state(state, ret_value=None)[源代码]
static terminate_execution(statement, state, successors)[源代码]
static prepare_native_return_state(native_state)[源代码]

Hook target for native function call returns.

Recovers and stores the return value from native memory and toggles the state, s.t. execution continues in the Soot engine.

class angr.engines.unicorn.SimEngineUnicorn(project)[源代码]

基类:SuccessorsMixin

Concrete execution in the Unicorn Engine, a fork of qemu.

Responds to the following parameters in the step stack:

  • step: How many basic blocks we want to execute

  • extra_stop_points: A collection of addresses at which execution should halt

参数:

project (angr.Project)

__init__(project)[源代码]
参数:

project (Project)

process_successors(successors, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

class angr.engines.pcode.HeavyPcodeMixin(*args, **kwargs)[源代码]

基类:SuccessorsMixin, PcodeLifterEngineMixin, PcodeEmulatorMixin

Execution engine based on P-code, Ghidra's IR.

Responds to the following parameters to the step stack:

  • irsb: The P-Code IRSB object to use for execution. If not provided one will be lifted.

  • skip_stmts: The number of statements to skip in processing

  • last_stmt: Do not execute any statements after this statement

  • thumb: Whether the block should be force to be lifted in ARM's THUMB mode. (FIXME)

  • extra_stop_points:

    An extra set of points at which to break basic blocks

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

__init__(*args, **kwargs)[源代码]
process_successors(successors, irsb=None, insn_text=None, insn_bytes=None, thumb=False, size=None, num_inst=None, extra_stop_points=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors (SimSuccessors) -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

  • irsb (IRSB | None)

  • insn_text (str | None)

  • insn_bytes (bytes | None)

  • thumb (bool)

  • size (int | None)

  • num_inst (int | None)

  • extra_stop_points (Iterable[int] | None)

返回类型:

None

angr.engines.pcode.register_pcode_arch_default_cc(arch)[源代码]
参数:

arch (ArchPcode)

class angr.engines.pcode.engine.HeavyPcodeMixin(*args, **kwargs)[源代码]

基类:SuccessorsMixin, PcodeLifterEngineMixin, PcodeEmulatorMixin

Execution engine based on P-code, Ghidra's IR.

Responds to the following parameters to the step stack:

  • irsb: The P-Code IRSB object to use for execution. If not provided one will be lifted.

  • skip_stmts: The number of statements to skip in processing

  • last_stmt: Do not execute any statements after this statement

  • thumb: Whether the block should be force to be lifted in ARM's THUMB mode. (FIXME)

  • extra_stop_points:

    An extra set of points at which to break basic blocks

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

__init__(*args, **kwargs)[源代码]
process_successors(successors, irsb=None, insn_text=None, insn_bytes=None, thumb=False, size=None, num_inst=None, extra_stop_points=None, **kwargs)[源代码]

Implement this function to fill out the SimSuccessors object with the results of stepping state.

In order to implement a model where multiple mixins can potentially handle a request, a mixin may implement this method and then perform a super() call if it wants to pass on handling to the next mixin.

Keep in mind python's method resolution order when composing multiple classes implementing this method. In short: left-to-right, depth-first, but deferring any base classes which are shared by multiple subclasses (the merge point of a diamond pattern in the inheritance graph) until the last point where they would be encountered in this depth-first search. For example, if you have classes A, B(A), C(B), D(A), E(C, D), then the method resolution order will be E, C, B, D, A.

参数:
  • state -- The state to manipulate

  • successors (SimSuccessors) -- The successors object to fill out

  • kwargs -- Any extra arguments. Do not fail if you are passed unexpected arguments.

  • irsb (IRSB | None)

  • insn_text (str | None)

  • insn_bytes (bytes | None)

  • thumb (bool)

  • size (int | None)

  • num_inst (int | None)

  • extra_stop_points (Iterable[int] | None)

返回类型:

None

class angr.engines.pcode.lifter.ExitStatement(dst, jumpkind)[源代码]

基类:object

This class exists to ease compatibility with CFGFast's processing of exit_statements. See _scan_irsb method.

参数:
  • dst (int | None)

  • jumpkind (str)

__init__(dst, jumpkind)[源代码]
参数:
  • dst (int | None)

  • jumpkind (str)

dst: int | None
jumpkind: str
class angr.engines.pcode.lifter.PcodeDisassemblerBlock(addr, insns, thumb, arch)[源代码]

基类:DisassemblerBlock

Helper class to represent a block of disassembled target architecture instructions

addr
arch
insns
thumb
class angr.engines.pcode.lifter.PcodeDisassemblerInsn(pcode_insn)[源代码]

基类:DisassemblerInsn

Helper class to represent a disassembled target architecture instruction

__init__(pcode_insn)[源代码]
property size: int
property address: int
property mnemonic: str
property op_str: str
class angr.engines.pcode.lifter.IRSB(data, mem_addr, arch, max_inst=None, max_bytes=None, bytes_offset=0, traceflags=0, opt_level=1, num_inst=None, num_bytes=None, strict_block_end=False, skip_stmts=False, collect_data_refs=False)[源代码]

基类:object

IRSB stands for Intermediate Representation Super-Block. An IRSB in is a single-entry, multiple-exit code block.

变量:
  • arch (archinfo.Arch) -- The architecture this block is lifted under

  • statements (list of IRStmt) -- The statements in this block

  • next (IRExpr) -- The expression for the default exit target of this block

  • offsIP (int) -- The offset of the instruction pointer in the VEX guest state

  • stmts_used (int) -- The number of statements in this IRSB

  • jumpkind (str) -- The type of this block's default jump (call, boring, syscall, etc) as a VEX enum string

  • direct_next (bool) -- Whether this block ends with a direct (not indirect) jump or branch

  • size (int) -- The size of this block in bytes

  • addr (int) -- The address of this basic block, i.e. the address in the first IMark

参数:
MAX_EXITS = 400
MAX_DATA_REFS = 2000
__init__(data, mem_addr, arch, max_inst=None, max_bytes=None, bytes_offset=0, traceflags=0, opt_level=1, num_inst=None, num_bytes=None, strict_block_end=False, skip_stmts=False, collect_data_refs=False)[源代码]
参数:
  • data (str | bytes | None) -- The bytes to lift. Can be either a string of bytes or a cffi buffer object. You may also pass None to initialize an empty IRSB.

  • mem_addr (int) -- The address to lift the data at.

  • arch (Arch) -- The architecture to lift the data as.

  • max_inst (Optional[int]) -- The maximum number of instructions to lift. (See note below)

  • max_bytes (Optional[int]) -- The maximum number of bytes to use.

  • num_inst (Optional[int]) -- Replaces max_inst if max_inst is None. If set to None as well, no instruction limit is used.

  • num_bytes (Optional[int]) -- Replaces max_bytes if max_bytes is None. If set to None as well, no byte limit is used.

  • bytes_offset (int) -- The offset into data to start lifting at. Note that for ARM THUMB mode, both mem_addr and bytes_offset must be odd (typically bytes_offset is set to 1).

  • traceflags (int) -- Unused by P-Code lifter

  • opt_level (int) -- Unused by P-Code lifter

  • strict_block_end (bool) -- Unused by P-Code lifter

  • skip_stmts (bool)

  • collect_data_refs (bool)

返回类型:

None

备注

Explicitly specifying the number of instructions to lift (max_inst) may not always work exactly as expected. For example, on MIPS, it is meaningless to lift a branch or jump instruction without its delay slot. VEX attempts to Do The Right Thing by possibly decoding fewer instructions than requested. Specifically, this means that lifting a branch or jump on MIPS as a single instruction (max_inst=1) will result in an empty IRSB, and subsequent attempts to run this block will raise SimIRSBError('Empty IRSB passed to SimIRSB.').

备注

If no instruction and byte limit is used, the lifter will continue lifting the block until the block ends properly or until it runs out of data to lift.

addr: int
arch: archinfo.Arch
behaviors: BehaviorFactory | None
data_refs: Sequence
const_vals: Sequence
default_exit_target: Optional
jumpkind: str | None
next: int | None
static empty_block(arch, addr, statements=None, nxt=None, tyenv=None, jumpkind=None, direct_next=None, size=None)[源代码]
返回类型:

IRSB

参数:
property has_statements: bool
property exit_statements: Sequence[tuple[int, int, ExitStatement]]
copy()[源代码]

Copy by creating an empty IRSB and then filling in the leftover attributes. Copy is made as deep as possible

返回类型:

IRSB

extend(extendwith)[源代码]

Appends an irsb to the current irsb. The irsb that is appended is invalidated. The appended irsb's jumpkind and default exit are used. :type extendwith: IRSB :param extendwith: The IRSB to append to this IRSB

返回类型:

IRSB

参数:

extendwith (IRSB)

invalidate_direct_next()[源代码]
返回类型:

None

pp()[源代码]

Pretty-print the IRSB to stdout.

返回类型:

None

property tyenv
property stmts_used: int
property offsIP: int
property direct_next: bool
property expressions

Return an iterator of all expressions contained in the IRSB.

property instructions: int

The number of instructions in this block

property instruction_addresses: Sequence[int]

Addresses of instructions in this block.

property size: int

The size of this block, in bytes

property operations

A list of all operations done by the IRSB, as libVEX enum names

property all_constants

Returns all constants in the block (including incrementing of the program counter) as pyvex.const.IRConst.

property constants

The constants (excluding updates of the program counter) in the IRSB as pyvex.const.IRConst.

property constant_jump_targets

A set of the static jump targets of the basic block.

property constant_jump_targets_and_jumpkinds

A dict of the static jump targets of the basic block to their jumpkind.

property statements: Iterable
property disassembly: PcodeDisassemblerBlock
class angr.engines.pcode.lifter.Lifter(arch, addr)[源代码]

基类:object

A lifter is a class of methods for processing a block.

变量:
  • data -- The bytes to lift as either a python string of bytes or a cffi buffer object.

  • bytes_offset -- The offset into data to start lifting at.

  • max_bytes -- The maximum number of bytes to lift. If set to None, no byte limit is used.

  • max_inst -- The maximum number of instructions to lift. If set to None, no instruction limit is used.

  • opt_level -- Unused by P-Code lifter

  • traceflags -- Unused by P-Code lifter

  • allow_arch_optimizations -- Unused by P-Code lifter

  • strict_block_end -- Unused by P-Code lifter

  • skip_stmts -- Unused by P-Code lifter

参数:
REQUIRE_DATA_C = False
REQUIRE_DATA_PY = False
__init__(arch, addr)[源代码]
参数:
arch: Arch
addr: int
data: str | bytes | None
bytes_offset: int | None
opt_level: int
traceflags: int | None
allow_arch_optimizations: bool | None
strict_block_end: bool | None
collect_data_refs: bool
max_inst: int | None
max_bytes: int | None
skip_stmts: bool
irsb: IRSB
lift()[源代码]

Lifts the data using the information passed into _lift. Should be overridden in child classes.

Should set the lifted IRSB to self.irsb. If a lifter raises a LiftingException on the data, this signals that the lifter cannot lift this data and arch and the lifter is skipped. If a lifter can lift any amount of data, it should lift it and return the lifted block with a jumpkind of Ijk_NoDecode, signalling to pyvex that other lifters should be used on the undecodable data.

返回类型:

None

angr.engines.pcode.lifter.lift(data, addr, arch, max_bytes=None, max_inst=None, bytes_offset=0, opt_level=1, traceflags=0, strict_block_end=True, inner=False, skip_stmts=False, collect_data_refs=False)[源代码]

Lift machine code in data to a P-code IRSB.

If a lifter raises a LiftingException on the data, it is skipped. If it succeeds and returns a block with a jumpkind of Ijk_NoDecode, all of the lifters are tried on the rest of the data and if they work, their output is appended to the first block.

参数:
  • arch (Arch) -- The arch to lift the data as.

  • addr (int) -- The starting address of the block. Effects the IMarks.

  • data (str | bytes | None) -- The bytes to lift as either a python string of bytes or a cffi buffer object.

  • max_bytes (Optional[int]) -- The maximum number of bytes to lift. If set to None, no byte limit is used.

  • max_inst (Optional[int]) -- The maximum number of instructions to lift. If set to None, no instruction limit is used.

  • bytes_offset (int) -- The offset into data to start lifting at.

  • opt_level (int) -- Unused by P-Code lifter

  • traceflags (int) -- Unused by P-Code lifter

  • strict_block_end (bool)

  • inner (bool)

  • skip_stmts (bool)

  • collect_data_refs (bool)

返回类型:

IRSB

备注

Explicitly specifying the number of instructions to lift (max_inst) may not always work exactly as expected. For example, on MIPS, it is meaningless to lift a branch or jump instruction without its delay slot. VEX attempts to Do The Right Thing by possibly decoding fewer instructions than requested. Specifically, this means that lifting a branch or jump on MIPS as a single instruction (max_inst=1) will result in an empty IRSB, and subsequent attempts to run this block will raise SimIRSBError('Empty IRSB passed to SimIRSB.').

备注

If no instruction and byte limit is used, the lifter will continue lifting the block until the block ends properly or until it runs out of data to lift.

class angr.engines.pcode.lifter.PcodeBasicBlockLifter(arch)[源代码]

基类:object

Lifts basic blocks to P-code

参数:

arch (archinfo.Arch)

__init__(arch)[源代码]
参数:

arch (Arch)

context: Context
behaviors: BehaviorFactory
lift(irsb, baseaddr, data, bytes_offset=0, max_bytes=None, max_inst=None, branch_delay_slot=False, is_sparc32=False)[源代码]
返回类型:

None

参数:
class angr.engines.pcode.lifter.PcodeLifter(arch, addr)[源代码]

基类:Lifter

Handles calling into pypcode to lift a block

参数:
addr: int
allow_arch_optimizations: bool | None
arch: Arch
bytes_offset: int | None
collect_data_refs: bool
data: str | bytes | None
irsb: IRSB
max_bytes: int | None
max_inst: int | None
opt_level: int
skip_stmts: bool
strict_block_end: bool | None
traceflags: int | None
lift()[源代码]

Lifts the data using the information passed into _lift. Should be overridden in child classes.

Should set the lifted IRSB to self.irsb. If a lifter raises a LiftingException on the data, this signals that the lifter cannot lift this data and arch and the lifter is skipped. If a lifter can lift any amount of data, it should lift it and return the lifted block with a jumpkind of Ijk_NoDecode, signalling to pyvex that other lifters should be used on the undecodable data.

返回类型:

None

class angr.engines.pcode.lifter.PcodeLifterEngineMixin(project=None, use_cache=None, cache_size=50000, default_opt_level=1, selfmodifying_code=None, single_step=False, default_strict_block_end=False, **kwargs)[源代码]

基类:SimEngineBase

Lifter mixin to lift from machine code to P-Code.

参数:
  • use_cache (bool | None)

  • cache_size (int)

  • default_opt_level (int)

  • selfmodifying_code (bool | None)

  • single_step (bool)

  • default_strict_block_end (bool)

__init__(project=None, use_cache=None, cache_size=50000, default_opt_level=1, selfmodifying_code=None, single_step=False, default_strict_block_end=False, **kwargs)[源代码]
参数:
  • use_cache (bool | None)

  • cache_size (int)

  • default_opt_level (int)

  • selfmodifying_code (bool | None)

  • single_step (bool)

  • default_strict_block_end (bool)

clear_cache()[源代码]
返回类型:

None

lift_vex(addr=None, state=None, clemory=None, insn_bytes=None, arch=None, size=None, num_inst=None, traceflags=0, thumb=False, extra_stop_points=None, opt_level=None, strict_block_end=None, skip_stmts=False, collect_data_refs=False, load_from_ro_regions=False, cross_insn_opt=None, const_prop=None)[源代码]

Temporary compatibility interface for integration with block code.

参数:
  • addr (int | None)

  • state (SimState | None)

  • clemory (Clemory | None)

  • insn_bytes (bytes | None)

  • arch (Arch | None)

  • size (int | None)

  • num_inst (int | None)

  • traceflags (int)

  • thumb (bool)

  • extra_stop_points (Iterable[int] | None)

  • opt_level (int | None)

  • strict_block_end (bool | None)

  • skip_stmts (bool)

  • collect_data_refs (bool)

  • load_from_ro_regions (bool)

  • cross_insn_opt (bool | None)

  • const_prop (bool | None)

lift_pcode(addr=None, state=None, clemory=None, insn_bytes=None, arch=None, size=None, num_inst=None, traceflags=0, thumb=False, extra_stop_points=None, opt_level=None, strict_block_end=None, skip_stmts=False, collect_data_refs=False, load_from_ro_regions=False, cross_insn_opt=None, const_prop=None)[源代码]

Lift an IRSB.

There are many possible valid sets of parameters. You at the very least must pass some source of data, some source of an architecture, and some source of an address.

Sources of data in order of priority: insn_bytes, clemory, state

Sources of an address, in order of priority: addr, state

Sources of an architecture, in order of priority: arch, clemory, state

参数:
  • state (Optional[SimState]) -- A state to use as a data source.

  • clemory (Optional[Clemory]) -- A cle.memory.Clemory object to use as a data source.

  • addr (Optional[int]) -- The address at which to start the block.

  • thumb (bool) -- Whether the block should be lifted in ARM's THUMB mode.

  • opt_level (Optional[int]) -- Unused for P-Code lifter

  • insn_bytes (Optional[bytes]) -- A string of bytes to use as a data source.

  • size (Optional[int]) -- The maximum size of the block, in bytes.

  • num_inst (Optional[int]) -- The maximum number of instructions.

  • traceflags (int) -- Unused by P-Code lifter

  • strict_block_end (Optional[bool]) -- Unused by P-Code lifter

  • load_from_ro_regions (bool) -- Unused by P-Code lifter

  • arch (Arch | None)

  • extra_stop_points (Iterable[int] | None)

  • skip_stmts (bool)

  • collect_data_refs (bool)

  • cross_insn_opt (bool | None)

  • const_prop (bool | None)

class angr.engines.pcode.emulate.PcodeEmulatorMixin(*args, **kwargs)[源代码]

基类:SimEngineBase

Mixin for p-code execution.

__init__(*args, **kwargs)[源代码]
handle_pcode_block(irsb)[源代码]

Execute a single P-Code IRSB.

参数:

irsb (IRSB) -- Block to be executed.

返回类型:

None

angr.engines.pcode.behavior.make_bv_sizes_equal(bv1, bv2)[源代码]

Makes two BVs equal in length through sign extension.

返回类型:

tuple[BV, BV]

参数:
class angr.engines.pcode.behavior.OpBehavior(opcode, is_unary, is_special=False)[源代码]

基类:object

Base class for all operation behaviors.

参数:
__init__(opcode, is_unary, is_special=False)[源代码]
参数:
返回类型:

None

opcode: int
is_unary: bool
is_special: bool
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
static generic_compare(args, comparison)[源代码]
返回类型:

BV

参数:
classmethod booleanize(in1)[源代码]

Reduce input BV to a single bit of truth: out <- 1 if (in1 != 0) else 0.

返回类型:

BV

参数:

in1 (BV)

class angr.engines.pcode.behavior.OpBehaviorCopy[源代码]

基类:OpBehavior

Behavior for the COPY operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorEqual[源代码]

基类:OpBehavior

Behavior for the INT_EQUAL operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorNotEqual[源代码]

基类:OpBehavior

Behavior for the INT_NOTEQUAL operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSless[源代码]

基类:OpBehavior

Behavior for the INT_SLESS operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSlessEqual[源代码]

基类:OpBehavior

Behavior for the INT_SLESSEQUAL operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntLess[源代码]

基类:OpBehavior

Behavior for the INT_LESS operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntLessEqual[源代码]

基类:OpBehavior

Behavior for the INT_LESSEQUAL operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntZext[源代码]

基类:OpBehavior

Behavior for the INT_ZEXT operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSext[源代码]

基类:OpBehavior

Behavior for the INT_SEXT operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntAdd[源代码]

基类:OpBehavior

Behavior for the INT_ADD operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSub[源代码]

基类:OpBehavior

Behavior for the INT_SUB operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntCarry[源代码]

基类:OpBehavior

Behavior for the INT_CARRY operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntScarry[源代码]

基类:OpBehavior

Behavior for the INT_SCARRY operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSborrow[源代码]

基类:OpBehavior

Behavior for the INT_SBORROW operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorInt2Comp[源代码]

基类:OpBehavior

Behavior for the INT_2COMP operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntNegate[源代码]

基类:OpBehavior

Behavior for the INT_NEGATE operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntXor[源代码]

基类:OpBehavior

Behavior for the INT_XOR operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntAnd[源代码]

基类:OpBehavior

Behavior for the INT_AND operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntOr[源代码]

基类:OpBehavior

Behavior for the INT_OR operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntLeft[源代码]

基类:OpBehavior

Behavior for the INT_LEFT operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntRight[源代码]

基类:OpBehavior

Behavior for the INT_RIGHT operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSright[源代码]

基类:OpBehavior

Behavior for the INT_SRIGHT operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntMult[源代码]

基类:OpBehavior

Behavior for the INT_MULT operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntDiv[源代码]

基类:OpBehavior

Behavior for the INT_DIV operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSdiv[源代码]

基类:OpBehavior

Behavior for the INT_SDIV operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntRem[源代码]

基类:OpBehavior

Behavior for the INT_REM operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorIntSrem[源代码]

基类:OpBehavior

Behavior for the INT_SREM operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorBoolNegate[源代码]

基类:OpBehavior

Behavior for the BOOL_NEGATE operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorBoolXor[源代码]

基类:OpBehavior

Behavior for the BOOL_XOR operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorBoolAnd[源代码]

基类:OpBehavior

Behavior for the BOOL_AND operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorBoolOr[源代码]

基类:OpBehavior

Behavior for the BOOL_OR operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatEqual[源代码]

基类:OpBehavior

Behavior for the FLOAT_EQUAL operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatNotEqual[源代码]

基类:OpBehavior

Behavior for the FLOAT_NOTEQUAL operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatLess[源代码]

基类:OpBehavior

Behavior for the FLOAT_LESS operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatLessEqual[源代码]

基类:OpBehavior

Behavior for the FLOAT_LESSEQUAL operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatNan[源代码]

基类:OpBehavior

Behavior for the FLOAT_NAN operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatAdd[源代码]

基类:OpBehavior

Behavior for the FLOAT_ADD operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatDiv[源代码]

基类:OpBehavior

Behavior for the FLOAT_DIV operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatMult[源代码]

基类:OpBehavior

Behavior for the FLOAT_MULT operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatSub[源代码]

基类:OpBehavior

Behavior for the FLOAT_SUB operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatNeg[源代码]

基类:OpBehavior

Behavior for the FLOAT_NEG operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatAbs[源代码]

基类:OpBehavior

Behavior for the FLOAT_ABS operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatSqrt[源代码]

基类:OpBehavior

Behavior for the FLOAT_SQRT operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatInt2Float[源代码]

基类:OpBehavior

Behavior for the FLOAT_INT2FLOAT operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatFloat2Float[源代码]

基类:OpBehavior

Behavior for the FLOAT_FLOAT2FLOAT operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatTrunc[源代码]

基类:OpBehavior

Behavior for the FLOAT_TRUNC operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatCeil[源代码]

基类:OpBehavior

Behavior for the FLOAT_CEIL operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatFloor[源代码]

基类:OpBehavior

Behavior for the FLOAT_FLOOR operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorFloatRound[源代码]

基类:OpBehavior

Behavior for the FLOAT_ROUND operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorPiece[源代码]

基类:OpBehavior

Behavior for the PIECE operation.

__init__()[源代码]
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorSubpiece[源代码]

基类:OpBehavior

Behavior for the SUBPIECE operation.

__init__()[源代码]
evaluate_binary(size_out, size_in, in1, in2)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorPopcount[源代码]

基类:OpBehavior

Behavior for the POPCOUNT operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.OpBehaviorLzcount[源代码]

基类:OpBehavior

Behavior for the LZCOUNT operation.

__init__()[源代码]
evaluate_unary(size_out, size_in, in1)[源代码]
返回类型:

BV

参数:
is_special: bool
is_unary: bool
opcode: int
class angr.engines.pcode.behavior.BehaviorFactory[源代码]

基类:object

Returns the behavior object for a given opcode.

__init__()[源代码]
get_behavior_for_opcode(opcode)[源代码]
返回类型:

OpBehavior

参数:

opcode (int)

class angr.engines.pcode.cc.SimCCM68k(arch)[源代码]

基类:SimCC

Default CC for M68k

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = []
FP_ARG_REGS: list[str] = []
STACKARG_SP_DIFF = 4
RETURN_VAL: SimFunctionArgument = <d0>
RETURN_ADDR: SimFunctionArgument = [0x0]
class angr.engines.pcode.cc.SimCCRISCV(arch)[源代码]

基类:SimCC

Default CC for RISCV

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']
RETURN_ADDR: SimFunctionArgument = <ra>
RETURN_VAL: SimFunctionArgument = <a0>
class angr.engines.pcode.cc.SimCCSPARC(arch)[源代码]

基类:SimCC

Default CC for SPARC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['o0', 'o1', 'o2', 'o3', 'o4', 'o5']
RETURN_VAL: SimFunctionArgument = <o0>
RETURN_ADDR: SimFunctionArgument = <o7>
class angr.engines.pcode.cc.SimCCSH4(arch)[源代码]

基类:SimCC

Default CC for SH4

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r4', 'r5']
RETURN_VAL: SimFunctionArgument = <r0>
RETURN_ADDR: SimFunctionArgument = <pr>
class angr.engines.pcode.cc.SimCCPARISC(arch)[源代码]

基类:SimCC

Default CC for PARISC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r26', 'r25']
RETURN_VAL: SimFunctionArgument = <r28>
RETURN_ADDR: SimFunctionArgument = <rp>
class angr.engines.pcode.cc.SimCCPowerPC(arch)[源代码]

基类:SimCC

Default CC for PowerPC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10']
FP_ARG_REGS: list[str] = []
STACKARG_SP_BUFF = 8
RETURN_ADDR: SimFunctionArgument = <lr>
RETURN_VAL: SimFunctionArgument = <r3>
class angr.engines.pcode.cc.SimCCXtensa(arch)[源代码]

基类:SimCC

Default CC for Xtensa

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['i2', 'i3', 'i4', 'i5', 'i6', 'i7']
FP_ARG_REGS: list[str] = []
RETURN_ADDR: SimFunctionArgument = <a0>
RETURN_VAL: SimFunctionArgument = <o2>
angr.engines.pcode.cc.register_pcode_arch_default_cc(arch)[源代码]
参数:

arch (ArchPcode)

Simulation Logging

class angr.state_plugins.sim_action.SimAction(state, region_type)[源代码]

基类:SimEvent

A SimAction represents a semantic action that an analyzed program performs.

TMP = 'tmp'
REG = 'reg'
MEM = 'mem'
__init__(state, region_type)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
property tmp_deps
property reg_deps
copy()[源代码]
downsize()[源代码]

Clears some low-level details (that take up memory) out of the SimAction.

class angr.state_plugins.sim_action.SimActionExit(state, target, condition=None, exit_type=None)[源代码]

基类:SimAction

An Exit action represents a (possibly conditional) jump.

CONDITIONAL = 'conditional'
DEFAULT = 'default'
__init__(state, target, condition=None, exit_type=None)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
class angr.state_plugins.sim_action.SimActionConstraint(state, constraint, condition=None)[源代码]

基类:SimAction

A constraint action represents an extra constraint added during execution of a path.

__init__(state, constraint, condition=None)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
class angr.state_plugins.sim_action.SimActionOperation(state, op, exprs, result)[源代码]

基类:SimAction

An action representing an operation between variables and/or constants.

__init__(state, op, exprs, result)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

property all_objects
property is_symbolic
class angr.state_plugins.sim_action.SimActionData(state, region_type, action, tmp=None, addr=None, size=None, data=None, condition=None, fallback=None, fd=None)[源代码]

基类:SimAction

A Data action represents a read or a write from memory, registers or a file.

READ = 'read'
WRITE = 'write'
OPERATE = 'operate'
__init__(state, region_type, action, tmp=None, addr=None, size=None, data=None, condition=None, fallback=None, fd=None)[源代码]

Initializes the SimAction.

参数:

state -- the state that's the SimAction is taking place in.

downsize()[源代码]

Clears some low-level details (that take up memory) out of the SimAction.

property all_objects
property is_symbolic
property tmp_deps
property reg_deps
property storage
angr.state_plugins.sim_action_object.ast_preserving_op(f, *args)[源代码]
angr.state_plugins.sim_action_object.ast_stripping_decorator(f)[源代码]
class angr.state_plugins.sim_action_object.SimActionObject(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]

基类:object

A SimActionObject tracks an AST and its dependencies.

参数:
__init__(ast, reg_deps=frozenset({}), tmp_deps=frozenset({}), deps=frozenset({}), state=None)[源代码]
参数:
ast: Base
reg_deps: frozenset[SimActionData | SimActionOperation]
tmp_deps: frozenset[SimActionData | SimActionOperation]
to_claripy()[源代码]
返回类型:

Base

copy()[源代码]
返回类型:

SimActionObject

is_leaf()[源代码]
返回类型:

bool

property op: str
property args: tuple[ArgType, ...]
property length: int | None
property variables: frozenset[str]
property symbolic: bool
property annotations: tuple[Annotation, ...]
property depth: int
SDiv(other)[源代码]
返回类型:

SimActionObject

SMod(other)[源代码]
返回类型:

SimActionObject

union(other)[源代码]
返回类型:

SimActionObject

intersection(other)[源代码]
返回类型:

SimActionObject

widen(other)[源代码]
返回类型:

SimActionObject

raw_to_bv()[源代码]
返回类型:

SimActionObject

bv_to_fp()[源代码]
返回类型:

SimActionObject

class angr.state_plugins.sim_event.SimEvent(state, event_type, **kwargs)[源代码]

基类:object

A SimEvent is a log entry for some notable event during symbolic execution. It logs the location it was generated (ins_addr, bbl_addr, stmt_idx, and sim_procedure) as well as arbitrary tags (objects).

You may also be interested in SimAction, which is a specialization of SimEvent for CPU events.

__init__(state, event_type, **kwargs)[源代码]
angr.state_plugins.sim_event.resource_event(state, exception)[源代码]

Procedures

class angr.sim_procedure.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)[源代码]

基类: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

参数:

The following parameters are optional:

参数:
  • 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

  • project (Project)

  • prototype (SimTypeFunction)

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

变量:
  • 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:

变量:
  • 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:

变量:
  • 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)[源代码]
project: Project
arch: Arch
cc: SimCC
prototype: SimTypeFunction
state: SimState
arg_session: None | ArgSession | int
execute(state, successors=None, arguments=None, ret_to=None)[源代码]

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)[源代码]
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)[源代码]

Implement the actual procedure here!

static_exits(blocks, **kwargs)[源代码]

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

参数:

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

返回:

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

返回类型:

list

dynamic_returns(blocks, **kwargs)[源代码]

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

参数:

blocks -- Blocks that are executed before reaching this SimProcedure.

返回类型:

bool

返回:

True if the call returns, False otherwise.

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

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

参数:
  • 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)[源代码]
ret(expr=None)[源代码]

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')[源代码]

Add an exit representing calling another function via pointer.

参数:
  • 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')[源代码]

Add an exit representing jumping to an address.

exit(exit_code)[源代码]

Add an exit representing terminating the program.

ty_ptr(ty)[源代码]
property is_java
property argument_types
property return_type
class angr.procedures.stubs.format_parser.FormatString(parser, components)[源代码]

基类:object

Describes a format string.

SCANF_DELIMITERS = [b'\t', b'\n', b'\x0b', b'\r', b' ']
__init__(parser, components)[源代码]

Takes a list of components which are either just strings or a FormatSpecifier.

property state
replace(va_arg)[源代码]

Implement printf - based on the stored format specifier information, format the values from the arg getter function args into a string.

参数:

va_arg -- A function which takes a type and returns the next argument of that type

返回:

The result formatted string

interpret(va_arg, addr=None, simfd=None)[源代码]

implement scanf - extract formatted data from memory or a file according to the stored format specifiers and store them into the pointers extracted from args.

参数:
  • va_arg -- A function which, given a type, returns the next argument of that type

  • addr -- The address in the memory to extract data from, or...

  • simfd -- A file descriptor to use for reading data from

返回:

The number of arguments parsed

class angr.procedures.stubs.format_parser.FormatSpecifier(string, length_spec, pad_chr, size, signed)[源代码]

基类:object

Describes a format specifier within a format string.

__init__(string, length_spec, pad_chr, size, signed)[源代码]
string
size
signed
length_spec
pad_chr
property spec_type
class angr.procedures.stubs.format_parser.FormatParser(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)[源代码]

基类:SimProcedure

For SimProcedures relying on printf-style format strings.

参数:
ARGS_MISMATCH = True
basic_spec = {b'A': double, b'E': double, b'F': double, b'G': double, b'X': unsigned int, b'a': double, b'c': char, b'd': int, b'e': double, b'f': double, b'g': double, b'i': int, b'n': unsigned int*, b'o': unsigned int, b'p': unsigned int*, b's': char*, b'u': unsigned int, b'x': unsigned int}
int_sign = {'signed': [b'd', b'i'], 'unsigned': [b'o', b'u', b'x', b'X']}
int_len_mod = {b'h': (short, unsigned short), b'hh': (char, char), b'j': (long long, unsigned long long), b'l': (long, unsigned long), b'll': (long long, unsigned long long), b't': (long, long), b'z': (size_t, size_t)}
other_types = {('string',): <function FormatParser.<lambda>>}
flags = ['#', '0', '\\-', ' ', '\\+', "\\'", 'I']
extract_components(fmt)[源代码]

Extract the actual formats from the format string fmt.

参数:

fmt (list) -- A list of format chars.

返回类型:

list

返回:

a FormatString object

class angr.procedures.stubs.format_parser.ScanfFormatParser(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)[源代码]

基类:FormatParser

For SimProcedures relying on scanf-style format strings.

basic_spec = {b'A': float, b'E': float, b'F': float, b'G': float, b'X': unsigned int, b'a': float, b'c': char, b'd': int, b'e': float, b'f': float, b'g': float, b'i': int, b'n': unsigned int*, b'o': unsigned int, b'p': unsigned int*, b's': char*, b'u': unsigned int, b'x': unsigned int}
float_spec = [b'e', b'E', b'f', b'F', b'g', b'G', b'a', b'A']
float_len_mod = {b'l': <class 'angr.sim_type.SimTypeDouble'>, b'll': <class 'angr.sim_type.SimTypeDouble'>}
class angr.procedures.definitions.SimTypeCollection[源代码]

基类:object

A type collection is the mechanism for describing types. Types in a type collection can be referenced using

__init__()[源代码]
set_names(*names)[源代码]
add(name, t)[源代码]

Add a type to the collection.

参数:
  • name (str) -- Name of the type to add.

  • t (SimType) -- The SimType object to add to the collection.

返回类型:

None

get(name, bottom_on_missing=False)[源代码]

Get a SimType object from the collection as identified by the name.

参数:
  • name (str) -- Name of the type to get.

  • bottom_on_missing (bool) -- Return a SimTypeBottom object if the required type does not exist.

返回类型:

SimType

返回:

The SimType object.

init_str()[源代码]
返回类型:

str

class angr.procedures.definitions.SimLibrary[源代码]

基类:object

A SimLibrary is the mechanism for describing a dynamic library's API, its functions and metadata.

Any instance of this class (or its subclasses) found in the angr.procedures.definitions package will be automatically picked up and added to angr.SIM_LIBRARIES via all its names.

变量:
  • fallback_cc -- A mapping from architecture to the default calling convention that should be used if no other information is present. Contains some sane defaults for linux.

  • fallback_proc -- A SimProcedure class that should be used to provide stub procedures. By default, ReturnUnconstrained.

__init__()[源代码]
copy()[源代码]

Make a copy of this SimLibrary, allowing it to be mutated without affecting the global version.

返回:

A new SimLibrary object with the same library references but different dict/list references

update(other)[源代码]

Augment this SimLibrary with the information from another SimLibrary

参数:

other -- The other SimLibrary

property name

The first common name of this library, e.g. libc.so.6, or '??????' if none are known.

set_library_names(*names)[源代码]

Set some common names of this library by which it may be referred during linking

参数:

names -- Any number of string library names may be passed as varargs.

set_default_cc(arch_name, cc_cls)[源代码]

Set the default calling convention used for this library under a given architecture

参数:

arch_name -- The string name of the architecture, i.e. the .name field from archinfo.

Parm cc_cls:

The SimCC class (not an instance!) to use

set_non_returning(*names)[源代码]

Mark some functions in this class as never returning, i.e. loops forever or terminates execution

参数:

names -- Any number of string function names may be passed as varargs

set_prototype(name, proto)[源代码]

Set the prototype of a function in the form of a SimTypeFunction containing argument and return types

参数:
  • name -- The name of the function as a string

  • proto -- The prototype of the function as a SimTypeFunction

set_prototypes(protos)[源代码]

Set the prototypes of many functions

参数:

protos -- Dictionary mapping function names to SimTypeFunction objects

set_c_prototype(c_decl)[源代码]

Set the prototype of a function in the form of a C-style function declaration.

参数:

c_decl (str) -- The C-style declaration of the function.

返回:

A tuple of (function name, function prototype)

返回类型:

tuple

add(name, proc_cls, **kwargs)[源代码]

Add a function implementation to the library.

参数:
  • name -- The name of the function as a string

  • proc_cls -- The implementation of the function as a SimProcedure _class_, not instance

  • kwargs -- Any additional parameters to the procedure class constructor may be passed as kwargs

add_all_from_dict(dictionary, **kwargs)[源代码]

Batch-add function implementations to the library.

参数:
  • dictionary -- A mapping from name to procedure class, i.e. the first two arguments to add()

  • kwargs -- Any additional kwargs will be passed to the constructors of _each_ procedure class

add_alias(name, *alt_names)[源代码]

Add some duplicate names for a given function. The original function's implementation must already be registered.

参数:
  • name -- The name of the function for which an implementation is already present

  • alt_names -- Any number of alternate names may be passed as varargs

get(name, arch)[源代码]

Get an implementation of the given function specialized for the given arch, or a stub procedure if none exists.

参数:
  • name -- The name of the function as a string

  • arch -- The architecure to use, as either a string or an archinfo.Arch instance

返回:

A SimProcedure instance representing the function as found in the library

get_stub(name, arch)[源代码]

Get a stub procedure for the given function, regardless of if a real implementation is available. This will apply any metadata, such as a default calling convention or a function prototype.

By stub, we pretty much always mean a ReturnUnconstrained SimProcedure with the appropriate display name and metadata set. This will appear in state.history.descriptions as <SimProcedure display_name (stub)>

参数:
  • name -- The name of the function as a string

  • arch -- The architecture to use, as either a string or an archinfo.Arch instance

返回:

A SimProcedure instance representing a plausable stub as could be found in the library.

get_prototype(name, arch=None)[源代码]

Get a prototype of the given function name, optionally specialize the prototype to a given architecture.

参数:
  • name (str) -- Name of the function.

  • arch -- The architecture to specialize to.

返回类型:

SimTypeFunction | None

返回:

Prototype of the function, or None if the prototype does not exist.

has_metadata(name)[源代码]

Check if a function has either an implementation or any metadata associated with it

参数:

name -- The name of the function as a string

返回:

A bool indicating if anything is known about the function

has_implementation(name)[源代码]

Check if a function has an implementation associated with it

参数:

name -- The name of the function as a string

返回:

A bool indicating if an implementation of the function is available

has_prototype(func_name)[源代码]

Check if a function has a prototype associated with it.

参数:

func_name (str) -- The name of the function.

返回:

A bool indicating if a prototype of the function is available.

返回类型:

bool

class angr.procedures.definitions.SimCppLibrary[源代码]

基类:SimLibrary

SimCppLibrary is a specialized version of SimLibrary that will demangle C++ function names before looking for an implementation or prototype for it.

get(name, arch)[源代码]

Get an implementation of the given function specialized for the given arch, or a stub procedure if none exists. Demangle the function name if it is a mangled C++ name.

参数:
  • name (str) -- The name of the function as a string

  • arch -- The architecure to use, as either a string or an archinfo.Arch instance

返回:

A SimProcedure instance representing the function as found in the library

get_stub(name, arch)[源代码]

Get a stub procedure for the given function, regardless of if a real implementation is available. This will apply any metadata, such as a default calling convention or a function prototype. Demangle the function name if it is a mangled C++ name.

参数:
  • name (str) -- The name of the function as a string

  • arch -- The architecture to use, as either a string or an archinfo.Arch instance

返回:

A SimProcedure instance representing a plausable stub as could be found in the library.

get_prototype(name, arch=None)[源代码]

Get a prototype of the given function name, optionally specialize the prototype to a given architecture. The function name will be demangled first.

参数:
  • name (str) -- Name of the function.

  • arch -- The architecture to specialize to.

返回类型:

SimTypeFunction | None

返回:

Prototype of the function, or None if the prototype does not exist.

has_metadata(name)[源代码]

Check if a function has either an implementation or any metadata associated with it. Demangle the function name if it is a mangled C++ name.

参数:

name -- The name of the function as a string

返回:

A bool indicating if anything is known about the function

has_implementation(name)[源代码]

Check if a function has an implementation associated with it. Demangle the function name if it is a mangled C++ name.

参数:

name (str) -- A mangled function name.

返回:

bool

has_prototype(func_name)[源代码]

Check if a function has a prototype associated with it. Demangle the function name if it is a mangled C++ name.

参数:

name (str) -- A mangled function name.

返回:

bool

class angr.procedures.definitions.SimSyscallLibrary[源代码]

基类:SimLibrary

SimSyscallLibrary is a specialized version of SimLibrary for dealing not with a dynamic library's API but rather an operating system's syscall API. Because this interface is inherently lower-level than a dynamic library, many parts of this class has been changed to store data based on an "ABI name" (ABI = application binary interface, like an API but for when there's no programming language) instead of an architecture. An ABI name is just an arbitrary string with which a calling convention and a syscall numbering is associated.

All the SimLibrary methods for adding functions still work, but now there's an additional layer on top that associates them with numbers.

__init__()[源代码]
copy()[源代码]

Make a copy of this SimLibrary, allowing it to be mutated without affecting the global version.

返回:

A new SimLibrary object with the same library references but different dict/list references

update(other)[源代码]

Augment this SimLibrary with the information from another SimLibrary

参数:

other -- The other SimLibrary

minimum_syscall_number(abi)[源代码]
参数:

abi -- The abi to evaluate

返回:

The smallest syscall number known for the given abi

maximum_syscall_number(abi)[源代码]
参数:

abi -- The abi to evaluate

返回:

The largest syscall number known for the given abi

add_number_mapping(abi, number, name)[源代码]

Associate a syscall number with the name of a function present in the underlying SimLibrary

参数:
  • abi -- The abi for which this mapping applies

  • number -- The syscall number

  • name -- The name of the function

add_number_mapping_from_dict(abi, mapping)[源代码]

Batch-associate syscall numbers with names of functions present in the underlying SimLibrary

参数:
  • abi -- The abi for which this mapping applies

  • mapping -- A dict mapping syscall numbers to function names

set_abi_cc(abi, cc_cls)[源代码]

Set the default calling convention for an abi

参数:
  • abi -- The name of the abi

  • cc_cls -- A SimCC _class_, not an instance, that should be used for syscalls using the abi

set_prototype(abi, name, proto)[源代码]

Set the prototype of a function in the form of a SimTypeFunction containing argument and return types

参数:
  • abi (str) -- ABI of the syscall.

  • name (str) -- The name of the syscall as a string

  • proto (SimTypeFunction) -- The prototype of the syscall as a SimTypeFunction

返回类型:

None

set_prototypes(abi, protos)[源代码]

Set the prototypes of many syscalls.

参数:
  • abi (str) -- ABI of the syscalls.

  • protos (dict[str, SimTypeFunction]) -- Dictionary mapping syscall names to SimTypeFunction objects

返回类型:

None

get(number, arch, abi_list=())[源代码]

The get() function for SimSyscallLibrary looks a little different from its original version.

Instead of providing a name, you provide a number, and you additionally provide a list of abi names that are applicable. The first abi for which the number is present in the mapping will be chosen. This allows for the easy abstractions of architectures like ARM or MIPS linux for which there are many ABIs that can be used at any time by using syscall numbers from various ranges. If no abi knows about the number, the stub procedure with the name "sys_%d" will be used.

参数:
  • number -- The syscall number

  • arch -- The architecture being worked with, as either a string name or an archinfo.Arch

  • abi_list -- A list of ABI names that could be used

返回:

A SimProcedure representing the implementation of the given syscall, or a stub if no implementation is available

get_stub(number, arch, abi_list=())[源代码]

Pretty much the intersection of SimLibrary.get_stub() and SimSyscallLibrary.get().

参数:
  • number -- The syscall number

  • arch -- The architecture being worked with, as either a string name or an archinfo.Arch

  • abi_list -- A list of ABI names that could be used

返回:

A SimProcedure representing a plausable stub that could model the syscall

get_prototype(abi, name, arch=None)[源代码]

Get a prototype of the given syscall name and its ABI, optionally specialize the prototype to a given architecture.

参数:
  • abi (str) -- ABI of the prototype to get.

  • name (str) -- Name of the syscall.

  • arch -- The architecture to specialize to.

返回类型:

SimTypeFunction | None

返回:

Prototype of the syscall, or None if the prototype does not exist.

has_metadata(number, arch, abi_list=())[源代码]

Pretty much the intersection of SimLibrary.has_metadata() and SimSyscallLibrary.get().

参数:
  • number -- The syscall number

  • arch -- The architecture being worked with, as either a string name or an archinfo.Arch

  • abi_list -- A list of ABI names that could be used

返回:

A bool of whether or not any implementation or metadata is known about the given syscall

has_implementation(number, arch, abi_list=())[源代码]

Pretty much the intersection of SimLibrary.has_implementation() and SimSyscallLibrary.get().

参数:
  • number -- The syscall number

  • arch -- The architecture being worked with, as either a string name or an archinfo.Arch

  • abi_list -- A list of ABI names that could be used

返回:

A bool of whether or not an implementation of the syscall is available

has_prototype(abi, name)[源代码]

Check if a function has a prototype associated with it. Demangle the function name if it is a mangled C++ name.

参数:
  • abi (str) -- Name of the ABI.

  • name (str) -- The syscall name.

返回类型:

bool

返回:

bool

angr.procedures.definitions.load_type_collections(skip=None)[源代码]
返回类型:

None

angr.procedures.definitions.load_win32_type_collections()[源代码]
返回类型:

None

angr.procedures.definitions.load_external_definitions()[源代码]

Load library definitions from specific directories. By default it parses ANGR_EXTERNAL_DEFINITIONS_DIRS as a semicolon separated list of directory paths. Then it loads all .py files in each directory. These .py files should declare SimLibrary() objects and call .set_library_names() to register themselves in angr.SIM_LIBRARIES.

angr.procedures.definitions.load_win32api_definitions()[源代码]
angr.procedures.definitions.load_all_definitions()[源代码]

Calling Conventions and Types

class angr.calling_conventions.PointerWrapper(value, buffer=False)[源代码]

基类:object

__init__(value, buffer=False)[源代码]
class angr.calling_conventions.AllocHelper(ptrsize)[源代码]

基类:object

__init__(ptrsize)[源代码]
alloc(size)[源代码]
dump(val, state, loc=None)[源代码]
translate(val, base)[源代码]
apply(state, base)[源代码]
size()[源代码]
classmethod calc_size(val, arch)[源代码]
classmethod stack_loc(val, arch, offset=0)[源代码]
angr.calling_conventions.refine_locs_with_struct_type(arch, locs, arg_type, offset=0, treat_bot_as_int=True)[源代码]
参数:
class angr.calling_conventions.SerializableIterator[源代码]

基类:object

getstate()[源代码]
setstate(state)[源代码]
class angr.calling_conventions.SerializableListIterator(lst)[源代码]

基类:SerializableIterator

__init__(lst)[源代码]
getstate()[源代码]
setstate(state)[源代码]
class angr.calling_conventions.SerializableCounter(start, stride, mapping=<function SerializableCounter.<lambda>>)[源代码]

基类:SerializableIterator

__init__(start, stride, mapping=<function SerializableCounter.<lambda>>)[源代码]
getstate()[源代码]
setstate(state)[源代码]
class angr.calling_conventions.SimFunctionArgument(size, is_fp=False)[源代码]

基类:object

Represent a generic function argument.

变量:
  • size (int) -- The size of the argument, in number of bytes.

  • is_fp (bool) -- Whether loads from this location should return a floating point bitvector

参数:
__init__(size, is_fp=False)[源代码]
参数:
check_value_set(value, arch)[源代码]
check_value_get(value)[源代码]
set_value(state, value, **kwargs)[源代码]
get_value(state, **kwargs)[源代码]
refine(size, arch=None, offset=None, is_fp=None)[源代码]
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

返回类型:

Iterable[SimRegArg | SimStackArg]

class angr.calling_conventions.SimRegArg(reg_name, size, reg_offset=0, is_fp=False, clear_entire_reg=False)[源代码]

基类:SimFunctionArgument

Represents a function argument that has been passed in a register.

变量:
  • reg_name (string) -- The name of the represented register.

  • size (int) -- The size of the data to store, in number of bytes.

  • reg_offset -- The offset into the register to start storing data.

  • clear_entire_reg -- Whether a store to this register should zero the unused parts of the register.

  • is_fp (bool) -- Whether loads from this location should return a floating point bitvector

参数:
  • reg_name (RegisterName)

  • size (int)

__init__(reg_name, size, reg_offset=0, is_fp=False, clear_entire_reg=False)[源代码]
参数:
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

check_offset(arch)[源代码]
set_value(state, value, **kwargs)[源代码]
get_value(state, **kwargs)[源代码]
refine(size, arch=None, offset=None, is_fp=None)[源代码]
sse_extend()[源代码]
class angr.calling_conventions.SimStackArg(stack_offset, size, is_fp=False)[源代码]

基类:SimFunctionArgument

Represents a function argument that has been passed on the stack.

变量:
  • stack_offset (int) -- The position of the argument relative to the stack pointer after the function prelude.

  • size (int) -- The size of the argument, in number of bytes.

  • is_fp (bool) -- Whether loads from this location should return a floating point bitvector

参数:
__init__(stack_offset, size, is_fp=False)[源代码]
参数:
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

set_value(state, value, stack_base=None, **kwargs)[源代码]
get_value(state, stack_base=None, **kwargs)[源代码]
refine(size, arch=None, offset=None, is_fp=None)[源代码]
class angr.calling_conventions.SimComboArg(locations, is_fp=False)[源代码]

基类:SimFunctionArgument

An argument which spans multiple storage locations. Locations should be given least-significant first.

__init__(locations, is_fp=False)[源代码]
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

set_value(state, value, **kwargs)[源代码]
get_value(state, **kwargs)[源代码]
class angr.calling_conventions.SimStructArg(struct, locs)[源代码]

基类:SimFunctionArgument

An argument which de/serializes a struct from a list of storage locations

变量:
  • struct -- The simtype describing the structure

  • locs -- The storage locations to use

参数:
__init__(struct, locs)[源代码]
参数:
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

get_value(state, **kwargs)[源代码]
set_value(state, value, **kwargs)[源代码]
class angr.calling_conventions.SimArrayArg(locs)[源代码]

基类:SimFunctionArgument

__init__(locs)[源代码]
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

get_value(state, **kwargs)[源代码]
set_value(state, value, **kwargs)[源代码]
class angr.calling_conventions.SimReferenceArgument(ptr_loc, main_loc)[源代码]

基类:SimFunctionArgument

A function argument which is passed by reference.

变量:
  • ptr_loc -- The location the reference's pointer is stored

  • main_loc -- A SimStackArgument describing how to load the argument's value as if it were stored at offset zero on the stack. It will be passed stack_base=ptr_loc.get_value(state)

__init__(ptr_loc, main_loc)[源代码]
get_footprint()[源代码]

Return a list of SimRegArg and SimStackArgs that are the base components used for this location

get_value(state, **kwargs)[源代码]
set_value(state, value, **kwargs)[源代码]
class angr.calling_conventions.ArgSession(cc)[源代码]

基类:object

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

__init__(cc)[源代码]
cc
fp_iter
int_iter
both_iter
getstate()[源代码]
setstate(state)[源代码]
class angr.calling_conventions.UsercallArgSession(cc)[源代码]

基类:object

An argsession for use with SimCCUsercall

__init__(cc)[源代码]
cc
real_args
getstate()[源代码]
setstate(state)[源代码]
class angr.calling_conventions.SimCC(arch)[源代码]

基类: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.

参数:

arch (archinfo.Arch)

__init__(arch)[源代码]
参数:

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)[源代码]

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)

基类:object

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

both_iter
cc
fp_iter
int_iter
__init__(cc)
getstate()
setstate(state)
arg_session(ret_ty)[源代码]

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.

参数:

ret_ty (SimType | None)

return_in_implicit_outparam(ty)[源代码]
stack_space(args)[源代码]
参数:

args -- A list of SimFunctionArguments

返回:

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)[源代码]

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)[源代码]
参数:
static is_fp_value(val)[源代码]
static guess_prototype(args, prototype=None)[源代码]

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)[源代码]
返回类型:

list[SimFunctionArgument]

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

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

参数:
  • 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)[源代码]

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

参数:
  • 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')[源代码]

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

参数:
  • 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)

返回类型:

SimCC | None

返回:

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

get_arg_info(state, prototype)[源代码]

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.calling_conventions.SimLyingRegArg(name, size=8)[源代码]

基类:SimRegArg

A register that LIES about the types it holds

__init__(name, size=8)[源代码]
get_value(state, **kwargs)[源代码]
set_value(state, value, **kwargs)[源代码]
refine(size, arch=None, offset=None, is_fp=None)[源代码]
class angr.calling_conventions.SimCCUsercall(arch, args, ret_loc)[源代码]

基类:SimCC

__init__(arch, args, ret_loc)[源代码]
参数:

arch -- The Archinfo arch for this CC

ArgSession

UsercallArgSession 的别名

next_arg(session, arg_type)[源代码]
return_val(ty, **kwargs)[源代码]

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

class angr.calling_conventions.SimCCCdecl(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = []
FP_ARG_REGS: list[str] = []
STACKARG_SP_DIFF = 4
CALLER_SAVED_REGS: list[str] = ['eax', 'ecx', 'edx']
RETURN_VAL: SimFunctionArgument = <eax>
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = <edx>
FP_RETURN_VAL: SimFunctionArgument | None = <st0>
RETURN_ADDR: SimFunctionArgument = [0x0]
ARCH

ArchX86 的别名

next_arg(session, arg_type)[源代码]
STRUCT_RETURN_THRESHOLD = 32
return_val(ty, perspective_returned=False)[源代码]

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

return_in_implicit_outparam(ty)[源代码]
class angr.calling_conventions.SimCCMicrosoftCdecl(arch)[源代码]

基类:SimCCCdecl

参数:

arch (archinfo.Arch)

STRUCT_RETURN_THRESHOLD = 64
class angr.calling_conventions.SimCCStdcall(arch)[源代码]

基类:SimCCMicrosoftCdecl

参数:

arch (archinfo.Arch)

CALLEE_CLEANUP = True
class angr.calling_conventions.SimCCMicrosoftFastcall(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['ecx', 'edx']
STACKARG_SP_DIFF = 4
RETURN_VAL: SimFunctionArgument = <eax>
RETURN_ADDR: SimFunctionArgument = [0x0]
ARCH

ArchX86 的别名

class angr.calling_conventions.MicrosoftAMD64ArgSession(cc)[源代码]

基类:object

__init__(cc)[源代码]
class angr.calling_conventions.SimCCMicrosoftAMD64(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['rcx', 'rdx', 'r8', 'r9']
FP_ARG_REGS: list[str] = ['xmm0', 'xmm1', 'xmm2', 'xmm3']
STACKARG_SP_DIFF = 8
STACKARG_SP_BUFF = 32
RETURN_VAL: SimFunctionArgument = <rax>
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = <rdx>
FP_RETURN_VAL: SimFunctionArgument | None = <xmm0>
RETURN_ADDR: SimFunctionArgument = [0x0]
ARCH

ArchAMD64 的别名

STACK_ALIGNMENT = 16
ArgSession

MicrosoftAMD64ArgSession 的别名

STRUCT_RETURN_THRESHOLD = 64
next_arg(session, arg_type)[源代码]
return_in_implicit_outparam(ty)[源代码]
return_val(ty, perspective_returned=False)[源代码]

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

class angr.calling_conventions.SimCCSyscall(arch)[源代码]

基类:SimCC

The base class of all syscall CCs.

参数:

arch (archinfo.Arch)

ERROR_REG: SimRegArg = None
SYSCALL_ERRNO_START = None
static syscall_num(state)[源代码]
返回类型:

int

linux_syscall_update_error_reg(state, expr)[源代码]
set_return_val(state, val, ty, **kwargs)[源代码]
class angr.calling_conventions.SimCCX86LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <eax>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchX86 的别名

static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCX86WindowsSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = []
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <eax>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchX86 的别名

static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCSystemVAMD64(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['rdi', 'rsi', 'rdx', 'rcx', 'r8', 'r9']
FP_ARG_REGS: list[str] = ['xmm0', 'xmm1', 'xmm2', 'xmm3', 'xmm4', 'xmm5', 'xmm6', 'xmm7']
STACKARG_SP_DIFF = 8
CALLER_SAVED_REGS: list[str] = ['rdi', 'rsi', 'rdx', 'rcx', 'r8', 'r9', 'r10', 'r11', 'rax']
RETURN_ADDR: SimFunctionArgument = [0x0]
RETURN_VAL: SimFunctionArgument = <rax>
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = <rdx>
FP_RETURN_VAL: SimFunctionArgument | None = <xmm0>
OVERFLOW_FP_RETURN_VAL = <xmm1>
ARCH

ArchAMD64 的别名

STACK_ALIGNMENT = 16
next_arg(session, arg_type)[源代码]
return_val(ty, perspective_returned=False)[源代码]

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

参数:

ty (SimType | None)

return_in_implicit_outparam(ty)[源代码]
class angr.calling_conventions.SimCCAMD64LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['rdi', 'rsi', 'rdx', 'r10', 'r8', 'r9']
RETURN_VAL: SimFunctionArgument = <rax>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchAMD64 的别名

CALLER_SAVED_REGS: list[str] = ['rax', 'rcx', 'r11']
static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCAMD64WindowsSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = []
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <rax>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchAMD64 的别名

static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCARM(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r0', 'r1', 'r2', 'r3']
FP_ARG_REGS: list[str] = []
CALLER_SAVED_REGS: list[str] = ['r0', 'r1', 'r2', 'r3']
RETURN_ADDR: SimFunctionArgument = <lr>
RETURN_VAL: SimFunctionArgument = <r0>
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = <r1>
ARCH

ArchARM 的别名

next_arg(session, arg_type)[源代码]
class angr.calling_conventions.SimCCARMHF(arch)[源代码]

基类:SimCCARM

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r0', 'r1', 'r2', 'r3']
FP_ARG_REGS: list[str] = ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13', 's14', 's15']
FP_RETURN_VAL: SimFunctionArgument | None = <s0>
CALLER_SAVED_REGS: list[str] = []
RETURN_ADDR: SimFunctionArgument = <lr>
RETURN_VAL: SimFunctionArgument = <r0>
ARCH

ArchARMHF 的别名

class angr.calling_conventions.SimCCARMLinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r0', 'r1', 'r2', 'r3']
FP_ARG_REGS: list[str] = []
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
RETURN_VAL: SimFunctionArgument = <r0>
ARCH

ArchARM 的别名

static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCAArch64(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7']
FP_ARG_REGS: list[str] = []
RETURN_ADDR: SimFunctionArgument = <lr>
RETURN_VAL: SimFunctionArgument = <x0>
ARCH

ArchAArch64 的别名

class angr.calling_conventions.SimCCAArch64LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <x0>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchAArch64 的别名

static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCRISCV64LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <a0>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchRISCV64 的别名

static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCO32(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['a0', 'a1', 'a2', 'a3']
FP_ARG_REGS: list[str] = ['f12', 'f13', 'f14', 'f15']
STACKARG_SP_BUFF = 16
CALLER_SAVED_REGS: list[str] = ['t9', 'gp']
RETURN_ADDR: SimFunctionArgument = <ra>
RETURN_VAL: SimFunctionArgument = <v0>
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = <v1>
ARCH

ArchMIPS32 的别名

next_arg(session, arg_type)[源代码]
class angr.calling_conventions.SimCCO32LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['a0', 'a1', 'a2', 'a3']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <v0>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchMIPS32 的别名

ERROR_REG: SimRegArg = <a3>
SYSCALL_ERRNO_START = -1133
static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCN64(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']
CALLER_SAVED_REGS: list[str] = ['t9', 'gp']
FP_ARG_REGS: list[str] = []
STACKARG_SP_BUFF = 32
RETURN_ADDR: SimFunctionArgument = <ra>
RETURN_VAL: SimFunctionArgument = <v0>
ARCH

ArchMIPS64 的别名

angr.calling_conventions.SimCCO64

SimCCN64 的别名

class angr.calling_conventions.SimCCN64LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <v0>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchMIPS64 的别名

ERROR_REG: SimRegArg = <a3>
SYSCALL_ERRNO_START = -1133
static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCPowerPC(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10']
FP_ARG_REGS: list[str] = []
STACKARG_SP_BUFF = 8
RETURN_ADDR: SimFunctionArgument = <lr>
RETURN_VAL: SimFunctionArgument = <r3>
OVERFLOW_RETURN_VAL: SimFunctionArgument | None = <r4>
ARCH

ArchPPC32 的别名

class angr.calling_conventions.SimCCPowerPCLinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <r3>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchPPC32 的别名

ERROR_REG: SimRegArg = <cr0_0>
SYSCALL_ERRNO_START = -515
static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCPowerPC64(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10']
FP_ARG_REGS: list[str] = []
STACKARG_SP_BUFF = 112
RETURN_ADDR: SimFunctionArgument = <lr>
RETURN_VAL: SimFunctionArgument = <r3>
ARCH

ArchPPC64 的别名

class angr.calling_conventions.SimCCPowerPC64LinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <r3>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchPPC64 的别名

ERROR_REG: SimRegArg = <cr0_0>
SYSCALL_ERRNO_START = -515
static syscall_num(state)[源代码]
class angr.calling_conventions.SimCCSoot(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARCH

ArchSoot 的别名

ARG_REGS: list[str] = []
setup_callsite(state, ret_addr, args, prototype, stack_base=None, alloc_base=None, grow_like_stack=True)[源代码]

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

参数:
  • 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.

static guess_prototype(args, prototype=None)[源代码]

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.

class angr.calling_conventions.SimCCUnknown(arch)[源代码]

基类:SimCC

Represent an unknown calling convention.

参数:

arch (archinfo.Arch)

class angr.calling_conventions.SimCCS390X(arch)[源代码]

基类:SimCC

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r2', 'r3', 'r4', 'r5', 'r6']
FP_ARG_REGS: list[str] = ['f0', 'f2', 'f4', 'f6']
STACKARG_SP_BUFF = 160
RETURN_ADDR: SimFunctionArgument = <r14>
RETURN_VAL: SimFunctionArgument = <r2>
ARCH

ArchS390X 的别名

class angr.calling_conventions.SimCCS390XLinuxSyscall(arch)[源代码]

基类:SimCCSyscall

参数:

arch (archinfo.Arch)

ARG_REGS: list[str] = ['r2', 'r3', 'r4', 'r5', 'r6', 'r7']
FP_ARG_REGS: list[str] = []
RETURN_VAL: SimFunctionArgument = <r2>
RETURN_ADDR: SimFunctionArgument = <ip_at_syscall>
ARCH

ArchS390X 的别名

static syscall_num(state)[源代码]
angr.calling_conventions.register_default_cc(arch, cc, platform='Linux')[源代码]
参数:
angr.calling_conventions.default_cc(arch, platform='Linux', language=None, syscall=False, default=None)[源代码]

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

参数:
  • 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).

  • default (Optional[type[SimCC]]) -- The default calling convention to return if nothing fits.

返回类型:

type[SimCC] | None

返回:

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

angr.calling_conventions.unify_arch_name(arch)[源代码]

Return the unified architecture name.

参数:

arch (str) -- The architecture name.

返回类型:

str

返回:

A unified architecture name.

angr.calling_conventions.register_syscall_cc(arch, os, cc)[源代码]
class angr.sim_variable.SimVariable(size, ident=None, name=None, region=None, category=None)[源代码]

基类:Serializable

参数:
  • size (int)

  • ident (str | None)

  • name (str | None)

  • region (int | None)

__init__(size, ident=None, name=None, region=None, category=None)[源代码]
参数:
  • ident (Optional[str]) -- A unique identifier provided by user or the program. Usually a string.

  • name (str) -- Name of this variable.

  • size (int)

  • region (int | None)

ident
name
region: int | None
category: str | None
renamed
candidate_names
size
copy()[源代码]
loc_repr(arch)[源代码]

The representation that shows up in a GUI

参数:

arch (Arch)

property is_function_argument
class angr.sim_variable.SimConstantVariable(size, ident=None, value=None, region=None)[源代码]

基类:SimVariable

参数:
  • size (int)

  • region (int | None)

__init__(size, ident=None, value=None, region=None)[源代码]
参数:
  • ident -- A unique identifier provided by user or the program. Usually a string.

  • name (str) -- Name of this variable.

  • size (int)

value
loc_repr(arch)[源代码]

The representation that shows up in a GUI

copy()[源代码]
返回类型:

SimConstantVariable

class angr.sim_variable.SimTemporaryVariable(tmp_id, size)[源代码]

基类:SimVariable

参数:
__init__(tmp_id, size)[源代码]
参数:
  • ident -- A unique identifier provided by user or the program. Usually a string.

  • name (str) -- Name of this variable.

  • tmp_id (int)

  • size (int)

tmp_id
loc_repr(arch)[源代码]

The representation that shows up in a GUI

copy()[源代码]
返回类型:

SimTemporaryVariable

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.sim_variable.SimRegisterVariable(reg_offset, size, ident=None, name=None, region=None, category=None)[源代码]

基类:SimVariable

参数:
  • reg_offset (int)

  • size (int)

  • region (int | None)

  • category (str | None)

__init__(reg_offset, size, ident=None, name=None, region=None, category=None)[源代码]
参数:
  • ident -- A unique identifier provided by user or the program. Usually a string.

  • name (str) -- Name of this variable.

  • reg_offset (int)

  • size (int)

reg
property bits
loc_repr(arch)[源代码]

The representation that shows up in a GUI

copy()[源代码]
返回类型:

SimRegisterVariable

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.sim_variable.SimMemoryVariable(addr, size, ident=None, name=None, region=None, category=None)[源代码]

基类:SimVariable

参数:
  • size (int)

  • region (int | None)

  • category (str | None)

__init__(addr, size, ident=None, name=None, region=None, category=None)[源代码]
参数:
  • ident -- A unique identifier provided by user or the program. Usually a string.

  • name (str) -- Name of this variable.

  • size (int)

addr
loc_repr(arch)[源代码]

The representation that shows up in a GUI

property bits
copy()[源代码]
返回类型:

SimMemoryVariable

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.sim_variable.SimStackVariable(offset, size, base='sp', base_addr=None, ident=None, name=None, region=None, category=None)[源代码]

基类:SimMemoryVariable

参数:
  • offset (int)

  • size (int)

  • region (int | None)

  • category (str | None)

__init__(offset, size, base='sp', base_addr=None, ident=None, name=None, region=None, category=None)[源代码]
参数:
  • ident -- A unique identifier provided by user or the program. Usually a string.

  • name (str) -- Name of this variable.

  • offset (int)

  • size (int)

base
offset
base_addr
loc_repr(arch)[源代码]

The representation that shows up in a GUI

copy()[源代码]
返回类型:

SimStackVariable

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.sim_variable.SimVariableSet[源代码]

基类:MutableSet

A collection of SimVariables.

__init__()[源代码]
add(value)[源代码]

Add an element.

add_register_variable(reg_var)[源代码]
add_memory_variable(mem_var)[源代码]
discard(value)[源代码]

Remove an element. Do not raise an exception if absent.

discard_register_variable(reg_var)[源代码]
discard_memory_variable(mem_var)[源代码]
add_memory_variables(addrs, size)[源代码]
copy()[源代码]
complement(other)[源代码]

Calculate the complement of self and other.

参数:

other -- Another SimVariableSet instance.

返回:

The complement result.

contains_register_variable(reg_var)[源代码]
contains_memory_variable(mem_var)[源代码]
class angr.sim_type.SimType(label=None)[源代码]

基类:object

SimType exists to track type information for SimProcedures.

base: bool = True
__init__(label=None)[源代码]
参数:

label -- the type label.

property size: int | None

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

with_arch(arch)[源代码]
参数:

arch (Arch | None)

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:
  • indent (int | None)

  • name_parens (bool)

copy()[源代码]
extract(state, addr, concrete=False)[源代码]
返回类型:

Any

参数:
store(state, addr, value)[源代码]
参数:
extract_claripy(bits)[源代码]

Given a bitvector bits which was loaded from memory in a big-endian fashion, return a more appropriate or structured representation of the data.

A type must have an arch associated in order to use this method.

返回类型:

Any

class angr.sim_type.TypeRef(name, ty)[源代码]

基类:SimType

A TypeRef is a reference to a type with a name. This allows for interactivity in type analysis, by storing a type and having the option to update it later and have all references to it automatically update as well.

__init__(name, ty)[源代码]
参数:

label -- the type label.

property type
property name

This is a read-only property because it is desirable to store typerefs in a mapping from name to type, and we want the mapping to be in the loop for any updates.

property size

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

with_arch(arch)[源代码]
c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

copy()[源代码]
class angr.sim_type.NamedTypeMixin(*args, name=None, **kwargs)[源代码]

基类:object

SimType classes with this mixin in the class hierarchy allows setting custom class names. A typical use case is to represent same or similar type classes with different qualified names, such as "std::basic_string" vs "std::__cxx11::basic_string". In such cases, .name stores the qualified name, and .unqualified_name() returns the unqualified name of the type.

参数:

name (str | None)

__init__(*args, name=None, **kwargs)[源代码]
参数:

name (str | None)

property name: str
unqualified_name(lang='c++')[源代码]
返回类型:

str

参数:

lang (str)

class angr.sim_type.SimTypeBottom(label=None)[源代码]

基类:SimType

SimTypeBottom basically represents a type error.

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

copy()[源代码]
class angr.sim_type.SimTypeTop(size=None, label=None)[源代码]

基类:SimType

SimTypeTop represents any type (mostly used with a pointer for void*).

参数:

size (int | None)

__init__(size=None, label=None)[源代码]
参数:
  • label -- the type label.

  • size (int | None)

copy()[源代码]
class angr.sim_type.SimTypeReg(size, label=None)[源代码]

基类:SimType

SimTypeReg is the base type for all types that are register-sized.

参数:

size (int | None)

__init__(size, label=None)[源代码]
参数:
  • label -- the type label.

  • size (int | None) -- the size of the type (e.g. 32bit, 8bit, etc.).

store(state, addr, value)[源代码]
参数:

value (StoreType)

copy()[源代码]
class angr.sim_type.SimTypeNum(size, signed=True, label=None)[源代码]

基类:SimType

SimTypeNum is a numeric type of arbitrary length

参数:

size (int)

__init__(size, signed=True, label=None)[源代码]
参数:
  • size (int) -- The size of the integer, in bits

  • signed -- Whether the integer is signed or not

  • label -- A label for the type

property size: int

The size of the type in bits, or None if no size is computable.

extract(state, addr, concrete=False)[源代码]
store(state, addr, value)[源代码]
参数:

value (StoreType)

copy()[源代码]
class angr.sim_type.SimTypeInt(signed=True, label=None)[源代码]

基类:SimTypeReg

SimTypeInt is a type that specifies a signed or unsigned C integer.

__init__(signed=True, label=None)[源代码]
参数:
  • signed -- True if signed, False if unsigned

  • label -- The type label

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

property size

The size of the type in bits, or None if no size is computable.

extract(state, addr, concrete=False)[源代码]
copy()[源代码]
class angr.sim_type.SimTypeShort(signed=True, label=None)[源代码]

基类:SimTypeInt

class angr.sim_type.SimTypeLong(signed=True, label=None)[源代码]

基类:SimTypeInt

class angr.sim_type.SimTypeLongLong(signed=True, label=None)[源代码]

基类:SimTypeInt

class angr.sim_type.SimTypeFixedSizeInt(signed=True, label=None)[源代码]

基类:SimTypeInt

The base class for all fixed-size (i.e., the size stays the same on all platforms) integer types. Do not instantiate this class directly.

c_repr(name=None, full=0, memo=None, indent=0)[源代码]
property size: int

The size of the type in bits, or None if no size is computable.

class angr.sim_type.SimTypeInt128(signed=True, label=None)[源代码]

基类:SimTypeFixedSizeInt

class angr.sim_type.SimTypeInt256(signed=True, label=None)[源代码]

基类:SimTypeFixedSizeInt

class angr.sim_type.SimTypeInt512(signed=True, label=None)[源代码]

基类:SimTypeFixedSizeInt

class angr.sim_type.SimTypeChar(signed=True, label=None)[源代码]

基类:SimTypeReg

SimTypeChar is a type that specifies a character; this could be represented by a byte, but this is meant to be interpreted as a character.

__init__(signed=True, label=None)[源代码]
参数:

label -- the type label.

store(state, addr, value)[源代码]
参数:

value (StoreType)

extract(state, addr, concrete=False)[源代码]
返回类型:

BV | bytes

参数:

concrete (bool)

copy()[源代码]
class angr.sim_type.SimTypeWideChar(signed=True, label=None)[源代码]

基类:SimTypeReg

SimTypeWideChar is a type that specifies a wide character (a UTF-16 character).

__init__(signed=True, label=None)[源代码]
参数:

label -- the type label.

store(state, addr, value)[源代码]
参数:

value (StoreType)

extract(state, addr, concrete=False)[源代码]
返回类型:

Any

copy()[源代码]
class angr.sim_type.SimTypeBool(signed=True, label=None)[源代码]

基类:SimTypeReg

__init__(signed=True, label=None)[源代码]
参数:

label -- the type label.

store(state, addr, value)[源代码]
参数:

value (StoreType | bool)

extract(state, addr, concrete=False)[源代码]
copy()[源代码]
class angr.sim_type.SimTypeFd(label=None)[源代码]

基类:SimTypeReg

SimTypeFd is a type that specifies a file descriptor.

__init__(label=None)[源代码]
参数:

label -- the type label

property size

The size of the type in bits, or None if no size is computable.

copy()[源代码]
extract(state, addr, concrete=False)[源代码]
class angr.sim_type.SimTypePointer(pts_to, label=None, offset=0)[源代码]

基类:SimTypeReg

SimTypePointer is a type that specifies a pointer to some other type.

__init__(pts_to, label=None, offset=0)[源代码]
参数:
  • label -- The type label.

  • pts_to -- The type to which this pointer points.

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

make(pts_to)[源代码]
property size

The size of the type in bits, or None if no size is computable.

copy()[源代码]
extract(state, addr, concrete=False)[源代码]
class angr.sim_type.SimTypeReference(refs, label=None)[源代码]

基类:SimTypeReg

SimTypeReference is a type that specifies a reference to some other type.

__init__(refs, label=None)[源代码]
参数:
  • label -- the type label.

  • size -- the size of the type (e.g. 32bit, 8bit, etc.).

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

make(refs)[源代码]
property size

The size of the type in bits, or None if no size is computable.

copy()[源代码]
extract(state, addr, concrete=False)[源代码]
class angr.sim_type.SimTypeArray(elem_type, length=None, label=None)[源代码]

基类:SimType

SimTypeArray is a type that specifies a series of data laid out in sequence.

__init__(elem_type, length=None, label=None)[源代码]
参数:
  • label -- The type label.

  • elem_type -- The type of each element in the array.

  • length -- An expression of the length of the array, if known.

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

property size

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

copy()[源代码]
extract(state, addr, concrete=False)[源代码]
store(state, addr, value)[源代码]
参数:

value (list[StoreType])

angr.sim_type.SimTypeFixedSizeArray

SimTypeArray 的别名

class angr.sim_type.SimTypeString(length=None, label=None, name=None)[源代码]

基类:NamedTypeMixin, SimType

SimTypeString is a type that represents a C-style string, i.e. a NUL-terminated array of bytes.

参数:
  • length (int | None)

  • name (str | None)

__init__(length=None, label=None, name=None)[源代码]
参数:
  • label -- The type label.

  • length (Optional[int]) -- An expression of the length of the string, if known.

  • name (str | None)

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

extract(state, addr, concrete=False)[源代码]
参数:

state (SimState)

property size

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

copy()[源代码]
class angr.sim_type.SimTypeWString(length=None, label=None, name=None)[源代码]

基类:NamedTypeMixin, SimType

A wide-character null-terminated string, where each character is 2 bytes.

参数:
  • length (int | None)

  • name (str | None)

__init__(length=None, label=None, name=None)[源代码]
参数:
  • label -- the type label.

  • length (int | None)

  • name (str | None)

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

extract(state, addr, concrete=False)[源代码]
store(state, addr, value)[源代码]
property size

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

copy()[源代码]
class angr.sim_type.SimTypeFunction(args, returnty, label=None, arg_names=None, variadic=False)[源代码]

基类:SimType

SimTypeFunction is a type that specifies an actual function (i.e. not a pointer) with certain types of arguments and a certain return value.

参数:
  • args (Iterable[SimType])

  • returnty (SimType | None)

  • arg_names (Iterable[str] | None)

base: bool = False
__init__(args, returnty, label=None, arg_names=None, variadic=False)[源代码]
参数:
  • label -- The type label

  • args (Iterable[SimType]) -- A tuple of types representing the arguments to the function

  • returnty (SimType | None) -- The return type of the function, or none for void

  • variadic -- Whether the function accepts varargs

  • arg_names (Iterable[str] | None)

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

property size

The size of the type in bits, or None if no size is computable.

copy()[源代码]
class angr.sim_type.SimTypeCppFunction(args, returnty, label=None, arg_names=None, ctor=False, dtor=False)[源代码]

基类:SimTypeFunction

SimTypeCppFunction is a type that specifies an actual C++-style function with information about arguments, return value, and more C++-specific properties.

变量:
  • ctor -- Whether the function is a constructor or not.

  • dtor -- Whether the function is a destructor or not.

参数:
__init__(args, returnty, label=None, arg_names=None, ctor=False, dtor=False)[源代码]
参数:
  • label -- The type label

  • args -- A tuple of types representing the arguments to the function

  • returnty -- The return type of the function, or none for void

  • variadic -- Whether the function accepts varargs

  • arg_names (Iterable[str] | None)

  • ctor (bool)

  • dtor (bool)

copy()[源代码]
class angr.sim_type.SimTypeLength(signed=False, addr=None, length=None, label=None)[源代码]

基类:SimTypeLong

SimTypeLength is a type that specifies the length of some buffer in memory.

...I'm not really sure what the original design of this class was going for

__init__(signed=False, addr=None, length=None, label=None)[源代码]
参数:
  • signed -- Whether the value is signed or not

  • label -- The type label.

  • addr -- The memory address (expression).

  • length -- The length (expression).

property size

The size of the type in bits, or None if no size is computable.

copy()[源代码]
class angr.sim_type.SimTypeFloat(size=32)[源代码]

基类:SimTypeReg

An IEEE754 single-precision floating point number

__init__(size=32)[源代码]
参数:
  • label -- the type label.

  • size -- the size of the type (e.g. 32bit, 8bit, etc.).

sort = FLOAT
signed = True
property size: int

The size of the type in bits, or None if no size is computable.

extract(state, addr, concrete=False)[源代码]
store(state, addr, value)[源代码]
参数:

value (StoreType | claripy.ast.FP)

copy()[源代码]
class angr.sim_type.SimTypeDouble(align_double=True)[源代码]

基类:SimTypeFloat

An IEEE754 double-precision floating point number

__init__(align_double=True)[源代码]
参数:
  • label -- the type label.

  • size -- the size of the type (e.g. 32bit, 8bit, etc.).

sort = DOUBLE
property size: int

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

copy()[源代码]
class angr.sim_type.SimStruct(fields, name=None, pack=False, align=None, anonymous=False)[源代码]

基类:NamedTypeMixin, SimType

参数:
__init__(fields, name=None, pack=False, align=None, anonymous=False)[源代码]
参数:
property packed
property offsets: dict[str, int]
extract(state, addr, concrete=False)[源代码]
返回类型:

SimStructValue

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

property size

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

store(state, addr, value)[源代码]
参数:

value (StoreType)

copy()[源代码]
class angr.sim_type.SimStructValue(struct, values=None)[源代码]

基类:object

A SimStruct type paired with some real values

__init__(struct, values=None)[源代码]
参数:
  • struct -- A SimStruct instance describing the type of this struct

  • values -- A mapping from struct fields to values

property struct
copy()[源代码]
class angr.sim_type.SimUnion(members, name=None, label=None)[源代码]

基类:NamedTypeMixin, SimType

fields = ('members', 'name')
__init__(members, name=None, label=None)[源代码]
参数:
  • members -- The members of the union, as a mapping name -> type

  • name -- The name of the union

property size

The size of the type in bits, or None if no size is computable.

property alignment

The alignment of the type in bytes.

extract(state, addr, concrete=False)[源代码]
c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
参数:

name_parens (bool)

copy()[源代码]
class angr.sim_type.SimUnionValue(union, values=None)[源代码]

基类:object

A SimStruct type paired with some real values

__init__(union, values=None)[源代码]
参数:
  • union -- A SimUnion instance describing the type of this union

  • values -- A mapping from union members to values

copy()[源代码]
class angr.sim_type.SimCppClass(members=None, function_members=None, vtable_ptrs=None, name=None, pack=False, align=None)[源代码]

基类:SimStruct

参数:
__init__(members=None, function_members=None, vtable_ptrs=None, name=None, pack=False, align=None)[源代码]
参数:
property members
extract(state, addr, concrete=False)[源代码]
返回类型:

SimCppClassValue

store(state, addr, value)[源代码]
参数:

value (StoreType)

copy()[源代码]
class angr.sim_type.SimCppClassValue(class_type, values)[源代码]

基类:SimStructValue

A SimCppClass type paired with some real values

参数:

class_type (SimCppClass)

__init__(class_type, values)[源代码]
参数:
  • struct -- A SimStruct instance describing the type of this struct

  • values -- A mapping from struct fields to values

  • class_type (SimCppClass)

copy()[源代码]
class angr.sim_type.SimTypeNumOffset(size, signed=True, label=None, offset=0)[源代码]

基类:SimTypeNum

like SimTypeNum, but supports an offset of 1 to 7 to a byte aligned address to allow structs with bitfields

__init__(size, signed=True, label=None, offset=0)[源代码]
参数:
  • size -- The size of the integer, in bits

  • signed -- Whether the integer is signed or not

  • label -- A label for the type

extract(state, addr, concrete=False)[源代码]
参数:

state (SimState)

store(state, addr, value)[源代码]
copy()[源代码]
class angr.sim_type.SimTypeRef(name, original_type)[源代码]

基类:SimType

SimTypeRef is a to-be-resolved reference to another SimType.

SimTypeRef is not SimTypeReference.

参数:

original_type (type[SimStruct])

__init__(name, original_type)[源代码]
参数:
property name: str | None
set_size(v)[源代码]
参数:

v (int)

c_repr(name=None, full=0, memo=None, indent=0, name_parens=True)[源代码]
返回类型:

str

参数:

name_parens (bool)

angr.sim_type.register_types(types)[源代码]

Pass in some types and they will be registered to the global type store.

The argument may be either a mapping from name to SimType, or a plain SimType. The plain SimType must be either a struct or union type with a name present.

>>> register_types(parse_types("typedef int x; typedef float y;"))
>>> register_types(parse_type("struct abcd { int ab; float cd; }"))
angr.sim_type.do_preprocess(defn, include_path=())[源代码]

Run a string through the C preprocessor that ships with pycparser but is weirdly inaccessible?

angr.sim_type.parse_signature(defn, preprocess=True, predefined_types=None, arch=None)[源代码]

Parse a single function prototype and return its type

angr.sim_type.parse_defns(defn, preprocess=True, predefined_types=None, arch=None)[源代码]

Parse a series of C definitions, returns a mapping from variable name to variable type object

angr.sim_type.parse_types(defn, preprocess=True, predefined_types=None, arch=None)[源代码]

Parse a series of C definitions, returns a mapping from type name to type object

angr.sim_type.parse_file(defn, preprocess=True, predefined_types=None, arch=None)[源代码]

Parse a series of C definitions, returns a tuple of two type mappings, one for variable definitions and one for type definitions.

参数:

predefined_types (dict[Any, SimType] | None)

angr.sim_type.type_parser_singleton()[源代码]
返回类型:

CParser

angr.sim_type.parse_type(defn, preprocess=True, predefined_types=None, arch=None)[源代码]

Parse a simple type expression into a SimType

>>> parse_type('int *')
angr.sim_type.parse_type_with_name(defn, preprocess=True, predefined_types=None, arch=None)[源代码]

Parse a simple type expression into a SimType, returning a tuple of the type object and any associated name that might be found in the place a name would go in a type declaration.

>>> parse_type_with_name('int *foo')
参数:

predefined_types (dict[Any, SimType] | None)

angr.sim_type.normalize_cpp_function_name(name)[源代码]
返回类型:

str

参数:

name (str)

angr.sim_type.parse_cpp_file(cpp_decl, with_param_names=False)[源代码]
参数:

with_param_names (bool)

angr.sim_type.dereference_simtype(t, type_collections, memo=None)[源代码]
返回类型:

SimType

参数:
class angr.callable.Callable(project, addr, prototype=None, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None, add_options=None, remove_options=None)[源代码]

基类:object

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

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

Otherwise, you can get the resulting simulation manager at callable.result_path_group.

__init__(project, addr, prototype=None, concrete_only=False, perform_merge=True, base_state=None, toc=None, cc=None, add_options=None, remove_options=None)[源代码]
参数:
  • project -- The project to operate on

  • addr -- The address of the function to use

The following parameters are optional:

参数:
  • prototype -- The signature of the calls you would like to make. This really shouldn't be optional.

  • concrete_only -- Throw an exception if the execution splits into multiple paths

  • perform_merge -- Merge all result states into one at the end (only relevant if concrete_only=False)

  • base_state -- The state from which to do these runs

  • toc -- The address of the table of contents for ppc64

  • cc -- The SimCC to use for a calling convention

set_base_state(state)[源代码]

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

perform_call(*args, prototype=None)[源代码]
call_c(c_args)[源代码]

Call this Callable with a string of C-style arguments.

参数:

c_args (str) -- C-style arguments.

返回:

The return value from the call.

返回类型:

claripy.Ast

Knowledge Base

Representing the artifacts of a project.

class angr.knowledge_base.KnowledgeBase(project, obj=None, name=None)[源代码]

基类:object

Represents a "model" of knowledge about an artifact.

Contains things like a CFG, data references, etc.

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

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

参数:

requested_plugin_cls (type[K])

返回类型:

K | None

request_knowledge(requested_plugin_cls)[源代码]
返回类型:

K

参数:

requested_plugin_cls (type[K])

class angr.knowledge_plugins.CFGManager(kb)[源代码]

基类:KnowledgeBasePlugin

This is the CFG manager, it manages CFGs

__init__(kb)[源代码]
new_model(prefix)[源代码]
copy()[源代码]
get_most_accurate()[源代码]
返回类型:

CFGModel | None

返回:

The most accurate CFG present in the CFGManager, or None if it does not hold any.

class angr.knowledge_plugins.CallsitePrototypes(kb)[源代码]

基类:KnowledgeBasePlugin

CallsitePrototypes manages callee prototypes at call sites.

__init__(kb)[源代码]
set_prototype(callsite_block_addr, cc, prototype, manual=False)[源代码]
返回类型:

None

参数:
get_cc(callsite_block_addr)[源代码]
返回类型:

SimCC | None

参数:

callsite_block_addr (int)

get_prototype(callsite_block_addr)[源代码]
返回类型:

SimTypeFunction | None

参数:

callsite_block_addr (int)

get_prototype_type(callsite_block_addr)[源代码]
返回类型:

bool | None

参数:

callsite_block_addr (int)

has_prototype(callsite_block_addr)[源代码]
返回类型:

bool

参数:

callsite_block_addr (int)

copy()[源代码]
class angr.knowledge_plugins.Comments(kb)[源代码]

基类:KnowledgeBasePlugin, dict

Tracks comments via a Dict of Address -> Text

参数:

kb (KnowledgeBase)

copy() a shallow copy of D[源代码]
class angr.knowledge_plugins.CustomStrings(kb)[源代码]

基类:KnowledgeBasePlugin

Store new strings that are recovered during various analysis. Each string has a unique ID associated.

__init__(kb)[源代码]
allocate(s)[源代码]
返回类型:

int

参数:

s (bytes)

copy()[源代码]
class angr.knowledge_plugins.Data(kb)[源代码]

基类:KnowledgeBasePlugin

The knowledge what purpose this plugin serves has been lost to the passing of time but the linter does not care for these failures of mere mortals and demands a docstring anyway. The pact has been made, and no violations of the rules will be tolerated, even if the spirit does not match the letter. Making the plugin smaller has only increased the weight of the failure, and thus this file has drawn its ire.

The only thing left to do is to attempt to find meaning in the meaninglessness, as the only act of rebellion against the uncaring forces that bind us. For is this not what being human is all about?

参数:

kb (KnowledgeBase)

copy()[源代码]
class angr.knowledge_plugins.DebugVariableManager(kb)[源代码]

基类:KnowledgeBasePlugin

Structure to manage and access variables with different visibility scopes.

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

from_name_and_pc(var_name, pc_addr)[源代码]

Get a variable from its string in the scope of pc.

返回类型:

Variable

参数:
  • var_name (str)

  • pc_addr (int)

from_name(var_name)[源代码]

Get the variable container for all variables named var_name

参数:

var_name (str) -- name for a variable

返回类型:

DebugVariableContainer

add_variable(cle_var, low_pc, high_pc)[源代码]

Add/load a variable

参数:
  • cle_variable -- The variable to add

  • low_pc (int) -- Start of the visibility scope of the variable as program counter address (rebased)

  • high_pc (int) -- End of the visibility scope of the variable as program counter address (rebased)

  • cle_var (Variable)

add_variable_list(vlist, low_pc, high_pc)[源代码]

Add all variables in a list with the same visibility range

参数:
  • vlist (list[Variable]) -- A list of cle variables to add

  • low_pc (int) -- Start of the visibility scope as program counter address (rebased)

  • high_pc (int) -- End of the visibility scope as program counter address (rebased)

load_from_dwarf(elf_object=None, cu=None)[源代码]

Automatically load all variables (global/local) from the DWARF debugging info

参数:
  • elf_object (Optional[ELF]) -- Optional, when only one elf object should be considered (e.g. p.loader.main_object)

  • cu (Optional[CompilationUnit]) -- Optional, when only one compilation unit should be considered

class angr.knowledge_plugins.Function(function_manager, addr, name=None, syscall=None, is_simprocedure=None, binary_name=None, is_plt=None, returning=None, alignment=False)[源代码]

基类:Serializable

A representation of a function and various information about it.

参数:
  • is_simprocedure (bool | None)

  • is_plt (bool | None)

__init__(function_manager, addr, name=None, syscall=None, is_simprocedure=None, binary_name=None, is_plt=None, returning=None, alignment=False)[源代码]

Function constructor. If the optional parameters are not provided, they will be automatically determined upon the creation of a Function object.

参数:
  • addr -- The address of the function.

  • is_simprocedure (bool | None)

  • is_plt (bool | None)

The following parameters are optional.

参数:
  • name (str) -- The name of the function.

  • syscall (bool) -- Whether this function is a syscall or not.

  • is_simprocedure (bool) -- Whether this function is a SimProcedure or not.

  • binary_name (str) -- Name of the binary where this function is.

  • is_plt (bool) -- If this function is a PLT entry.

  • returning (bool) -- If this function returns.

  • alignment (bool) -- If this function acts as an alignment filler. Such functions usually only contain nops.

transition_graph
normalized
addr
startpoint
is_alignment
bp_on_stack
retaddr_on_stack
sp_delta
prototype: SimTypeFunction | None
prototype_libname: str | None
is_prototype_guessed: bool
prepared_registers
prepared_stack_variables
registers_read_afterwards
info
tags
ran_cca
is_syscall
is_simprocedure
is_plt
is_default_name
previous_names
from_signature
binary_name
calling_convention: SimCC | None
property alignment
property name
property project
property returning
property blocks

An iterator of all local blocks in the current function.

返回:

angr.lifter.Block instances.

property cyclomatic_complexity

The cyclomatic complexity of the function.

Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code. It is computed using the formula: M = E - N + 2P, where E = the number of edges in the graph, N = the number of nodes in the graph, P = the number of connected components.

The cyclomatic complexity value is lazily computed and cached for future use. Initially this value is None until it is computed for the first time

返回:

The cyclomatic complexity of the function.

返回类型:

int

property xrefs

An iterator of all xrefs of the current function.

返回:

angr.knowledge_plugins.xrefs.xref.XRef instances.

property block_addrs

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

返回:

block addresses.

property block_addrs_set

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

返回:

A set of block addresses.

返回类型:

set

get_block(addr, size=None, byte_string=None)[源代码]

Getting a block out of the current function.

参数:
  • addr (int) -- The address of the block.

  • size (int) -- The size of the block. This is optional. If not provided, angr will load

  • byte_string (Optional[bytes])

返回:

get_block_size(addr)[源代码]
返回类型:

int | None

参数:

addr (int)

property nodes: Iterable[CodeNode]
get_node(addr)[源代码]
返回类型:

BlockNode | None

property has_unresolved_jumps
property has_unresolved_calls
property operations

All of the operations that are done by this functions.

property code_constants

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

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]
参数:

cmsg

Return Function:

The function instantiated out of the cmsg data.

string_references(minimum_length=2)[源代码]

All of the constant string references used by this function.

参数:

minimum_length -- The minimum length of strings to find (default is 1)

返回:

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

property local_runtime_values

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

返回:

a set of constants

property num_arguments
property endpoints
property endpoints_with_type
property ret_sites
property jumpout_sites
property retout_sites
property callout_sites
property size
property binary

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

property offset: int

the function's binary offset (i.e., non-rebased address)

Type:

return

property symbol: None | Symbol

the function's Symbol, if any

Type:

return

property pseudocode: str

the function's pseudocode

Type:

return

add_jumpout_site(node)[源代码]

Add a custom jumpout site.

参数:

node (CodeNode) -- The address of the basic block that control flow leaves during this transition.

返回:

None

add_retout_site(node)[源代码]

Add a custom retout site.

Retout (returning to outside of the function) sites are very rare. It mostly occurs during CFG recovery when we incorrectly identify the beginning of a function in the first iteration, and then correctly identify that function later in the same iteration (function alignments can lead to this bizarre case). We will mark all edges going out of the header of that function as a outside edge, because all successors now belong to the incorrectly-identified function. This identification error will be fixed in the second iteration of CFG recovery. However, we still want to keep track of jumpouts/retouts during the first iteration so other logic in CFG recovery still work.

参数:

node (CodeNode) -- The address of the basic block that control flow leaves the current function after a call.

返回:

None

mark_nonreturning_calls_endpoints()[源代码]

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

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

返回:

None

get_call_sites()[源代码]

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

返回类型:

Iterable[int]

返回:

A view of the addresses of the blocks that end in calls.

get_call_target(callsite_addr)[源代码]

Get the target of a call.

参数:

callsite_addr -- The address of a basic block that ends in a call.

返回:

The target of said call, or None if callsite_addr is not a callsite.

get_call_return(callsite_addr)[源代码]

Get the hypothetical return address of a call.

参数:

callsite_addr -- The address of the basic block that ends in a call.

返回:

The likely return target of said call, or None if callsite_addr is not a callsite.

property graph

Get a local transition graph. A local transition graph is a transition graph that only contains nodes that belong to the current function. All edges, except for the edges going out from the current function or coming from outside the current function, are included.

The generated graph is cached in self._local_transition_graph.

返回:

A local transition graph.

返回类型:

networkx.DiGraph

graph_ex(exception_edges=True)[源代码]

Get a local transition graph with a custom configuration. A local transition graph is a transition graph that only contains nodes that belong to the current function. This method allows user to exclude certain types of edges together with the nodes that are only reachable through such edges, such as exception edges.

The generated graph is not cached.

参数:

exception_edges (bool) -- Should exception edges and the nodes that are only reachable through exception edges be kept.

返回:

A local transition graph with a special configuration.

返回类型:

networkx.DiGraph

transition_graph_ex(exception_edges=True)[源代码]

Get a transition graph with a custom configuration. This method allows user to exclude certain types of edges together with the nodes that are only reachable through such edges, such as exception edges.

The generated graph is not cached.

参数:

exception_edges (bool) -- Should exception edges and the nodes that are only reachable through exception edges be kept.

返回:

A local transition graph with a special configuration.

返回类型:

networkx.DiGraph

subgraph(ins_addrs)[源代码]

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

参数:

ins_addrs (iterable) -- A collection of instruction addresses that should be included in the subgraph.

Return networkx.DiGraph:

A subgraph.

instruction_size(insn_addr)[源代码]

Get the size of the instruction specified by insn_addr.

参数:

insn_addr (int) -- Address of the instruction

Return int:

Size of the instruction in bytes, or None if the instruction is not found.

addr_to_instruction_addr(addr)[源代码]

Obtain the address of the instruction that covers @addr.

参数:

addr (int) -- An address.

返回:

Address of the instruction that covers @addr, or None if this addr is not covered by any instruction of this function.

返回类型:

int or None

dbg_print()[源代码]

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

dbg_draw(filename)[源代码]

Draw the graph and save it to a PNG file.

property arguments
property has_return
property callable
normalize()[源代码]

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

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

返回:

None

find_declaration(ignore_binary_name=False, binary_name_hint=None)[源代码]

Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, and update self.calling_convention with the declaration.

参数:
  • ignore_binary_name (bool) -- Do not rely on the executable or library where the function belongs to determine its source library. This is useful when working on statically linked binaries (because all functions will belong to the main executable). We will search for all libraries in angr to find the first declaration match.

  • binary_name_hint (Optional[str]) -- Substring of the library name where this function might be originally coming from. Useful for FLIRT-identified functions in statically linked binaries.

返回类型:

bool

返回:

True if a declaration is found and self.prototype and self.calling_convention are updated. False if we fail to find a matching function declaration, in which case self.prototype or self.calling_convention will be kept untouched.

property demangled_name
get_unambiguous_name(display_name=None)[源代码]

Get a disambiguated function name.

参数:

display_name (Optional[str]) -- Name to display, otherwise the function name.

返回类型:

str

返回:

The function name in the form: ::<name> when the function binary is the main object. ::<obj>::<name> when the function binary is not the main object. ::<addr>::<name> when the function binary is an unnamed non-main object, or when multiple functions with

the same name are defined in the function binary.

apply_definition(definition, calling_convention=None)[源代码]
返回类型:

None

参数:
functions_reachable()[源代码]
返回类型:

set[Function]

返回:

The set of all functions that can be reached from the function represented by self.

copy()[源代码]
pp(**kwargs)[源代码]

Pretty-print the function disassembly.

class angr.knowledge_plugins.FunctionManager(kb)[源代码]

基类:KnowledgeBasePlugin, Mapping

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

__init__(kb)[源代码]
copy()[源代码]
clear()[源代码]
get_by_addr(addr)[源代码]
返回类型:

Function

get_by_name(name, check_previous_names=False)[源代码]
返回类型:

Generator[Function]

参数:
  • name (str)

  • check_previous_names (bool)

contains_addr(addr)[源代码]

Decide if an address is handled by the function manager.

Note: this function is non-conformant with python programming idioms, but its needed for performance reasons.

参数:

addr (int) -- Address of the function.

ceiling_func(addr)[源代码]

Return the function who has the least address that is greater than or equal to addr.

参数:

addr (int) -- The address to query.

返回:

A Function instance, or None if there is no other function after addr.

返回类型:

Function or None

floor_func(addr)[源代码]

Return the function who has the greatest address that is less than or equal to addr.

参数:

addr (int) -- The address to query.

返回:

A Function instance, or None if there is no other function before addr.

返回类型:

Function or None

query(query, check_previous_names=False)[源代码]

Query for a function using selectors to disambiguate. Supported variations: :rtype: Function | None

::<name> Function <name> in the main object ::<addr>::<name> Function <name> at <addr> ::<obj>::<name> Function <name> in <obj>

参数:
  • query (str)

  • check_previous_names (bool)

返回类型:

Function | None

function(addr=None, name=None, check_previous_names=False, create=False, syscall=False, plt=None)[源代码]

Get a function object from the function manager.

Pass either addr or name with the appropriate values.

参数:
  • addr (int) -- Address of the function.

  • name (str) -- Name of the function.

  • create (bool) -- Whether to create the function or not if the function does not exist.

  • syscall (bool) -- True to create the function as a syscall, False otherwise.

  • plt (bool or None) -- True to find the PLT stub, False to find a non-PLT stub, None to disable this restriction.

返回:

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

返回类型:

Function or None

dbg_draw(prefix='dbg_function_')[源代码]
rebuild_callgraph()[源代码]
class angr.knowledge_plugins.IndirectJumps(kb)[源代码]

基类:KnowledgeBasePlugin, dict

This plugin tracks the targets of indirect jumps

__init__(kb)[源代码]
copy() a shallow copy of D[源代码]
update_resolved_addrs(indirect_address, resolved_addresses)[源代码]
参数:
  • indirect_address (int)

  • resolved_addresses (list[int])

class angr.knowledge_plugins.KeyDefinitionManager(kb)[源代码]

基类:KnowledgeBasePlugin

KeyDefinitionManager manages and caches reaching definition models for each function.

For each function, by default we cache the entire reaching definitions model with observed results at the following locations: - Before each call instruction: ('insn', address of the call instruction, OP_BEFORE) - After returning from each call: ('node', address of the block that ends with a call, OP_AFTER)

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

has_model(func_addr)[源代码]
参数:

func_addr (int)

get_model(func_addr)[源代码]
参数:

func_addr (int)

copy()[源代码]
返回类型:

KeyDefinitionManager

class angr.knowledge_plugins.KnowledgeBasePlugin(kb)[源代码]

基类:object

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

copy()[源代码]
static register_default(name, cls)[源代码]
class angr.knowledge_plugins.Labels(kb)[源代码]

基类:KnowledgeBasePlugin

__init__(kb)[源代码]
items()[源代码]
get(addr)[源代码]

Get a label as string for a given address Same as .labels[x]

lookup(name)[源代码]

Returns an address to a given label To show all available labels, iterate over .labels or list(b.kb.labels)

copy()[源代码]
get_unique_label(label)[源代码]

Get a unique label name from the given label name.

参数:

label (str) -- The desired label name.

返回:

A unique label name.

class angr.knowledge_plugins.Obfuscations(kb)[源代码]

基类:KnowledgeBasePlugin

Store discovered information and artifacts about (string) obfuscation techniques in the project.

__init__(kb)[源代码]
copy()[源代码]
class angr.knowledge_plugins.PatchManager(kb)[源代码]

基类:KnowledgeBasePlugin

A placeholder-style implementation for a binary patch manager. This class should be significantly changed in the future when all data about loaded binary objects are loaded into angr knowledge base from CLE. As of now, it only stores byte-level replacements.

Patches should not overlap, but it's user's responsibility to check for and avoid overlapping patches.

__init__(kb)[源代码]
add_patch(addr, new_bytes, comment=None)[源代码]
参数:

comment (str | None)

add_patch_obj(patch)[源代码]
参数:

patch (Patch)

remove_patch(addr)[源代码]
patch_addrs()[源代码]
get_patch(addr)[源代码]

Get patch at the given address.

参数:

addr (int) -- The address of the patch.

返回:

The patch if there is one starting at the address, or None if there isn't any.

返回类型:

Patch or None

get_all_patches(addr, size)[源代码]

Retrieve all patches that cover a region specified by [addr, addr+size).

参数:
  • addr (int) -- The address of the beginning of the region.

  • size (int) -- Size of the region.

返回:

A list of patches.

返回类型:

list

keys()[源代码]
items()[源代码]
values()[源代码]
copy()[源代码]
static overlap(a0, a1, b0, b1)[源代码]
apply_patches_to_binary(binary_bytes=None, patches=None)[源代码]
返回类型:

bytes

参数:
apply_patches_to_state(state)[源代码]
property patched_entry_state
class angr.knowledge_plugins.PropagationManager(kb)[源代码]

基类:KnowledgeBasePlugin

Manages the results of Propagator, including intermediate results for unfinished Propagation runs.

__init__(kb)[源代码]
exists(prop_key)[源代码]

Internal function to check if a func, specified as a CodeLocation exists in our known propagations

参数:

prop_key (tuple) -- A key of the propagation result.

返回类型:

bool

返回:

Whether such a key exists or not.

update(prop_key, model)[源代码]

Add the replacements to known propagations

参数:
  • prop_key (tuple) -- A key of the propagation result.

  • model (PropagationModel) -- The propagation result to store

返回类型:

None

get(prop_key, default=None)[源代码]

Gets the replacements for a specified function location. If the replacement does not exist in the known propagations, it returns None.

参数:
  • prop_key -- A key of the propagation result.

  • default -- The default value to return if the prop_key does not exist in the cache.

返回类型:

PropagationModel

返回:

Dict or None

copy()[源代码]
discard_by_prefix(prefix)[源代码]
参数:

prefix (str)

class angr.knowledge_plugins.StructuredCodeManager(kb)[源代码]

基类:KnowledgeBasePlugin

A knowledge base plugin to store structured code generator results.

__init__(kb)[源代码]
discard(key)[源代码]
available_flavors(item)[源代码]
copy()[源代码]
class angr.knowledge_plugins.TypesStore(kb)[源代码]

基类:KnowledgeBasePlugin, UserDict

A kb plugin that stores a mapping from name to TypeRef. It will return types from angr.sim_type.ALL_TYPES as a default.

__init__(kb)[源代码]
copy()[源代码]
iter_own()[源代码]

Iterate over all the names which are stored in this object - i.e. values() without ALL_TYPES

rename(old, new)[源代码]
unique_type_name()[源代码]
返回类型:

str

class angr.knowledge_plugins.VariableManager(kb)[源代码]

基类:KnowledgeBasePlugin

Manage variables.

__init__(kb)[源代码]
has_function_manager(key)[源代码]
返回类型:

bool

参数:

key (int)

get_function_manager(func_addr)[源代码]
返回类型:

VariableManagerInternal

initialize_variable_names()[源代码]
返回类型:

None

get_variable_accesses(variable, same_name=False)[源代码]

Get a list of all references to the given variable.

参数:
  • variable (SimVariable) -- The variable.

  • same_name (bool) -- Whether to include all variables with the same variable name, or just based on the variable identifier.

返回类型:

list[VariableAccess]

返回:

All references to the variable.

copy()[源代码]
static convert_variable_list(vlist, manager)[源代码]
参数:
load_from_dwarf(cu_list=None)[源代码]
参数:

cu_list (list[CompilationUnit] | None)

class angr.knowledge_plugins.XRefManager(kb)[源代码]

基类:KnowledgeBasePlugin, Serializable

__init__(kb)[源代码]
copy()[源代码]
add_xref(xref)[源代码]
add_xrefs(xrefs)[源代码]
get_xrefs_by_ins_addr(ins_addr)[源代码]
get_xrefs_by_dst(dst)[源代码]
get_xrefs_by_dst_region(start, end)[源代码]

Get a set of XRef objects that point to a given address region bounded by start and end. Will only return absolute xrefs, not relative ones (like SP offsets)

get_xrefs_by_ins_addr_region(start, end)[源代码]

Get a set of XRef objects that originate at a given address region bounded by start and end. Useful for finding references from a basic block or function.

返回类型:

set[XRef]

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg_model=None, kb=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.knowledge_plugins.patches.Patch(addr, new_bytes, comment=None)[源代码]

基类:object

参数:

comment (str | None)

__init__(addr, new_bytes, comment=None)[源代码]
参数:

comment (str | None)

class angr.knowledge_plugins.patches.PatchManager(kb)[源代码]

基类:KnowledgeBasePlugin

A placeholder-style implementation for a binary patch manager. This class should be significantly changed in the future when all data about loaded binary objects are loaded into angr knowledge base from CLE. As of now, it only stores byte-level replacements.

Patches should not overlap, but it's user's responsibility to check for and avoid overlapping patches.

__init__(kb)[源代码]
add_patch(addr, new_bytes, comment=None)[源代码]
参数:

comment (str | None)

add_patch_obj(patch)[源代码]
参数:

patch (Patch)

remove_patch(addr)[源代码]
patch_addrs()[源代码]
get_patch(addr)[源代码]

Get patch at the given address.

参数:

addr (int) -- The address of the patch.

返回:

The patch if there is one starting at the address, or None if there isn't any.

返回类型:

Patch or None

get_all_patches(addr, size)[源代码]

Retrieve all patches that cover a region specified by [addr, addr+size).

参数:
  • addr (int) -- The address of the beginning of the region.

  • size (int) -- Size of the region.

返回:

A list of patches.

返回类型:

list

keys()[源代码]
items()[源代码]
values()[源代码]
copy()[源代码]
static overlap(a0, a1, b0, b1)[源代码]
apply_patches_to_binary(binary_bytes=None, patches=None)[源代码]
返回类型:

bytes

参数:
apply_patches_to_state(state)[源代码]
property patched_entry_state
class angr.knowledge_plugins.plugin.KnowledgeBasePlugin(kb)[源代码]

基类:object

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

copy()[源代码]
static register_default(name, cls)[源代码]
class angr.knowledge_plugins.callsite_prototypes.CallsitePrototypes(kb)[源代码]

基类:KnowledgeBasePlugin

CallsitePrototypes manages callee prototypes at call sites.

__init__(kb)[源代码]
set_prototype(callsite_block_addr, cc, prototype, manual=False)[源代码]
返回类型:

None

参数:
get_cc(callsite_block_addr)[源代码]
返回类型:

SimCC | None

参数:

callsite_block_addr (int)

get_prototype(callsite_block_addr)[源代码]
返回类型:

SimTypeFunction | None

参数:

callsite_block_addr (int)

get_prototype_type(callsite_block_addr)[源代码]
返回类型:

bool | None

参数:

callsite_block_addr (int)

has_prototype(callsite_block_addr)[源代码]
返回类型:

bool

参数:

callsite_block_addr (int)

copy()[源代码]
class angr.knowledge_plugins.cfg.CFGENode(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None, input_state=None, final_states=None, syscall_name=None, looping_times=0, depth=None, callstack_key=None, creation_failure_info=None)[源代码]

基类:CFGNode

The CFGNode that is used in CFGEmulated.

__init__(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None, input_state=None, final_states=None, syscall_name=None, looping_times=0, depth=None, callstack_key=None, creation_failure_info=None)[源代码]

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

input_state
looping_times
depth
creation_failure_info
final_states
return_target
syscall
property callstack_key
property creation_failed
downsize()[源代码]

Drop saved states.

copy()[源代码]
class angr.knowledge_plugins.cfg.CFGManager(kb)[源代码]

基类:KnowledgeBasePlugin

This is the CFG manager, it manages CFGs

__init__(kb)[源代码]
new_model(prefix)[源代码]
copy()[源代码]
get_most_accurate()[源代码]
返回类型:

CFGModel | None

返回:

The most accurate CFG present in the CFGManager, or None if it does not hold any.

class angr.knowledge_plugins.cfg.CFGModel(ident, cfg_manager=None, is_arm=False)[源代码]

基类:Serializable

This class describes a Control Flow Graph for a specific range of code.

__init__(ident, cfg_manager=None, is_arm=False)[源代码]
ident
is_arm
graph
jump_tables: dict[int, IndirectJump]
memory_data: dict[int, MemoryData]
insn_addr_to_memory_data: dict[int, MemoryData]
normalized
edges_to_repair
property project
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg_manager=None, loader=None)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

copy()[源代码]
add_node(block_id, node)[源代码]
返回类型:

None

参数:
remove_node(block_id, node)[源代码]

Remove the given CFGNode instance. Note that this method does not remove the node from the graph.

参数:
  • block_id (int) -- The Unique ID of the CFGNode.

  • node (CFGNode) -- The CFGNode instance to remove.

返回类型:

None

返回:

None

get_node(block_id)[源代码]

Get a single node from node key.

参数:

block_id (BlockID) -- Block ID of the node.

返回:

The CFGNode

返回类型:

CFGNode

get_any_node(addr, is_syscall=None, anyaddr=False, force_fastpath=False)[源代码]

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

参数:
  • addr (int) -- Address of the beginning of the basic block. Set anyaddr to True to support arbitrary address.

  • is_syscall (Optional[bool]) -- Whether you want to get the syscall node or any other node. This is due to the fact that syscall SimProcedures have the same address as the target it returns to. None means get either, True means get a syscall node, False means get something that isn't a syscall node.

  • anyaddr (bool) -- If anyaddr is True, then addr doesn't have to be the beginning address of a basic block. By default the entire graph.nodes() will be iterated, and the first node containing the specific address is returned, which can be slow.

  • force_fastpath (bool) -- If force_fastpath is True, it will only perform a dict lookup in the _nodes_by_addr dict.

返回类型:

CFGNode | None

返回:

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

get_all_nodes(addr, is_syscall=None, anyaddr=False)[源代码]

Get all CFGNodes whose address is the specified one.

参数:
  • addr (int) -- Address of the node

  • is_syscall (Optional[bool]) -- True returns the syscall node, False returns the normal CFGNode, None returns both

  • anyaddr (bool)

返回类型:

list[CFGNode]

返回:

all CFGNodes

get_all_nodes_intersecting_region(addr, size=1)[源代码]

Get all CFGNodes that intersect the given region.

参数:
  • addr (int) -- Minimum address of target region.

  • size (int) -- Size of region, in bytes.

返回类型:

set[CFGNode]

nodes()[源代码]

An iterator of all nodes in the graph.

返回:

The iterator.

返回类型:

iterator

get_predecessors(cfgnode, excluding_fakeret=True, jumpkind=None)[源代码]

Get predecessors of a node in the control flow graph.

参数:
  • cfgnode (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all predecessors that is connected to the node with a fakeret edge.

  • jumpkind (Optional[str]) -- Only return predecessors with the specified jumpkind. This argument will be ignored if set to None.

返回类型:

list[CFGNode]

返回:

A list of predecessors

get_successors(node, excluding_fakeret=True, jumpkind=None)[源代码]

Get successors of a node in the control flow graph.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all successors that is connected to the node with a fakeret edge.

  • jumpkind (str | None) -- Only return successors with the specified jumpkind. This argument will be ignored if set to None.

  • jumpkind

返回:

A list of successors

返回类型:

list

get_successors_and_jumpkinds(node, excluding_fakeret=True)[源代码]

Get a list of tuples where the first element is the successor of the CFG node and the second element is the jumpkind of the successor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all successors that are fall-through successors.

返回:

A list of successors and their corresponding jumpkinds.

返回类型:

list

get_successors_and_jumpkind(node, excluding_fakeret=True)

Get a list of tuples where the first element is the successor of the CFG node and the second element is the jumpkind of the successor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all successors that are fall-through successors.

返回:

A list of successors and their corresponding jumpkinds.

返回类型:

list

get_predecessors_and_jumpkinds(node, excluding_fakeret=True)[源代码]

Get a list of tuples where the first element is the predecessor of the CFG node and the second element is the jumpkind of the predecessor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all predecessors that are fall-through predecessors.

返回类型:

list[tuple[CFGNode, str]]

返回:

A list of predecessors and their corresponding jumpkinds.

get_predecessors_and_jumpkind(node, excluding_fakeret=True)

Get a list of tuples where the first element is the predecessor of the CFG node and the second element is the jumpkind of the predecessor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all predecessors that are fall-through predecessors.

返回类型:

list[tuple[CFGNode, str]]

返回:

A list of predecessors and their corresponding jumpkinds.

get_all_predecessors(cfgnode, depth_limit=None)[源代码]

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

参数:
  • cfgnode (CFGNode) -- The CFGNode object

  • depth_limit (int) -- Optional depth limit for the depth-first search

返回:

A list of predecessors in the CFG

返回类型:

list

get_all_successors(cfgnode, depth_limit=None)[源代码]

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

参数:
  • cfgnode (CFGNode) -- The CFGNode object

  • depth_limit (int) -- Optional depth limit for the depth-first search

返回:

A list of successors in the CFG

返回类型:

list

get_branching_nodes()[源代码]

Returns all nodes that has an out degree >= 2

get_exit_stmt_idx(src_block, dst_block)[源代码]

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

返回:

The exit statement ID

add_memory_data(data_addr, data_type, data_size=None)[源代码]

Add a MemoryData entry to self.memory_data.

参数:
  • data_addr (int) -- Address of the data

  • data_type (MemoryDataSort | None) -- Type of the memory data

  • data_size (Optional[int]) -- Size of the memory data, or None if unknown for now.

返回类型:

bool

返回:

True if a new memory data entry is added, False otherwise.

tidy_data_references(memory_data_addrs=None, exec_mem_regions=None, xrefs=None, seg_list=None, data_type_guessing_handlers=None)[源代码]

Go through all data references (or the ones as specified by memory_data_addrs) and determine their sizes and types if possible.

参数:
  • memory_data_addrs (list[int] | None) -- A list of addresses of memory data, or None if tidying all known memory data entries.

  • exec_mem_regions (list[tuple[int, int]] | None) -- A list of start and end addresses of executable memory regions.

  • seg_list (SegmentList | None) -- The segment list that CFGFast uses during CFG recovery.

  • data_type_guessing_handlers (list[Callable] | None) -- A list of Python functions that will guess data types. They will be called in sequence to determine data types for memory data whose type is unknown.

  • xrefs (XRefManager | None)

返回类型:

bool

返回:

True if new data entries are found, False otherwise.

remove_node_and_graph_node(node)[源代码]

Like remove_node, but also removes node from the graph.

参数:

node (CFGNode) -- The node to remove.

返回类型:

None

get_intersecting_functions(addr, size=1, kb=None)[源代码]

Find all functions with nodes intersecting [addr, addr + size).

参数:
  • addr (int) -- Minimum address of target region.

  • size (int) -- Size of region, in bytes.

  • kb (KnowledgeBase | None) -- Knowledge base to search for functions in.

返回类型:

set[Function]

find_function_for_reflow_into_addr(addr, kb=None)[源代码]

Look for a function that flows into a new node at addr.

参数:
  • addr (int) -- Address of new block.

  • kb (KnowledgeBase | None) -- Knowledge base to search for functions in.

返回类型:

Function | None

clear_region_for_reflow(addr, size=1, kb=None)[源代码]

Remove nodes in the graph intersecting region [addr, addr + size).

Any functions that intersect the range, and their associated nodes in the CFG, will also be removed from the knowledge base for analysis.

参数:
  • addr (int) -- Minimum address of target region.

  • size (int) -- Size of the region, in bytes.

  • kb (KnowledgeBase | None) -- Knowledge base to search for functions in.

返回类型:

None

class angr.knowledge_plugins.cfg.CFGNode(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, soot_block=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None)[源代码]

基类:Serializable

This class stands for each single node in CFG.

__init__(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, soot_block=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None)[源代码]

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

addr: int | SootAddressDescriptor
size
simprocedure_name
no_ret
function_address
thumb
byte_string: bytes | None
is_syscall
instruction_addrs
irsb
soot_block
has_return
block_id: BlockID | int
property name
property successors
property predecessors
successors_and_jumpkinds(excluding_fakeret=True)[源代码]
predecessors_and_jumpkinds(excluding_fakeret=True)[源代码]
get_data_references(kb=None)[源代码]

Get the known data references for this CFGNode via the knowledge base.

参数:

kb -- Which knowledge base to use; uses the global KB by default if none is provided

返回:

Generator yielding xrefs to this CFGNode's block.

返回类型:

iter

property accessed_data_references

Property providing a view of all the known data references for this CFGNode via the global knowledge base

返回:

Generator yielding xrefs to this CFGNode's block.

返回类型:

iter

property is_simprocedure
property callstack_key
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg=None)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

copy()[源代码]
merge(other)[源代码]

Merges this node with the other, returning a new node that spans the both.

to_codenode()[源代码]
property block: Block | SootBlock | None
syscall_name
class angr.knowledge_plugins.cfg.IndirectJump(addr, ins_addr, func_addr, jumpkind, stmt_idx, resolved_targets=None, jumptable=False, jumptable_addr=None, jumptable_size=None, jumptable_entry_size=None, jumptable_entries=None, type_=255)[源代码]

基类:Serializable

参数:
  • addr (int)

  • ins_addr (int)

  • func_addr (int)

  • jumpkind (str)

  • stmt_idx (int)

  • resolved_targets (list[int] | None)

  • jumptable (bool)

  • jumptable_addr (int | None)

  • jumptable_size (int | None)

  • jumptable_entry_size (int | None)

  • jumptable_entries (list[int] | None)

  • type_ (int | None)

__init__(addr, ins_addr, func_addr, jumpkind, stmt_idx, resolved_targets=None, jumptable=False, jumptable_addr=None, jumptable_size=None, jumptable_entry_size=None, jumptable_entries=None, type_=255)[源代码]
参数:
  • addr (int)

  • ins_addr (int)

  • func_addr (int)

  • jumpkind (str)

  • stmt_idx (int)

  • resolved_targets (list[int] | None)

  • jumptable (bool)

  • jumptable_addr (int | None)

  • jumptable_size (int | None)

  • jumptable_entry_size (int | None)

  • jumptable_entries (list[int] | None)

  • type_ (int | None)

addr
ins_addr
func_addr
jumpkind
stmt_idx
resolved_targets
jumptable
jumptable_addr
jumptable_size
jumptable_entry_size
jumptable_entries
type
class angr.knowledge_plugins.cfg.IndirectJumpType[源代码]

基类:object

Jumptable_AddressLoadedFromMemory = 0
Jumptable_AddressComputed = 1
Vtable = 3
Unknown = 255
class angr.knowledge_plugins.cfg.MemoryData(address, size, sort, pointer_addr=None, max_size=None, reference_size=None)[源代码]

基类:Serializable

MemoryData describes the syntactic content of a single address of memory.

reference_size reflects the size of content. It can be different from size, which is the actual size of the memory data item in memory. The intended way to get the actual content in memory is self.content[:self.size].

参数:
  • address (int)

  • size (int)

  • sort (str | None)

  • pointer_addr (int | None)

  • max_size (int | None)

  • reference_size (int | None)

__init__(address, size, sort, pointer_addr=None, max_size=None, reference_size=None)[源代码]
参数:
  • address (int)

  • size (int)

  • sort (str | None)

  • pointer_addr (int | None)

  • max_size (int | None)

  • reference_size (int | None)

addr: int
size: int
reference_size: int
sort: str | None
max_size: int | None
pointer_addr: int | None
content: bytes | None
property address
copy()[源代码]

Make a copy of the MemoryData.

返回:

A copy of the MemoryData instance.

返回类型:

MemoryData

fill_content(loader)[源代码]

Load data to fill self.content.

参数:

loader -- The project loader.

返回:

None

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.knowledge_plugins.cfg.MemoryDataSort[源代码]

基类:object

Unspecified = None
Unknown = 'unknown'
Integer = 'integer'
PointerArray = 'pointer-array'
String = 'string'
UnicodeString = 'unicode'
SegmentBoundary = 'segment-boundary'
CodeReference = 'code reference'
GOTPLTEntry = 'GOT PLT Entry'
ELFHeader = 'elf-header'
FloatingPoint = 'fp'
Alignment = 'alignment'
class angr.knowledge_plugins.cfg.cfg_model.CFGModel(ident, cfg_manager=None, is_arm=False)[源代码]

基类:Serializable

This class describes a Control Flow Graph for a specific range of code.

__init__(ident, cfg_manager=None, is_arm=False)[源代码]
ident
is_arm
graph
jump_tables: dict[int, IndirectJump]
memory_data: dict[int, MemoryData]
insn_addr_to_memory_data: dict[int, MemoryData]
normalized
edges_to_repair
property project
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg_manager=None, loader=None)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

copy()[源代码]
add_node(block_id, node)[源代码]
返回类型:

None

参数:
remove_node(block_id, node)[源代码]

Remove the given CFGNode instance. Note that this method does not remove the node from the graph.

参数:
  • block_id (int) -- The Unique ID of the CFGNode.

  • node (CFGNode) -- The CFGNode instance to remove.

返回类型:

None

返回:

None

get_node(block_id)[源代码]

Get a single node from node key.

参数:

block_id (BlockID) -- Block ID of the node.

返回:

The CFGNode

返回类型:

CFGNode

get_any_node(addr, is_syscall=None, anyaddr=False, force_fastpath=False)[源代码]

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

参数:
  • addr (int) -- Address of the beginning of the basic block. Set anyaddr to True to support arbitrary address.

  • is_syscall (Optional[bool]) -- Whether you want to get the syscall node or any other node. This is due to the fact that syscall SimProcedures have the same address as the target it returns to. None means get either, True means get a syscall node, False means get something that isn't a syscall node.

  • anyaddr (bool) -- If anyaddr is True, then addr doesn't have to be the beginning address of a basic block. By default the entire graph.nodes() will be iterated, and the first node containing the specific address is returned, which can be slow.

  • force_fastpath (bool) -- If force_fastpath is True, it will only perform a dict lookup in the _nodes_by_addr dict.

返回类型:

CFGNode | None

返回:

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

get_all_nodes(addr, is_syscall=None, anyaddr=False)[源代码]

Get all CFGNodes whose address is the specified one.

参数:
  • addr (int) -- Address of the node

  • is_syscall (Optional[bool]) -- True returns the syscall node, False returns the normal CFGNode, None returns both

  • anyaddr (bool)

返回类型:

list[CFGNode]

返回:

all CFGNodes

get_all_nodes_intersecting_region(addr, size=1)[源代码]

Get all CFGNodes that intersect the given region.

参数:
  • addr (int) -- Minimum address of target region.

  • size (int) -- Size of region, in bytes.

返回类型:

set[CFGNode]

nodes()[源代码]

An iterator of all nodes in the graph.

返回:

The iterator.

返回类型:

iterator

get_predecessors(cfgnode, excluding_fakeret=True, jumpkind=None)[源代码]

Get predecessors of a node in the control flow graph.

参数:
  • cfgnode (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all predecessors that is connected to the node with a fakeret edge.

  • jumpkind (Optional[str]) -- Only return predecessors with the specified jumpkind. This argument will be ignored if set to None.

返回类型:

list[CFGNode]

返回:

A list of predecessors

get_successors(node, excluding_fakeret=True, jumpkind=None)[源代码]

Get successors of a node in the control flow graph.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all successors that is connected to the node with a fakeret edge.

  • jumpkind (str | None) -- Only return successors with the specified jumpkind. This argument will be ignored if set to None.

  • jumpkind

返回:

A list of successors

返回类型:

list

get_successors_and_jumpkinds(node, excluding_fakeret=True)[源代码]

Get a list of tuples where the first element is the successor of the CFG node and the second element is the jumpkind of the successor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all successors that are fall-through successors.

返回:

A list of successors and their corresponding jumpkinds.

返回类型:

list

get_successors_and_jumpkind(node, excluding_fakeret=True)

Get a list of tuples where the first element is the successor of the CFG node and the second element is the jumpkind of the successor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all successors that are fall-through successors.

返回:

A list of successors and their corresponding jumpkinds.

返回类型:

list

get_predecessors_and_jumpkinds(node, excluding_fakeret=True)[源代码]

Get a list of tuples where the first element is the predecessor of the CFG node and the second element is the jumpkind of the predecessor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all predecessors that are fall-through predecessors.

返回类型:

list[tuple[CFGNode, str]]

返回:

A list of predecessors and their corresponding jumpkinds.

get_predecessors_and_jumpkind(node, excluding_fakeret=True)

Get a list of tuples where the first element is the predecessor of the CFG node and the second element is the jumpkind of the predecessor.

参数:
  • node (CFGNode) -- The node.

  • excluding_fakeret (bool) -- True if you want to exclude all predecessors that are fall-through predecessors.

返回类型:

list[tuple[CFGNode, str]]

返回:

A list of predecessors and their corresponding jumpkinds.

get_all_predecessors(cfgnode, depth_limit=None)[源代码]

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

参数:
  • cfgnode (CFGNode) -- The CFGNode object

  • depth_limit (int) -- Optional depth limit for the depth-first search

返回:

A list of predecessors in the CFG

返回类型:

list

get_all_successors(cfgnode, depth_limit=None)[源代码]

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

参数:
  • cfgnode (CFGNode) -- The CFGNode object

  • depth_limit (int) -- Optional depth limit for the depth-first search

返回:

A list of successors in the CFG

返回类型:

list

get_branching_nodes()[源代码]

Returns all nodes that has an out degree >= 2

get_exit_stmt_idx(src_block, dst_block)[源代码]

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

返回:

The exit statement ID

add_memory_data(data_addr, data_type, data_size=None)[源代码]

Add a MemoryData entry to self.memory_data.

参数:
  • data_addr (int) -- Address of the data

  • data_type (MemoryDataSort | None) -- Type of the memory data

  • data_size (Optional[int]) -- Size of the memory data, or None if unknown for now.

返回类型:

bool

返回:

True if a new memory data entry is added, False otherwise.

tidy_data_references(memory_data_addrs=None, exec_mem_regions=None, xrefs=None, seg_list=None, data_type_guessing_handlers=None)[源代码]

Go through all data references (or the ones as specified by memory_data_addrs) and determine their sizes and types if possible.

参数:
  • memory_data_addrs (list[int] | None) -- A list of addresses of memory data, or None if tidying all known memory data entries.

  • exec_mem_regions (list[tuple[int, int]] | None) -- A list of start and end addresses of executable memory regions.

  • seg_list (SegmentList | None) -- The segment list that CFGFast uses during CFG recovery.

  • data_type_guessing_handlers (list[Callable] | None) -- A list of Python functions that will guess data types. They will be called in sequence to determine data types for memory data whose type is unknown.

  • xrefs (XRefManager | None)

返回类型:

bool

返回:

True if new data entries are found, False otherwise.

remove_node_and_graph_node(node)[源代码]

Like remove_node, but also removes node from the graph.

参数:

node (CFGNode) -- The node to remove.

返回类型:

None

get_intersecting_functions(addr, size=1, kb=None)[源代码]

Find all functions with nodes intersecting [addr, addr + size).

参数:
  • addr (int) -- Minimum address of target region.

  • size (int) -- Size of region, in bytes.

  • kb (KnowledgeBase | None) -- Knowledge base to search for functions in.

返回类型:

set[Function]

find_function_for_reflow_into_addr(addr, kb=None)[源代码]

Look for a function that flows into a new node at addr.

参数:
  • addr (int) -- Address of new block.

  • kb (KnowledgeBase | None) -- Knowledge base to search for functions in.

返回类型:

Function | None

clear_region_for_reflow(addr, size=1, kb=None)[源代码]

Remove nodes in the graph intersecting region [addr, addr + size).

Any functions that intersect the range, and their associated nodes in the CFG, will also be removed from the knowledge base for analysis.

参数:
  • addr (int) -- Minimum address of target region.

  • size (int) -- Size of the region, in bytes.

  • kb (KnowledgeBase | None) -- Knowledge base to search for functions in.

返回类型:

None

class angr.knowledge_plugins.cfg.memory_data.MemoryDataSort[源代码]

基类:object

Unspecified = None
Unknown = 'unknown'
Integer = 'integer'
PointerArray = 'pointer-array'
String = 'string'
UnicodeString = 'unicode'
SegmentBoundary = 'segment-boundary'
CodeReference = 'code reference'
GOTPLTEntry = 'GOT PLT Entry'
ELFHeader = 'elf-header'
FloatingPoint = 'fp'
Alignment = 'alignment'
class angr.knowledge_plugins.cfg.memory_data.MemoryData(address, size, sort, pointer_addr=None, max_size=None, reference_size=None)[源代码]

基类:Serializable

MemoryData describes the syntactic content of a single address of memory.

reference_size reflects the size of content. It can be different from size, which is the actual size of the memory data item in memory. The intended way to get the actual content in memory is self.content[:self.size].

参数:
  • address (int)

  • size (int)

  • sort (str | None)

  • pointer_addr (int | None)

  • max_size (int | None)

  • reference_size (int)

__init__(address, size, sort, pointer_addr=None, max_size=None, reference_size=None)[源代码]
参数:
  • address (int)

  • size (int)

  • sort (str | None)

  • pointer_addr (int | None)

  • max_size (int | None)

  • reference_size (int | None)

addr: int
size: int
reference_size: int
sort: str | None
max_size: int | None
pointer_addr: int | None
content: bytes | None
property address
copy()[源代码]

Make a copy of the MemoryData.

返回:

A copy of the MemoryData instance.

返回类型:

MemoryData

fill_content(loader)[源代码]

Load data to fill self.content.

参数:

loader -- The project loader.

返回:

None

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.knowledge_plugins.cfg.cfg_manager.CFGManager(kb)[源代码]

基类:KnowledgeBasePlugin

This is the CFG manager, it manages CFGs

__init__(kb)[源代码]
new_model(prefix)[源代码]
copy()[源代码]
get_most_accurate()[源代码]
返回类型:

CFGModel | None

返回:

The most accurate CFG present in the CFGManager, or None if it does not hold any.

class angr.knowledge_plugins.cfg.cfg_node.CFGNodeCreationFailure(exc_info=None, to_copy=None)[源代码]

基类:object

This class contains additional information for whenever creating a CFGNode failed. It includes a full traceback and the exception messages.

__init__(exc_info=None, to_copy=None)[源代码]
short_reason
long_reason
traceback
class angr.knowledge_plugins.cfg.cfg_node.CFGNode(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, soot_block=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None)[源代码]

基类:Serializable

This class stands for each single node in CFG.

参数:
__init__(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, soot_block=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None)[源代码]

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

addr: int | SootAddressDescriptor
size
simprocedure_name
no_ret
function_address
thumb
byte_string: bytes | None
is_syscall
instruction_addrs
irsb
soot_block
has_return
block_id: BlockID | int
property name
property successors
property predecessors
successors_and_jumpkinds(excluding_fakeret=True)[源代码]
predecessors_and_jumpkinds(excluding_fakeret=True)[源代码]
get_data_references(kb=None)[源代码]

Get the known data references for this CFGNode via the knowledge base.

参数:

kb -- Which knowledge base to use; uses the global KB by default if none is provided

返回:

Generator yielding xrefs to this CFGNode's block.

返回类型:

iter

property accessed_data_references

Property providing a view of all the known data references for this CFGNode via the global knowledge base

返回:

Generator yielding xrefs to this CFGNode's block.

返回类型:

iter

property is_simprocedure
property callstack_key
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg=None)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

copy()[源代码]
merge(other)[源代码]

Merges this node with the other, returning a new node that spans the both.

to_codenode()[源代码]
property block: Block | SootBlock | None
syscall_name
class angr.knowledge_plugins.cfg.cfg_node.CFGENode(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None, input_state=None, final_states=None, syscall_name=None, looping_times=0, depth=None, callstack_key=None, creation_failure_info=None)[源代码]

基类:CFGNode

The CFGNode that is used in CFGEmulated.

参数:
__init__(addr, size, cfg, simprocedure_name=None, no_ret=False, function_address=None, block_id=None, irsb=None, instruction_addrs=None, thumb=False, byte_string=None, is_syscall=None, name=None, input_state=None, final_states=None, syscall_name=None, looping_times=0, depth=None, callstack_key=None, creation_failure_info=None)[源代码]

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

input_state
looping_times
depth
creation_failure_info
final_states
return_target
syscall
property callstack_key
property creation_failed
downsize()[源代码]

Drop saved states.

copy()[源代码]
class angr.knowledge_plugins.cfg.indirect_jump.IndirectJumpType[源代码]

基类:object

Jumptable_AddressLoadedFromMemory = 0
Jumptable_AddressComputed = 1
Vtable = 3
Unknown = 255
class angr.knowledge_plugins.cfg.indirect_jump.IndirectJump(addr, ins_addr, func_addr, jumpkind, stmt_idx, resolved_targets=None, jumptable=False, jumptable_addr=None, jumptable_size=None, jumptable_entry_size=None, jumptable_entries=None, type_=255)[源代码]

基类:Serializable

参数:
  • addr (int)

  • ins_addr (int)

  • func_addr (int)

  • jumpkind (str)

  • stmt_idx (int)

  • resolved_targets (list[int] | None)

  • jumptable (bool)

  • jumptable_addr (int | None)

  • jumptable_size (int | None)

  • jumptable_entry_size (int | None)

  • jumptable_entries (list[int] | None)

  • type_ (int | None)

__init__(addr, ins_addr, func_addr, jumpkind, stmt_idx, resolved_targets=None, jumptable=False, jumptable_addr=None, jumptable_size=None, jumptable_entry_size=None, jumptable_entries=None, type_=255)[源代码]
参数:
  • addr (int)

  • ins_addr (int)

  • func_addr (int)

  • jumpkind (str)

  • stmt_idx (int)

  • resolved_targets (list[int] | None)

  • jumptable (bool)

  • jumptable_addr (int | None)

  • jumptable_size (int | None)

  • jumptable_entry_size (int | None)

  • jumptable_entries (list[int] | None)

  • type_ (int | None)

addr
ins_addr
func_addr
jumpkind
stmt_idx
resolved_targets
jumptable
jumptable_addr
jumptable_size
jumptable_entry_size
jumptable_entries
type
class angr.knowledge_plugins.types.TypesStore(kb)[源代码]

基类:KnowledgeBasePlugin, UserDict

A kb plugin that stores a mapping from name to TypeRef. It will return types from angr.sim_type.ALL_TYPES as a default.

__init__(kb)[源代码]
copy()[源代码]
iter_own()[源代码]

Iterate over all the names which are stored in this object - i.e. values() without ALL_TYPES

rename(old, new)[源代码]
unique_type_name()[源代码]
返回类型:

str

class angr.knowledge_plugins.propagations.PropagationManager(kb)[源代码]

基类:KnowledgeBasePlugin

Manages the results of Propagator, including intermediate results for unfinished Propagation runs.

__init__(kb)[源代码]
exists(prop_key)[源代码]

Internal function to check if a func, specified as a CodeLocation exists in our known propagations

参数:

prop_key (tuple) -- A key of the propagation result.

返回类型:

bool

返回:

Whether such a key exists or not.

update(prop_key, model)[源代码]

Add the replacements to known propagations

参数:
  • prop_key (tuple) -- A key of the propagation result.

  • model (PropagationModel) -- The propagation result to store

返回类型:

None

get(prop_key, default=None)[源代码]

Gets the replacements for a specified function location. If the replacement does not exist in the known propagations, it returns None.

参数:
  • prop_key -- A key of the propagation result.

  • default -- The default value to return if the prop_key does not exist in the cache.

返回类型:

PropagationModel

返回:

Dict or None

copy()[源代码]
discard_by_prefix(prefix)[源代码]
参数:

prefix (str)

class angr.knowledge_plugins.propagations.PropagationModel(prop_key, node_iterations=None, states=None, block_initial_reg_values=None, replacements=None, equivalence=None, function=None, input_states=None)[源代码]

基类:Serializable

This class stores the propagation result that comes out of Propagator.

参数:
  • prop_key (tuple)

  • node_iterations (defaultdict[Any, int] | None)

  • states (dict | None)

  • block_initial_reg_values (dict | None)

  • replacements (defaultdict[Any, dict] | None)

  • equivalence (set | None)

  • function (Function | None)

  • input_states (dict | None)

__init__(prop_key, node_iterations=None, states=None, block_initial_reg_values=None, replacements=None, equivalence=None, function=None, input_states=None)[源代码]
参数:
key
node_iterations
input_states
states
block_initial_reg_values
replacements
equivalence
graph_visitor
downsize()[源代码]
block_beginning_state(block_addr)[源代码]
返回类型:

PropagatorState

class angr.knowledge_plugins.comments.Comments(kb)[源代码]

基类:KnowledgeBasePlugin, dict

Tracks comments via a Dict of Address -> Text

参数:

kb (KnowledgeBase)

copy() a shallow copy of D[源代码]
class angr.knowledge_plugins.data.Data(kb)[源代码]

基类:KnowledgeBasePlugin

The knowledge what purpose this plugin serves has been lost to the passing of time but the linter does not care for these failures of mere mortals and demands a docstring anyway. The pact has been made, and no violations of the rules will be tolerated, even if the spirit does not match the letter. Making the plugin smaller has only increased the weight of the failure, and thus this file has drawn its ire.

The only thing left to do is to attempt to find meaning in the meaninglessness, as the only act of rebellion against the uncaring forces that bind us. For is this not what being human is all about?

参数:

kb (KnowledgeBase)

copy()[源代码]
class angr.knowledge_plugins.indirect_jumps.IndirectJumps(kb)[源代码]

基类:KnowledgeBasePlugin, dict

This plugin tracks the targets of indirect jumps

__init__(kb)[源代码]
copy() a shallow copy of D[源代码]
update_resolved_addrs(indirect_address, resolved_addresses)[源代码]
参数:
  • indirect_address (int)

  • resolved_addresses (list[int])

class angr.knowledge_plugins.labels.Labels(kb)[源代码]

基类:KnowledgeBasePlugin

__init__(kb)[源代码]
items()[源代码]
get(addr)[源代码]

Get a label as string for a given address Same as .labels[x]

lookup(name)[源代码]

Returns an address to a given label To show all available labels, iterate over .labels or list(b.kb.labels)

copy()[源代码]
get_unique_label(label)[源代码]

Get a unique label name from the given label name.

参数:

label (str) -- The desired label name.

返回:

A unique label name.

class angr.knowledge_plugins.functions.Function(function_manager, addr, name=None, syscall=None, is_simprocedure=None, binary_name=None, is_plt=None, returning=None, alignment=False)[源代码]

基类:Serializable

A representation of a function and various information about it.

参数:
  • is_simprocedure (bool | None)

  • is_plt (bool | None)

__init__(function_manager, addr, name=None, syscall=None, is_simprocedure=None, binary_name=None, is_plt=None, returning=None, alignment=False)[源代码]

Function constructor. If the optional parameters are not provided, they will be automatically determined upon the creation of a Function object.

参数:
  • addr -- The address of the function.

  • is_simprocedure (bool | None)

  • is_plt (bool | None)

The following parameters are optional.

参数:
  • name (str) -- The name of the function.

  • syscall (bool) -- Whether this function is a syscall or not.

  • is_simprocedure (bool) -- Whether this function is a SimProcedure or not.

  • binary_name (str) -- Name of the binary where this function is.

  • is_plt (bool) -- If this function is a PLT entry.

  • returning (bool) -- If this function returns.

  • alignment (bool) -- If this function acts as an alignment filler. Such functions usually only contain nops.

transition_graph
normalized
addr
startpoint
is_alignment
bp_on_stack
retaddr_on_stack
sp_delta
prototype: SimTypeFunction | None
prototype_libname: str | None
is_prototype_guessed: bool
prepared_registers
prepared_stack_variables
registers_read_afterwards
info
tags
ran_cca
is_syscall
is_simprocedure
is_plt
is_default_name
previous_names
from_signature
binary_name
calling_convention: SimCC | None
property alignment
property name
property project
property returning
property blocks

An iterator of all local blocks in the current function.

返回:

angr.lifter.Block instances.

property cyclomatic_complexity

The cyclomatic complexity of the function.

Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code. It is computed using the formula: M = E - N + 2P, where E = the number of edges in the graph, N = the number of nodes in the graph, P = the number of connected components.

The cyclomatic complexity value is lazily computed and cached for future use. Initially this value is None until it is computed for the first time

返回:

The cyclomatic complexity of the function.

返回类型:

int

property xrefs

An iterator of all xrefs of the current function.

返回:

angr.knowledge_plugins.xrefs.xref.XRef instances.

property block_addrs

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

返回:

block addresses.

property block_addrs_set

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

返回:

A set of block addresses.

返回类型:

set

get_block(addr, size=None, byte_string=None)[源代码]

Getting a block out of the current function.

参数:
  • addr (int) -- The address of the block.

  • size (int) -- The size of the block. This is optional. If not provided, angr will load

  • byte_string (Optional[bytes])

返回:

get_block_size(addr)[源代码]
返回类型:

int | None

参数:

addr (int)

property nodes: Iterable[CodeNode]
get_node(addr)[源代码]
返回类型:

BlockNode | None

property has_unresolved_jumps
property has_unresolved_calls
property operations

All of the operations that are done by this functions.

property code_constants

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

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]
参数:

cmsg

Return Function:

The function instantiated out of the cmsg data.

string_references(minimum_length=2)[源代码]

All of the constant string references used by this function.

参数:

minimum_length -- The minimum length of strings to find (default is 1)

返回:

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

property local_runtime_values

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

返回:

a set of constants

property num_arguments
property endpoints
property endpoints_with_type
property ret_sites
property jumpout_sites
property retout_sites
property callout_sites
property size
property binary

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

property offset: int

the function's binary offset (i.e., non-rebased address)

Type:

return

property symbol: None | Symbol

the function's Symbol, if any

Type:

return

property pseudocode: str

the function's pseudocode

Type:

return

add_jumpout_site(node)[源代码]

Add a custom jumpout site.

参数:

node (CodeNode) -- The address of the basic block that control flow leaves during this transition.

返回:

None

add_retout_site(node)[源代码]

Add a custom retout site.

Retout (returning to outside of the function) sites are very rare. It mostly occurs during CFG recovery when we incorrectly identify the beginning of a function in the first iteration, and then correctly identify that function later in the same iteration (function alignments can lead to this bizarre case). We will mark all edges going out of the header of that function as a outside edge, because all successors now belong to the incorrectly-identified function. This identification error will be fixed in the second iteration of CFG recovery. However, we still want to keep track of jumpouts/retouts during the first iteration so other logic in CFG recovery still work.

参数:

node (CodeNode) -- The address of the basic block that control flow leaves the current function after a call.

返回:

None

mark_nonreturning_calls_endpoints()[源代码]

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

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

返回:

None

get_call_sites()[源代码]

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

返回类型:

Iterable[int]

返回:

A view of the addresses of the blocks that end in calls.

get_call_target(callsite_addr)[源代码]

Get the target of a call.

参数:

callsite_addr -- The address of a basic block that ends in a call.

返回:

The target of said call, or None if callsite_addr is not a callsite.

get_call_return(callsite_addr)[源代码]

Get the hypothetical return address of a call.

参数:

callsite_addr -- The address of the basic block that ends in a call.

返回:

The likely return target of said call, or None if callsite_addr is not a callsite.

property graph

Get a local transition graph. A local transition graph is a transition graph that only contains nodes that belong to the current function. All edges, except for the edges going out from the current function or coming from outside the current function, are included.

The generated graph is cached in self._local_transition_graph.

返回:

A local transition graph.

返回类型:

networkx.DiGraph

graph_ex(exception_edges=True)[源代码]

Get a local transition graph with a custom configuration. A local transition graph is a transition graph that only contains nodes that belong to the current function. This method allows user to exclude certain types of edges together with the nodes that are only reachable through such edges, such as exception edges.

The generated graph is not cached.

参数:

exception_edges (bool) -- Should exception edges and the nodes that are only reachable through exception edges be kept.

返回:

A local transition graph with a special configuration.

返回类型:

networkx.DiGraph

transition_graph_ex(exception_edges=True)[源代码]

Get a transition graph with a custom configuration. This method allows user to exclude certain types of edges together with the nodes that are only reachable through such edges, such as exception edges.

The generated graph is not cached.

参数:

exception_edges (bool) -- Should exception edges and the nodes that are only reachable through exception edges be kept.

返回:

A local transition graph with a special configuration.

返回类型:

networkx.DiGraph

subgraph(ins_addrs)[源代码]

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

参数:

ins_addrs (iterable) -- A collection of instruction addresses that should be included in the subgraph.

Return networkx.DiGraph:

A subgraph.

instruction_size(insn_addr)[源代码]

Get the size of the instruction specified by insn_addr.

参数:

insn_addr (int) -- Address of the instruction

Return int:

Size of the instruction in bytes, or None if the instruction is not found.

addr_to_instruction_addr(addr)[源代码]

Obtain the address of the instruction that covers @addr.

参数:

addr (int) -- An address.

返回:

Address of the instruction that covers @addr, or None if this addr is not covered by any instruction of this function.

返回类型:

int or None

dbg_print()[源代码]

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

dbg_draw(filename)[源代码]

Draw the graph and save it to a PNG file.

property arguments
property has_return
property callable
normalize()[源代码]

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

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

返回:

None

find_declaration(ignore_binary_name=False, binary_name_hint=None)[源代码]

Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, and update self.calling_convention with the declaration.

参数:
  • ignore_binary_name (bool) -- Do not rely on the executable or library where the function belongs to determine its source library. This is useful when working on statically linked binaries (because all functions will belong to the main executable). We will search for all libraries in angr to find the first declaration match.

  • binary_name_hint (Optional[str]) -- Substring of the library name where this function might be originally coming from. Useful for FLIRT-identified functions in statically linked binaries.

返回类型:

bool

返回:

True if a declaration is found and self.prototype and self.calling_convention are updated. False if we fail to find a matching function declaration, in which case self.prototype or self.calling_convention will be kept untouched.

property demangled_name
get_unambiguous_name(display_name=None)[源代码]

Get a disambiguated function name.

参数:

display_name (Optional[str]) -- Name to display, otherwise the function name.

返回类型:

str

返回:

The function name in the form: ::<name> when the function binary is the main object. ::<obj>::<name> when the function binary is not the main object. ::<addr>::<name> when the function binary is an unnamed non-main object, or when multiple functions with

the same name are defined in the function binary.

apply_definition(definition, calling_convention=None)[源代码]
返回类型:

None

参数:
functions_reachable()[源代码]
返回类型:

set[Function]

返回:

The set of all functions that can be reached from the function represented by self.

copy()[源代码]
pp(**kwargs)[源代码]

Pretty-print the function disassembly.

class angr.knowledge_plugins.functions.FunctionManager(kb)[源代码]

基类:KnowledgeBasePlugin, Mapping

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

__init__(kb)[源代码]
copy()[源代码]
clear()[源代码]
get_by_addr(addr)[源代码]
返回类型:

Function

get_by_name(name, check_previous_names=False)[源代码]
返回类型:

Generator[Function]

参数:
  • name (str)

  • check_previous_names (bool)

contains_addr(addr)[源代码]

Decide if an address is handled by the function manager.

Note: this function is non-conformant with python programming idioms, but its needed for performance reasons.

参数:

addr (int) -- Address of the function.

ceiling_func(addr)[源代码]

Return the function who has the least address that is greater than or equal to addr.

参数:

addr (int) -- The address to query.

返回:

A Function instance, or None if there is no other function after addr.

返回类型:

Function or None

floor_func(addr)[源代码]

Return the function who has the greatest address that is less than or equal to addr.

参数:

addr (int) -- The address to query.

返回:

A Function instance, or None if there is no other function before addr.

返回类型:

Function or None

query(query, check_previous_names=False)[源代码]

Query for a function using selectors to disambiguate. Supported variations: :rtype: Function | None

::<name> Function <name> in the main object ::<addr>::<name> Function <name> at <addr> ::<obj>::<name> Function <name> in <obj>

参数:
  • query (str)

  • check_previous_names (bool)

返回类型:

Function | None

function(addr=None, name=None, check_previous_names=False, create=False, syscall=False, plt=None)[源代码]

Get a function object from the function manager.

Pass either addr or name with the appropriate values.

参数:
  • addr (int) -- Address of the function.

  • name (str) -- Name of the function.

  • create (bool) -- Whether to create the function or not if the function does not exist.

  • syscall (bool) -- True to create the function as a syscall, False otherwise.

  • plt (bool or None) -- True to find the PLT stub, False to find a non-PLT stub, None to disable this restriction.

返回:

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

返回类型:

Function or None

dbg_draw(prefix='dbg_function_')[源代码]
rebuild_callgraph()[源代码]
class angr.knowledge_plugins.functions.function_manager.FunctionDict(backref, *args, **kwargs)[源代码]

基类:SortedDict

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

__init__(backref, *args, **kwargs)[源代码]

Initialize sorted dict instance.

Optional key-function argument defines a callable that, like the key argument to the built-in sorted function, extracts a comparison key from each dictionary key. If no function is specified, the default compares the dictionary keys directly. The key-function argument must be provided as a positional argument and must come before all other arguments.

Optional iterable argument provides an initial sequence of pairs to initialize the sorted dict. Each pair in the sequence defines the key and corresponding value. If a key is seen more than once, the last value associated with it is stored in the new sorted dict.

Optional mapping argument provides an initial mapping of items to initialize the sorted dict.

If keyword arguments are given, the keywords themselves, with their associated values, are added as items to the dictionary. If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is stored in the sorted dict.

Sorted dict keys must be hashable, per the requirement for Python's dictionaries. Keys (or the result of the key-function) must also be comparable, per the requirement for sorted lists.

>>> d = {'alpha': 1, 'beta': 2}
>>> SortedDict([('alpha', 1), ('beta', 2)]) == d
True
>>> SortedDict({'alpha': 1, 'beta': 2}) == d
True
>>> SortedDict(alpha=1, beta=2) == d
True
get(addr)[源代码]

Return the value for key if key is in the dictionary, else default.

floor_addr(addr)[源代码]
ceiling_addr(addr)[源代码]
class angr.knowledge_plugins.functions.function_manager.FunctionManager(kb)[源代码]

基类:KnowledgeBasePlugin, Mapping

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

__init__(kb)[源代码]
copy()[源代码]
clear()[源代码]
get_by_addr(addr)[源代码]
返回类型:

Function

get_by_name(name, check_previous_names=False)[源代码]
返回类型:

Generator[Function]

参数:
  • name (str)

  • check_previous_names (bool)

contains_addr(addr)[源代码]

Decide if an address is handled by the function manager.

Note: this function is non-conformant with python programming idioms, but its needed for performance reasons.

参数:

addr (int) -- Address of the function.

ceiling_func(addr)[源代码]

Return the function who has the least address that is greater than or equal to addr.

参数:

addr (int) -- The address to query.

返回:

A Function instance, or None if there is no other function after addr.

返回类型:

Function or None

floor_func(addr)[源代码]

Return the function who has the greatest address that is less than or equal to addr.

参数:

addr (int) -- The address to query.

返回:

A Function instance, or None if there is no other function before addr.

返回类型:

Function or None

query(query, check_previous_names=False)[源代码]

Query for a function using selectors to disambiguate. Supported variations: :rtype: Function | None

::<name> Function <name> in the main object ::<addr>::<name> Function <name> at <addr> ::<obj>::<name> Function <name> in <obj>

参数:
  • query (str)

  • check_previous_names (bool)

返回类型:

Function | None

function(addr=None, name=None, check_previous_names=False, create=False, syscall=False, plt=None)[源代码]

Get a function object from the function manager.

Pass either addr or name with the appropriate values.

参数:
  • addr (int) -- Address of the function.

  • name (str) -- Name of the function.

  • create (bool) -- Whether to create the function or not if the function does not exist.

  • syscall (bool) -- True to create the function as a syscall, False otherwise.

  • plt (bool or None) -- True to find the PLT stub, False to find a non-PLT stub, None to disable this restriction.

返回:

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

返回类型:

Function or None

dbg_draw(prefix='dbg_function_')[源代码]
rebuild_callgraph()[源代码]
class angr.knowledge_plugins.functions.function.Function(function_manager, addr, name=None, syscall=None, is_simprocedure=None, binary_name=None, is_plt=None, returning=None, alignment=False)[源代码]

基类:Serializable

A representation of a function and various information about it.

参数:
  • is_simprocedure (bool | None)

  • is_plt (bool | None)

__init__(function_manager, addr, name=None, syscall=None, is_simprocedure=None, binary_name=None, is_plt=None, returning=None, alignment=False)[源代码]

Function constructor. If the optional parameters are not provided, they will be automatically determined upon the creation of a Function object.

参数:
  • addr -- The address of the function.

  • is_simprocedure (bool | None)

  • is_plt (bool | None)

The following parameters are optional.

参数:
  • name (str) -- The name of the function.

  • syscall (bool) -- Whether this function is a syscall or not.

  • is_simprocedure (bool) -- Whether this function is a SimProcedure or not.

  • binary_name (str) -- Name of the binary where this function is.

  • is_plt (bool) -- If this function is a PLT entry.

  • returning (bool) -- If this function returns.

  • alignment (bool) -- If this function acts as an alignment filler. Such functions usually only contain nops.

transition_graph
normalized
addr
startpoint
is_alignment
bp_on_stack
retaddr_on_stack
sp_delta
prototype: SimTypeFunction | None
prototype_libname: str | None
is_prototype_guessed: bool
prepared_registers
prepared_stack_variables
registers_read_afterwards
info
tags
ran_cca
is_syscall
is_simprocedure
is_plt
is_default_name
previous_names
from_signature
binary_name
calling_convention: SimCC | None
property alignment
property name
property project
property returning
property blocks

An iterator of all local blocks in the current function.

返回:

angr.lifter.Block instances.

property cyclomatic_complexity

The cyclomatic complexity of the function.

Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code. It is computed using the formula: M = E - N + 2P, where E = the number of edges in the graph, N = the number of nodes in the graph, P = the number of connected components.

The cyclomatic complexity value is lazily computed and cached for future use. Initially this value is None until it is computed for the first time

返回:

The cyclomatic complexity of the function.

返回类型:

int

property xrefs

An iterator of all xrefs of the current function.

返回:

angr.knowledge_plugins.xrefs.xref.XRef instances.

property block_addrs

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

返回:

block addresses.

property block_addrs_set

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

返回:

A set of block addresses.

返回类型:

set

get_block(addr, size=None, byte_string=None)[源代码]

Getting a block out of the current function.

参数:
  • addr (int) -- The address of the block.

  • size (int) -- The size of the block. This is optional. If not provided, angr will load

  • byte_string (Optional[bytes])

返回:

get_block_size(addr)[源代码]
返回类型:

int | None

参数:

addr (int)

property nodes: Iterable[CodeNode]
get_node(addr)[源代码]
返回类型:

BlockNode | None

property has_unresolved_jumps
property has_unresolved_calls
property operations

All of the operations that are done by this functions.

property code_constants

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

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]
参数:

cmsg

Return Function:

The function instantiated out of the cmsg data.

string_references(minimum_length=2)[源代码]

All of the constant string references used by this function.

参数:

minimum_length -- The minimum length of strings to find (default is 1)

返回:

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

property local_runtime_values

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

返回:

a set of constants

property num_arguments
property endpoints
property endpoints_with_type
property ret_sites
property jumpout_sites
property retout_sites
property callout_sites
property size
property binary

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

property offset: int

the function's binary offset (i.e., non-rebased address)

Type:

return

property symbol: None | Symbol

the function's Symbol, if any

Type:

return

property pseudocode: str

the function's pseudocode

Type:

return

add_jumpout_site(node)[源代码]

Add a custom jumpout site.

参数:

node (CodeNode) -- The address of the basic block that control flow leaves during this transition.

返回:

None

add_retout_site(node)[源代码]

Add a custom retout site.

Retout (returning to outside of the function) sites are very rare. It mostly occurs during CFG recovery when we incorrectly identify the beginning of a function in the first iteration, and then correctly identify that function later in the same iteration (function alignments can lead to this bizarre case). We will mark all edges going out of the header of that function as a outside edge, because all successors now belong to the incorrectly-identified function. This identification error will be fixed in the second iteration of CFG recovery. However, we still want to keep track of jumpouts/retouts during the first iteration so other logic in CFG recovery still work.

参数:

node (CodeNode) -- The address of the basic block that control flow leaves the current function after a call.

返回:

None

mark_nonreturning_calls_endpoints()[源代码]

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

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

返回:

None

get_call_sites()[源代码]

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

返回类型:

Iterable[int]

返回:

A view of the addresses of the blocks that end in calls.

get_call_target(callsite_addr)[源代码]

Get the target of a call.

参数:

callsite_addr -- The address of a basic block that ends in a call.

返回:

The target of said call, or None if callsite_addr is not a callsite.

get_call_return(callsite_addr)[源代码]

Get the hypothetical return address of a call.

参数:

callsite_addr -- The address of the basic block that ends in a call.

返回:

The likely return target of said call, or None if callsite_addr is not a callsite.

property graph

Get a local transition graph. A local transition graph is a transition graph that only contains nodes that belong to the current function. All edges, except for the edges going out from the current function or coming from outside the current function, are included.

The generated graph is cached in self._local_transition_graph.

返回:

A local transition graph.

返回类型:

networkx.DiGraph

graph_ex(exception_edges=True)[源代码]

Get a local transition graph with a custom configuration. A local transition graph is a transition graph that only contains nodes that belong to the current function. This method allows user to exclude certain types of edges together with the nodes that are only reachable through such edges, such as exception edges.

The generated graph is not cached.

参数:

exception_edges (bool) -- Should exception edges and the nodes that are only reachable through exception edges be kept.

返回:

A local transition graph with a special configuration.

返回类型:

networkx.DiGraph

transition_graph_ex(exception_edges=True)[源代码]

Get a transition graph with a custom configuration. This method allows user to exclude certain types of edges together with the nodes that are only reachable through such edges, such as exception edges.

The generated graph is not cached.

参数:

exception_edges (bool) -- Should exception edges and the nodes that are only reachable through exception edges be kept.

返回:

A local transition graph with a special configuration.

返回类型:

networkx.DiGraph

subgraph(ins_addrs)[源代码]

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

参数:

ins_addrs (iterable) -- A collection of instruction addresses that should be included in the subgraph.

Return networkx.DiGraph:

A subgraph.

instruction_size(insn_addr)[源代码]

Get the size of the instruction specified by insn_addr.

参数:

insn_addr (int) -- Address of the instruction

Return int:

Size of the instruction in bytes, or None if the instruction is not found.

addr_to_instruction_addr(addr)[源代码]

Obtain the address of the instruction that covers @addr.

参数:

addr (int) -- An address.

返回:

Address of the instruction that covers @addr, or None if this addr is not covered by any instruction of this function.

返回类型:

int or None

dbg_print()[源代码]

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

dbg_draw(filename)[源代码]

Draw the graph and save it to a PNG file.

property arguments
property has_return
property callable
normalize()[源代码]

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

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

返回:

None

find_declaration(ignore_binary_name=False, binary_name_hint=None)[源代码]

Find the most likely function declaration from the embedded collection of prototypes, set it to self.prototype, and update self.calling_convention with the declaration.

参数:
  • ignore_binary_name (bool) -- Do not rely on the executable or library where the function belongs to determine its source library. This is useful when working on statically linked binaries (because all functions will belong to the main executable). We will search for all libraries in angr to find the first declaration match.

  • binary_name_hint (Optional[str]) -- Substring of the library name where this function might be originally coming from. Useful for FLIRT-identified functions in statically linked binaries.

返回类型:

bool

返回:

True if a declaration is found and self.prototype and self.calling_convention are updated. False if we fail to find a matching function declaration, in which case self.prototype or self.calling_convention will be kept untouched.

property demangled_name
get_unambiguous_name(display_name=None)[源代码]

Get a disambiguated function name.

参数:

display_name (Optional[str]) -- Name to display, otherwise the function name.

返回类型:

str

返回:

The function name in the form: ::<name> when the function binary is the main object. ::<obj>::<name> when the function binary is not the main object. ::<addr>::<name> when the function binary is an unnamed non-main object, or when multiple functions with

the same name are defined in the function binary.

apply_definition(definition, calling_convention=None)[源代码]
返回类型:

None

参数:
functions_reachable()[源代码]
返回类型:

set[Function]

返回:

The set of all functions that can be reached from the function represented by self.

copy()[源代码]
pp(**kwargs)[源代码]

Pretty-print the function disassembly.

class angr.knowledge_plugins.functions.function_parser.FunctionParser[源代码]

基类:object

The implementation of the serialization methods for the <Function> class.

static serialize(function)[源代码]

:return :

static parse_from_cmsg(cmsg, function_manager=None, project=None, all_func_addrs=None)[源代码]
参数:

cmsg -- The data to instantiate the <Function> from.

Return Function:

class angr.knowledge_plugins.functions.soot_function.SootFunction(function_manager, addr, name=None, syscall=None)[源代码]

基类:Function

A representation of a function and various information about it.

__init__(function_manager, addr, name=None, syscall=None)[源代码]

Function constructor for Soot

参数:
  • addr -- The address of the function.

  • name -- (Optional) The name of the function.

  • syscall -- (Optional) Whether this function is a syscall or not.

transition_graph
normalized
previous_names
addr
is_syscall
is_plt
is_simprocedure
binary_name
bp_on_stack
retaddr_on_stack
sp_delta
calling_convention: SimCC | None
prototype: SimTypeFunction | None
prepared_registers
prepared_stack_variables
registers_read_afterwards
startpoint
info
tags
normalize()[源代码]

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

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

返回:

None

from_signature
is_alignment
is_default_name
is_prototype_guessed: bool
prototype_libname: str | None
ran_cca
class angr.knowledge_plugins.variables.VariableManager(kb)[源代码]

基类:KnowledgeBasePlugin

Manage variables.

__init__(kb)[源代码]
has_function_manager(key)[源代码]
返回类型:

bool

参数:

key (int)

get_function_manager(func_addr)[源代码]
返回类型:

VariableManagerInternal

initialize_variable_names()[源代码]
返回类型:

None

get_variable_accesses(variable, same_name=False)[源代码]

Get a list of all references to the given variable.

参数:
  • variable (SimVariable) -- The variable.

  • same_name (bool) -- Whether to include all variables with the same variable name, or just based on the variable identifier.

返回类型:

list[VariableAccess]

返回:

All references to the variable.

copy()[源代码]
static convert_variable_list(vlist, manager)[源代码]
参数:
load_from_dwarf(cu_list=None)[源代码]
参数:

cu_list (list[CompilationUnit] | None)

class angr.knowledge_plugins.variables.VariableType[源代码]

基类:object

Describes variable types.

REGISTER = 0
MEMORY = 1
class angr.knowledge_plugins.variables.variable_access.VariableAccessSort[源代码]

基类:object

Provides enums for variable access types.

WRITE = 0
READ = 1
REFERENCE = 2
class angr.knowledge_plugins.variables.variable_access.VariableAccess(variable, access_type, location, offset, atom_hash=None)[源代码]

基类:Serializable

Describes a variable access.

__init__(variable, access_type, location, offset, atom_hash=None)[源代码]
variable: SimVariable
access_type: int
location: CodeLocation
offset: int | None
atom_hash: int | None
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, variable_by_ident=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:
返回:

A unserialized class object.

返回类型:

cls

class angr.knowledge_plugins.variables.variable_manager.VariableType[源代码]

基类:object

Describes variable types.

REGISTER = 0
MEMORY = 1
class angr.knowledge_plugins.variables.variable_manager.LiveVariables(register_region, stack_region)[源代码]

基类:object

A collection of live variables at a program point.

__init__(register_region, stack_region)[源代码]
register_region
stack_region
class angr.knowledge_plugins.variables.variable_manager.VariableManagerInternal(manager, func_addr=None)[源代码]

基类:Serializable

Manage variables for a function. It is meant to be used internally by VariableManager, but it's common to be given a reference to one in response to a query for "the variables for a given function". Maybe a better name would be "VariableManagerScope".

__init__(manager, func_addr=None)[源代码]
set_manager(manager)[源代码]
参数:

manager (VariableManager)

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, variable_manager=None, func_addr=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

next_variable_ident(sort)[源代码]
add_variable(sort, start, variable)[源代码]
参数:

variable (SimVariable)

set_variable(sort, start, variable)[源代码]
参数:

variable (SimVariable)

write_to(variable, offset, location, overwrite=False, atom=None)[源代码]
read_from(variable, offset, location, overwrite=False, atom=None)[源代码]
reference_at(variable, offset, location, overwrite=False, atom=None)[源代码]
record_variable(location, variable, offset, overwrite=False, atom=None)[源代码]
参数:

location (CodeLocation)

remove_variable_by_atom(location, variable, atom)[源代码]
参数:
make_phi_node(block_addr, *variables)[源代码]

Create a phi variable for variables at block block_addr.

参数:
  • block_addr (int) -- The address of the current block.

  • variables -- Variables that the phi variable represents.

返回:

The created phi variable.

set_live_variables(addr, register_region, stack_region)[源代码]
find_variables_by_insn(ins_addr, sort)[源代码]
is_variable_used_at(variable, loc)[源代码]
返回类型:

bool

参数:
find_variable_by_stmt(block_addr, stmt_idx, sort, block_idx=None)[源代码]
参数:

block_idx (int | None)

find_variables_by_stmt(block_addr, stmt_idx, sort, block_idx=None)[源代码]
返回类型:

list[tuple[SimVariable, int]]

参数:
  • block_addr (int)

  • stmt_idx (int)

  • sort (str)

  • block_idx (int | None)

find_variable_by_atom(block_addr, stmt_idx, atom, block_idx=None)[源代码]
参数:

block_idx (int | None)

find_variables_by_atom(block_addr, stmt_idx, atom, block_idx=None)[源代码]
返回类型:

set[tuple[SimVariable, int]]

参数:

block_idx (int | None)

find_variables_by_stack_offset(offset)[源代码]
返回类型:

set[SimVariable]

参数:

offset (int)

find_variables_by_register(reg)[源代码]
返回类型:

set[SimVariable]

参数:

reg (str | int)

get_variable_accesses(variable, same_name=False)[源代码]
返回类型:

list[VariableAccess]

参数:
get_variables(sort=None, collapse_same_ident=False)[源代码]

Get a list of variables.

参数:
  • sort -- Sort of the variable to get.

  • collapse_same_ident -- Whether variables of the same identifier should be collapsed or not.

返回:

A list of variables.

get_unified_variables(sort=None)[源代码]

Get a list of unified variables.

参数:

sort -- Sort of the variable to get.

返回:

A list of variables.

get_global_variables(addr)[源代码]

Get global variable by the address of the variable.

参数:

addr (int) -- Address of the variable.

返回:

A set of variables or an empty set if no variable exists.

is_phi_variable(var)[源代码]

Test if var is a phi variable.

参数:

var (SimVariable) -- The variable instance.

返回:

True if var is a phi variable, False otherwise.

返回类型:

bool

get_phi_subvariables(var)[源代码]

Get sub-variables that phi variable var represents.

参数:

var (SimVariable) -- The variable instance.

返回:

A set of sub-variables, or an empty set if var is not a phi variable.

返回类型:

set

get_phi_variables(block_addr)[源代码]

Get a dict of phi variables and their corresponding variables.

参数:

block_addr (int) -- Address of the block.

返回:

A dict of phi variables of an empty dict if there are no phi variables at the block.

返回类型:

dict

get_variables_without_writes()[源代码]

Get all variables that have never been written to.

返回类型:

list[SimVariable]

返回:

A list of variables that are never written to.

input_variables(exclude_specials=True)[源代码]

Get all variables that have never been written to.

返回:

A list of variables that are never written to.

参数:

exclude_specials (bool)

assign_variable_names(labels=None, types=None)[源代码]

Assign default names to all SSA variables.

参数:

labels -- Known labels in the binary.

返回:

None

assign_unified_variable_names(labels=None, arg_names=None, reset=False, func_blocks=None)[源代码]

Assign default names to all unified variables. If func_blocks is provided, we will find out variables that are only ever written to in Phi assignments and never used elsewhere, and put these variables at the end of the sorted list. These variables are likely completely removed during the dephication process.

参数:
  • labels -- Known labels in the binary.

  • arg_names (Optional[list[str]]) -- Known argument names.

  • reset (bool) -- Reset all variable names or not.

  • func_blocks (Optional[list[Block]]) -- A list of function blocks of the function where these variables are accessed.

返回类型:

None

set_variable_type(var, ty, name=None, override_bot=True, all_unified=False, mark_manual=False)[源代码]
返回类型:

None

参数:
get_variable_type(var)[源代码]
返回类型:

SimType | None

remove_types()[源代码]
unify_variables()[源代码]

Map SSA variables to a unified variable. Fill in self._unified_variables.

返回类型:

None

set_unified_variable(variable, unified)[源代码]

Set the unified variable for a given SSA variable.

参数:
返回类型:

None

返回:

None

unified_variable(variable)[源代码]

Return the unified variable for a given SSA variable,

参数:

variable (SimVariable) -- The SSA variable.

返回类型:

SimVariable | None

返回:

The unified variable, or None if there is no such SSA variable.

class angr.knowledge_plugins.variables.variable_manager.VariableManager(kb)[源代码]

基类:KnowledgeBasePlugin

Manage variables.

__init__(kb)[源代码]
has_function_manager(key)[源代码]
返回类型:

bool

参数:

key (int)

get_function_manager(func_addr)[源代码]
返回类型:

VariableManagerInternal

initialize_variable_names()[源代码]
返回类型:

None

get_variable_accesses(variable, same_name=False)[源代码]

Get a list of all references to the given variable.

参数:
  • variable (SimVariable) -- The variable.

  • same_name (bool) -- Whether to include all variables with the same variable name, or just based on the variable identifier.

返回类型:

list[VariableAccess]

返回:

All references to the variable.

copy()[源代码]
static convert_variable_list(vlist, manager)[源代码]
参数:
load_from_dwarf(cu_list=None)[源代码]
参数:

cu_list (list[CompilationUnit] | None)

class angr.knowledge_plugins.debug_variables.DebugVariableContainer[源代码]

基类:object

Variable tree for variables with same name to lock up which variable is visible at a given program counter address.

__init__()[源代码]

It is recommended to use DebugVariableManager.add_variable() instead

from_pc(pc)[源代码]

Returns the visible variable (if any) for a given pc address.

返回类型:

Variable

class angr.knowledge_plugins.debug_variables.DebugVariable(low_pc, high_pc, cle_variable)[源代码]

基类:DebugVariableContainer

变量:
  • low_pc -- Start of the visibility scope of the variable as program counter address (rebased)

  • high_pc -- End of the visibility scope of the variable as program counter address (rebased)

  • cle_variable -- Original variable from cle

参数:
  • low_pc (int)

  • high_pc (int)

  • cle_variable (Variable)

__init__(low_pc, high_pc, cle_variable)[源代码]

It is recommended to use DebugVariableManager.add_variable() instead

参数:
from_pc(pc)[源代码]

Returns the visible variable (if any) for a given pc address.

返回类型:

Variable

contains(dvar)[源代码]
返回类型:

bool

参数:

dvar (DebugVariable)

test_unsupported_overlap(dvar)[源代码]

Test for an unsupported overlapping

参数:

dvar (DebugVariable) -- Second DebugVariable to compare with

返回类型:

bool

返回:

True if there is an unsupported overlapping

class angr.knowledge_plugins.debug_variables.DebugVariableManager(kb)[源代码]

基类:KnowledgeBasePlugin

Structure to manage and access variables with different visibility scopes.

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

from_name_and_pc(var_name, pc_addr)[源代码]

Get a variable from its string in the scope of pc.

返回类型:

Variable

参数:
  • var_name (str)

  • pc_addr (int)

from_name(var_name)[源代码]

Get the variable container for all variables named var_name

参数:

var_name (str) -- name for a variable

返回类型:

DebugVariableContainer

add_variable(cle_var, low_pc, high_pc)[源代码]

Add/load a variable

参数:
  • cle_variable -- The variable to add

  • low_pc (int) -- Start of the visibility scope of the variable as program counter address (rebased)

  • high_pc (int) -- End of the visibility scope of the variable as program counter address (rebased)

  • cle_var (Variable)

add_variable_list(vlist, low_pc, high_pc)[源代码]

Add all variables in a list with the same visibility range

参数:
  • vlist (list[Variable]) -- A list of cle variables to add

  • low_pc (int) -- Start of the visibility scope as program counter address (rebased)

  • high_pc (int) -- End of the visibility scope as program counter address (rebased)

load_from_dwarf(elf_object=None, cu=None)[源代码]

Automatically load all variables (global/local) from the DWARF debugging info

参数:
  • elf_object (Optional[ELF]) -- Optional, when only one elf object should be considered (e.g. p.loader.main_object)

  • cu (Optional[CompilationUnit]) -- Optional, when only one compilation unit should be considered

class angr.knowledge_plugins.structured_code.StructuredCodeManager(kb)[源代码]

基类:KnowledgeBasePlugin

A knowledge base plugin to store structured code generator results.

__init__(kb)[源代码]
discard(key)[源代码]
available_flavors(item)[源代码]
copy()[源代码]
class angr.knowledge_plugins.key_definitions.Definition(atom, codeloc, dummy=False, tags=None)[源代码]

基类:Generic[A]

An atom definition.

变量:
  • atom -- The atom being defined.

  • codeloc -- Where this definition is created in the original binary code.

  • dummy -- Tell whether the definition should be considered dummy or not. During simplification by AILment, definitions marked as dummy will not be removed.

  • tags -- A set of tags containing information about the definition gathered during analyses.

参数:
__init__(atom, codeloc, dummy=False, tags=None)[源代码]
参数:
atom: TypeVar(A, bound= Atom)
codeloc: CodeLocation
dummy: bool
tags
property offset: int
property size: int
matches(**kwargs)[源代码]

Return whether this definition has certain characteristics.

返回类型:

bool

class angr.knowledge_plugins.key_definitions.DerefSize(value)[源代码]

基类:Enum

An enum for specialized kinds of dereferences

NULL_TERMINATE - Dereference until the first byte which could be a literal null. Return a value including the

terminator.

NULL_TERMINATE = 1
class angr.knowledge_plugins.key_definitions.KeyDefinitionManager(kb)[源代码]

基类:KnowledgeBasePlugin

KeyDefinitionManager manages and caches reaching definition models for each function.

For each function, by default we cache the entire reaching definitions model with observed results at the following locations: - Before each call instruction: ('insn', address of the call instruction, OP_BEFORE) - After returning from each call: ('node', address of the block that ends with a call, OP_AFTER)

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

has_model(func_addr)[源代码]
参数:

func_addr (int)

get_model(func_addr)[源代码]
参数:

func_addr (int)

copy()[源代码]
返回类型:

KeyDefinitionManager

class angr.knowledge_plugins.key_definitions.LiveDefinitions(arch, track_tmps=False, canonical_size=8, registers=None, stack=None, memory=None, heap=None, tmps=None, others=None, register_uses=None, stack_uses=None, heap_uses=None, memory_uses=None, tmp_uses=None, other_uses=None, element_limit=5, merge_into_tops=True)[源代码]

基类:object

A LiveDefinitions instance contains definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.

参数:
INITIAL_SP_32BIT = 2147418112
INITIAL_SP_64BIT = 140737488289792
__init__(arch, track_tmps=False, canonical_size=8, registers=None, stack=None, memory=None, heap=None, tmps=None, others=None, register_uses=None, stack_uses=None, heap_uses=None, memory_uses=None, tmp_uses=None, other_uses=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
project: Project | None
arch
track_tmps
registers: MultiValuedMemory
stack: MultiValuedMemory
memory: MultiValuedMemory
heap: MultiValuedMemory
tmps: dict[int, set[Definition]]
others: dict[Atom, MultiValues]
register_uses
stack_uses
heap_uses
memory_uses
tmp_uses: dict[int, set[CodeLocation]]
other_uses
uses_by_codeloc: dict[CodeLocation, set[Definition]]
property register_definitions
property stack_definitions
property memory_definitions
property heap_definitions
copy(discard_tmpdefs=False)[源代码]
返回类型:

LiveDefinitions

reset_uses()[源代码]
static top(bits)[源代码]

Get a TOP value.

参数:

bits (int) -- Width of the TOP value (in bits).

返回:

The TOP value.

static is_top(expr)[源代码]

Check if the given expression is a TOP value.

参数:

expr -- The given expression.

返回类型:

bool

返回:

True if the expression is TOP, False otherwise.

stack_address(offset)[源代码]
返回类型:

BV

参数:

offset (int)

static is_stack_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_stack_offset(addr, had_stack_base=False)[源代码]
返回类型:

int | None

参数:

addr (Base)

static annotate_with_def(symvar, definition)[源代码]
参数:
返回类型:

TypeVar(MVType, bound= BV | FP)

返回:

static extract_defs(symvar)[源代码]
返回类型:

Generator[Definition]

参数:

symvar (Base)

static extract_defs_from_annotations(annos)[源代码]
返回类型:

set[Definition]

参数:

annos (Iterable[Annotation])

static extract_defs_from_mv(mv)[源代码]
返回类型:

Generator[Definition]

参数:

mv (MultiValues)

get_sp()[源代码]

Return the concrete value contained by the stack pointer.

返回类型:

int

get_sp_offset()[源代码]

Return the offset of the stack pointer.

返回类型:

int | None

get_stack_address(offset)[源代码]
返回类型:

int | None

参数:

offset (Base)

stack_offset_to_stack_addr(offset)[源代码]
返回类型:

int

merge(*others)[源代码]
返回类型:

tuple[LiveDefinitions, bool]

参数:

others (LiveDefinitions)

compare(other)[源代码]
返回类型:

bool

参数:

other (LiveDefinitions)

kill_definitions(atom)[源代码]

Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification.

参数:

atom (Atom)

返回类型:

None

返回:

None

kill_and_add_definition(atom, code_loc, data, dummy=False, tags=None, endness=None, annotated=False)[源代码]
返回类型:

MultiValues | None

参数:
add_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_use_by_def(definition, code_loc, expr=None)[源代码]
返回类型:

None

参数:
get_definitions(thing)[源代码]
返回类型:

set[Definition[Atom]]

参数:

thing (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | MultiValues)

get_tmp_definitions(tmp_idx)[源代码]
返回类型:

set[Definition]

参数:

tmp_idx (int)

get_register_definitions(reg_offset, size)[源代码]
返回类型:

set[Definition]

参数:
get_stack_values(stack_offset, size, endness)[源代码]
返回类型:

MultiValues | None

参数:
  • stack_offset (int)

  • size (int)

  • endness (str)

get_stack_definitions(stack_offset, size)[源代码]
返回类型:

set[Definition]

参数:
  • stack_offset (int)

  • size (int)

get_heap_definitions(heap_addr, size)[源代码]
返回类型:

set[Definition]

参数:
get_memory_definitions(addr, size)[源代码]
返回类型:

set[Definition]

参数:
get_definitions_from_atoms(**kwargs)
get_value_from_definition(**kwargs)
get_one_value_from_definition(**kwargs)
get_concrete_value_from_definition(**kwargs)
get_value_from_atom(**kwargs)
get_one_value_from_atom(**kwargs)
get_concrete_value_from_atom(**kwargs)
get_values(spec)[源代码]
返回类型:

MultiValues | None

参数:

spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])

get_one_value(spec, strip_annotations=False)[源代码]
返回类型:

BV | None

参数:
get_concrete_value(spec, cast_to=<class 'int'>)[源代码]
返回类型:

int | bytes | None

参数:
add_register_use(reg_offset, size, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_register_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_heap_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_heap_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_memory_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_memory_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use(atom, code_loc)[源代码]
返回类型:

None

参数:
add_tmp_use_by_def(def_, code_loc)[源代码]
返回类型:

None

参数:
deref(pointer, size, endness=Endness.BE)[源代码]
static is_heap_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_heap_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

heap_address(offset)[源代码]
返回类型:

BV

参数:

offset (int | HeapAddress)

class angr.knowledge_plugins.key_definitions.ReachingDefinitionsModel(func_addr=None, track_liveness=True)[源代码]

基类:object

Models the definitions, uses, and memory of a ReachingDefinitionState object

参数:
  • func_addr (int | None)

  • track_liveness (bool)

__init__(func_addr=None, track_liveness=True)[源代码]
参数:
  • func_addr (int | None)

  • track_liveness (bool)

add_def(d)[源代码]
返回类型:

None

参数:

d (Definition)

kill_def(d)[源代码]
返回类型:

None

参数:

d (Definition)

at_new_stmt(codeloc)[源代码]
返回类型:

None

参数:

codeloc (CodeLocation)

at_new_block(code_loc, pred_codelocs)[源代码]
返回类型:

None

参数:
make_liveness_snapshot()[源代码]
返回类型:

None

find_defs_at(code_loc, op=ObservationPointType.OP_BEFORE)[源代码]
返回类型:

set[Definition]

参数:
get_defs(atom, code_loc, op)[源代码]
返回类型:

set[Definition]

参数:
copy()[源代码]
返回类型:

ReachingDefinitionsModel

merge(model)[源代码]
参数:

model (ReachingDefinitionsModel)

get_observation_by_insn(ins_addr, kind)[源代码]
返回类型:

LiveDefinitions | None

参数:
get_observation_by_node(node_addr, kind, node_idx=None)[源代码]
返回类型:

LiveDefinitions | None

参数:
get_observation_by_stmt(arg1, arg2, arg3=None, *, block_idx=None)[源代码]
get_observation_by_exit(node_addr, stmt_idx, src_node_idx=None)[源代码]
返回类型:

LiveDefinitions | None

参数:
  • node_addr (int)

  • stmt_idx (int)

  • src_node_idx (int | None)

class angr.knowledge_plugins.key_definitions.Uses(uses_by_definition=None, uses_by_location=None)[源代码]

基类:object

Describes uses (including the use location and the use expression) for definitions.

参数:
__init__(uses_by_definition=None, uses_by_location=None)[源代码]
参数:
add_use(definition, codeloc, expr=None)[源代码]

Add a use for a given definition.

参数:
  • definition (Definition) -- The definition that is used.

  • codeloc (CodeLocation) -- The code location where the use occurs.

  • expr (Optional[Any]) -- The expression that uses the specified definition at this location.

get_uses(definition)[源代码]

Retrieve the uses of a given definition.

参数:

definition (Definition) -- The definition for which we get the uses.

返回类型:

set[CodeLocation]

get_uses_with_expr(definition)[源代码]

Retrieve the uses and the corresponding expressions of a given definition.

参数:

definition (Definition) -- The definition for which we get the uses and the corresponding expressions.

返回类型:

set[tuple[CodeLocation, Optional[Any]]]

remove_use(definition, codeloc, expr=None)[源代码]

Remove one use of a given definition.

参数:
  • definition (Definition) -- The definition of which to remove the uses.

  • codeloc (CodeLocation) -- The code location where the use is.

  • expr (Optional[Any]) -- The expression that uses the definition at the given location.

返回类型:

None

返回:

None

remove_uses(definition)[源代码]

Remove all uses of a given definition.

参数:

definition (Definition) -- The definition of which to remove the uses.

返回:

None

get_uses_by_location(codeloc, exprs=False)[源代码]

Retrieve all definitions that are used at a given location.

参数:
返回类型:

set[Definition] | set[tuple[Definition, Optional[Any]]]

返回:

A set of definitions that are used at the given location.

get_uses_by_insaddr(ins_addr, exprs=False)[源代码]

Retrieve all definitions that are used at a given location specified by the instruction address.

参数:
  • ins_addr (int) -- The instruction address.

  • exprs (bool)

返回类型:

set[Definition] | set[tuple[Definition, Optional[Any]]]

返回:

A set of definitions that are used at the given location.

copy()[源代码]

Copy the instance.

返回类型:

Uses

返回:

Return a new <Uses> instance containing the same data.

merge(other)[源代码]

Merge an instance of <Uses> into the current instance.

参数:

other (Uses) -- The other <Uses> from which the data will be added to the current instance.

返回类型:

bool

返回:

True if any merge occurred, False otherwise

class angr.knowledge_plugins.key_definitions.atoms.AtomKind(value)[源代码]

基类:Enum

An enum indicating the class of an atom

REGISTER = 1
MEMORY = 2
TMP = 3
GUARD = 4
CONSTANT = 5
class angr.knowledge_plugins.key_definitions.atoms.Atom(size)[源代码]

基类:object

This class represents a data storage location manipulated by IR instructions.

It could either be a Tmp (temporary variable), a Register, a MemoryLocation.

__init__(size)[源代码]
参数:

size -- The size of the atom in bytes

size
property bits: int
static from_ail_expr(expr, arch, full_reg=False)[源代码]
返回类型:

Register

参数:
static from_argument(argument, arch, full_reg=False, sp=None)[源代码]

Instantiate an Atom from a given argument.

参数:
  • argument (SimFunctionArgument) -- The argument to create a new atom from.

  • arch (Arch) -- The argument representing archinfo architecture for argument.

  • full_reg -- Whether to return an atom indicating the entire register if the argument only specifies a slice of the register.

  • sp (Optional[int]) -- The current stack offset. Optional. Only used when argument is a SimStackArg.

返回类型:

Register | MemoryLocation

static reg(thing, size=None, arch=None)[源代码]

Create a Register atom.

参数:
  • thing (str | RegisterOffset) -- The register offset (e.g., project.arch.registers["rax"][0]) or the register name (e.g., "rax").

  • size (Optional[int]) -- Size of the register atom. Must be provided when creating the atom using a register offset.

  • arch (Optional[Arch]) -- The architecture. Must be provided when creating the atom using a register name.

返回类型:

Register

返回:

The Register Atom object.

static register(thing, size=None, arch=None)

Create a Register atom.

参数:
  • thing (str | RegisterOffset) -- The register offset (e.g., project.arch.registers["rax"][0]) or the register name (e.g., "rax").

  • size (Optional[int]) -- Size of the register atom. Must be provided when creating the atom using a register offset.

  • arch (Optional[Arch]) -- The architecture. Must be provided when creating the atom using a register name.

返回类型:

Register

返回:

The Register Atom object.

static mem(addr, size, endness=None)[源代码]

Create a MemoryLocation atom,

参数:
  • addr (SpOffset | HeapAddress | int) -- The memory location. Can be an SpOffset for stack variables, an int for global memory variables, or a HeapAddress for items on the heap.

  • size (int) -- Size of the atom.

  • endness (Optional[str]) -- Optional, either "Iend_LE" or "Iend_BE".

返回类型:

MemoryLocation

返回:

The MemoryLocation Atom object.

static memory(addr, size, endness=None)

Create a MemoryLocation atom,

参数:
  • addr (SpOffset | HeapAddress | int) -- The memory location. Can be an SpOffset for stack variables, an int for global memory variables, or a HeapAddress for items on the heap.

  • size (int) -- Size of the atom.

  • endness (Optional[str]) -- Optional, either "Iend_LE" or "Iend_BE".

返回类型:

MemoryLocation

返回:

The MemoryLocation Atom object.

class angr.knowledge_plugins.key_definitions.atoms.GuardUse(target)[源代码]

基类:Atom

Implements a guard use.

__init__(target)[源代码]
参数:

size -- The size of the atom in bytes

target
class angr.knowledge_plugins.key_definitions.atoms.ConstantSrc(value, size)[源代码]

基类:Atom

Represents a constant.

参数:
__init__(value, size)[源代码]
参数:
  • size (int) -- The size of the atom in bytes

  • value (int)

value: int
class angr.knowledge_plugins.key_definitions.atoms.Tmp(tmp_idx, size)[源代码]

基类:Atom

Represents a variable used by the IR to store intermediate values.

参数:
__init__(tmp_idx, size)[源代码]
参数:
  • size (int) -- The size of the atom in bytes

  • tmp_idx (int)

tmp_idx
class angr.knowledge_plugins.key_definitions.atoms.Register(reg_offset, size, arch=None)[源代码]

基类:Atom

Represents a given CPU register.

As an IR abstracts the CPU design to target different architectures, registers are represented as a separated memory space. Thus a register is defined by its offset from the base of this memory and its size.

变量:
  • reg_offset (int) -- The offset from the base to define its place in the memory bloc.

  • size (int) -- The size, in number of bytes.

参数:
__init__(reg_offset, size, arch=None)[源代码]
参数:
reg_offset
arch
property name: str
class angr.knowledge_plugins.key_definitions.atoms.VirtualVariable(varid, size, category, oident=None)[源代码]

基类:Atom

Represents a virtual variable.

参数:
  • varid (int)

  • size (int)

  • category (ailment.Expr.VirtualVariableCategory)

  • oident (str | int | None)

__init__(varid, size, category, oident=None)[源代码]
参数:
varid
category
oident
property was_reg: bool
property was_stack: bool
property was_parameter: bool
property was_tmp: bool
property reg_offset: int | None
property stack_offset: int | None
property tmp_idx: int | None
class angr.knowledge_plugins.key_definitions.atoms.MemoryLocation(addr, size, endness=None)[源代码]

基类:Atom

Represents a memory slice.

It is characterized by its address and its size.

参数:
__init__(addr, size, endness=None)[源代码]
参数:
  • addr (int) -- The address of the beginning memory location slice.

  • size (int) -- The size of the represented memory location, in bytes.

  • endness (str | None)

addr: SpOffset | int | BV
endness
property is_on_stack: bool

True if this memory location is located on the stack.

property symbolic: bool
class angr.knowledge_plugins.key_definitions.constants.ObservationPointType(value)[源代码]

基类:IntEnum

Enum to replace the previously generic constants This makes it possible to annotate where they are expected by typing something as ObservationPointType instead of Literal[0,1]

OP_BEFORE = 0
OP_AFTER = 1
class angr.knowledge_plugins.key_definitions.definition.DefinitionMatchPredicate(kind=None, bbl_addr=None, ins_addr=None, variable=None, variable_manager=None, stack_offset=None, reg_name=None, heap_offset=None, global_addr=None, tmp_idx=None, const_val=None, extern=None)[源代码]

基类:object

A dataclass indicating several facts which much all must match in order for a definition to match. Largely an internal class; don't worry about this.

参数:
kind: AtomKind | type[Atom] | None = None
bbl_addr: int | None = None
ins_addr: int | None = None
variable: SimVariable | None = None
variable_manager: Union[VariableManagerInternal, None, Literal[False]] = None
stack_offset: int | None = None
reg_name: str | int | None = None
heap_offset: int | None = None
global_addr: int | None = None
tmp_idx: int | None = None
const_val: int | None = None
extern: bool | None = None
static construct(predicate=None, **kwargs)[源代码]
返回类型:

DefinitionMatchPredicate

参数:

predicate (DefinitionMatchPredicate | None)

normalize()[源代码]
matches(defn)[源代码]
返回类型:

bool

参数:

defn (Definition)

__init__(kind=None, bbl_addr=None, ins_addr=None, variable=None, variable_manager=None, stack_offset=None, reg_name=None, heap_offset=None, global_addr=None, tmp_idx=None, const_val=None, extern=None)
参数:
返回类型:

None

class angr.knowledge_plugins.key_definitions.definition.Definition(atom, codeloc, dummy=False, tags=None)[源代码]

基类:Generic[A]

An atom definition.

变量:
  • atom -- The atom being defined.

  • codeloc -- Where this definition is created in the original binary code.

  • dummy -- Tell whether the definition should be considered dummy or not. During simplification by AILment, definitions marked as dummy will not be removed.

  • tags -- A set of tags containing information about the definition gathered during analyses.

参数:
__init__(atom, codeloc, dummy=False, tags=None)[源代码]
参数:
atom: TypeVar(A, bound= Atom)
codeloc: CodeLocation
dummy: bool
tags
property offset: int
property size: int
matches(**kwargs)[源代码]

Return whether this definition has certain characteristics.

返回类型:

bool

class angr.knowledge_plugins.key_definitions.environment.Environment(environment=None)[源代码]

基类:object

Represent the environment in which a program runs. It's a mapping of variable names, to claripy.ast.Base that should contain possible addresses, or <UNDEFINED>, at which their respective values are stored.

Note: The <Environment> object does not store the values associated with variables themselves.

参数:

environment (dict[str | Undefined, set[claripy.ast.Base]] | None)

__init__(environment=None)[源代码]
参数:

environment (dict[str | Undefined, set[Base]] | None)

get(names)[源代码]
参数:

names (set[str]) -- Potential values for the name of the environment variable to get the pointers of.

返回类型:

tuple[set[Base], bool]

返回:

The potential addresses of the values the environment variable can take; And a boolean value telling whether all the names were known of the internal representation (i.e. will be False if one of the queried variable was not found).

set(name, pointers)[源代码]
参数:
  • name (str | Undefined) -- Name of the environment variable to which we will associate the pointers.

  • pointers (set[Base]) -- New addresses where the new values of the environment variable are located.

merge(*others)[源代码]
返回类型:

tuple[Environment, bool]

参数:

others (Environment)

compare(other)[源代码]
返回类型:

bool

参数:

other (Environment)

class angr.knowledge_plugins.key_definitions.heap_address.HeapAddress(value)[源代码]

基类:object

The representation of an address on the heap.

参数:

value (int | Undefined)

__init__(value)[源代码]
参数:

value (int | Undefined)

property value
class angr.knowledge_plugins.key_definitions.key_definition_manager.RDAObserverControl(func_addr, call_site_block_addrs, call_site_ins_addrs)[源代码]

基类:object

参数:
  • func_addr (int)

  • call_site_block_addrs (Iterable[int])

  • call_site_ins_addrs (Iterable[int])

__init__(func_addr, call_site_block_addrs, call_site_ins_addrs)[源代码]
参数:
rda_observe_callback(ob_type, **kwargs)[源代码]
class angr.knowledge_plugins.key_definitions.key_definition_manager.KeyDefinitionManager(kb)[源代码]

基类:KnowledgeBasePlugin

KeyDefinitionManager manages and caches reaching definition models for each function.

For each function, by default we cache the entire reaching definitions model with observed results at the following locations: - Before each call instruction: ('insn', address of the call instruction, OP_BEFORE) - After returning from each call: ('node', address of the block that ends with a call, OP_AFTER)

参数:

kb (KnowledgeBase)

__init__(kb)[源代码]
参数:

kb (KnowledgeBase)

has_model(func_addr)[源代码]
参数:

func_addr (int)

get_model(func_addr)[源代码]
参数:

func_addr (int)

copy()[源代码]
返回类型:

KeyDefinitionManager

class angr.knowledge_plugins.key_definitions.live_definitions.DerefSize(value)[源代码]

基类:Enum

An enum for specialized kinds of dereferences

NULL_TERMINATE - Dereference until the first byte which could be a literal null. Return a value including the

terminator.

NULL_TERMINATE = 1
class angr.knowledge_plugins.key_definitions.live_definitions.DefinitionAnnotation(definition)[源代码]

基类:Annotation

An annotation that attaches a Definition to an AST.

__init__(definition)[源代码]
definition
property relocatable

Returns whether this annotation can be relocated in a simplification.

返回:

True if it can be relocated, false otherwise.

property eliminatable

Returns whether this annotation can be eliminated in a simplification.

返回:

True if eliminatable, False otherwise

class angr.knowledge_plugins.key_definitions.live_definitions.LiveDefinitions(arch, track_tmps=False, canonical_size=8, registers=None, stack=None, memory=None, heap=None, tmps=None, others=None, register_uses=None, stack_uses=None, heap_uses=None, memory_uses=None, tmp_uses=None, other_uses=None, element_limit=5, merge_into_tops=True)[源代码]

基类:object

A LiveDefinitions instance contains definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.

参数:
INITIAL_SP_32BIT = 2147418112
INITIAL_SP_64BIT = 140737488289792
__init__(arch, track_tmps=False, canonical_size=8, registers=None, stack=None, memory=None, heap=None, tmps=None, others=None, register_uses=None, stack_uses=None, heap_uses=None, memory_uses=None, tmp_uses=None, other_uses=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
project: Project | None
arch
track_tmps
registers: MultiValuedMemory
stack: MultiValuedMemory
memory: MultiValuedMemory
heap: MultiValuedMemory
tmps: dict[int, set[Definition]]
others: dict[Atom, MultiValues]
register_uses
stack_uses
heap_uses
memory_uses
tmp_uses: dict[int, set[CodeLocation]]
other_uses
uses_by_codeloc: dict[CodeLocation, set[Definition]]
property register_definitions
property stack_definitions
property memory_definitions
property heap_definitions
copy(discard_tmpdefs=False)[源代码]
返回类型:

LiveDefinitions

reset_uses()[源代码]
static top(bits)[源代码]

Get a TOP value.

参数:

bits (int) -- Width of the TOP value (in bits).

返回:

The TOP value.

static is_top(expr)[源代码]

Check if the given expression is a TOP value.

参数:

expr -- The given expression.

返回类型:

bool

返回:

True if the expression is TOP, False otherwise.

stack_address(offset)[源代码]
返回类型:

BV

参数:

offset (int)

static is_stack_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_stack_offset(addr, had_stack_base=False)[源代码]
返回类型:

int | None

参数:

addr (Base)

static annotate_with_def(symvar, definition)[源代码]
参数:
返回类型:

TypeVar(MVType, bound= BV | FP)

返回:

static extract_defs(symvar)[源代码]
返回类型:

Generator[Definition]

参数:

symvar (Base)

static extract_defs_from_annotations(annos)[源代码]
返回类型:

set[Definition]

参数:

annos (Iterable[Annotation])

static extract_defs_from_mv(mv)[源代码]
返回类型:

Generator[Definition]

参数:

mv (MultiValues)

get_sp()[源代码]

Return the concrete value contained by the stack pointer.

返回类型:

int

get_sp_offset()[源代码]

Return the offset of the stack pointer.

返回类型:

int | None

get_stack_address(offset)[源代码]
返回类型:

int | None

参数:

offset (Base)

stack_offset_to_stack_addr(offset)[源代码]
返回类型:

int

merge(*others)[源代码]
返回类型:

tuple[LiveDefinitions, bool]

参数:

others (LiveDefinitions)

compare(other)[源代码]
返回类型:

bool

参数:

other (LiveDefinitions)

kill_definitions(atom)[源代码]

Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification.

参数:

atom (Atom)

返回类型:

None

返回:

None

kill_and_add_definition(atom, code_loc, data, dummy=False, tags=None, endness=None, annotated=False)[源代码]
返回类型:

MultiValues | None

参数:
add_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_use_by_def(definition, code_loc, expr=None)[源代码]
返回类型:

None

参数:
get_definitions(thing)[源代码]
返回类型:

set[Definition[Atom]]

参数:

thing (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | MultiValues)

get_tmp_definitions(tmp_idx)[源代码]
返回类型:

set[Definition]

参数:

tmp_idx (int)

get_register_definitions(reg_offset, size)[源代码]
返回类型:

set[Definition]

参数:
get_stack_values(stack_offset, size, endness)[源代码]
返回类型:

MultiValues | None

参数:
  • stack_offset (int)

  • size (int)

  • endness (str)

get_stack_definitions(stack_offset, size)[源代码]
返回类型:

set[Definition]

参数:
  • stack_offset (int)

  • size (int)

get_heap_definitions(heap_addr, size)[源代码]
返回类型:

set[Definition]

参数:
get_memory_definitions(addr, size)[源代码]
返回类型:

set[Definition]

参数:
get_definitions_from_atoms(**kwargs)
get_value_from_definition(**kwargs)
get_one_value_from_definition(**kwargs)
get_concrete_value_from_definition(**kwargs)
get_value_from_atom(**kwargs)
get_one_value_from_atom(**kwargs)
get_concrete_value_from_atom(**kwargs)
get_values(spec)[源代码]
返回类型:

MultiValues | None

参数:

spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])

get_one_value(spec, strip_annotations=False)[源代码]
返回类型:

BV | None

参数:
get_concrete_value(spec, cast_to=<class 'int'>)[源代码]
返回类型:

int | bytes | None

参数:
add_register_use(reg_offset, size, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_register_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_heap_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_heap_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_memory_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_memory_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use(atom, code_loc)[源代码]
返回类型:

None

参数:
add_tmp_use_by_def(def_, code_loc)[源代码]
返回类型:

None

参数:
deref(pointer, size, endness=Endness.BE)[源代码]
static is_heap_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_heap_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

heap_address(offset)[源代码]
返回类型:

BV

参数:

offset (int | HeapAddress)

class angr.knowledge_plugins.key_definitions.rd_model.ReachingDefinitionsModel(func_addr=None, track_liveness=True)[源代码]

基类:object

Models the definitions, uses, and memory of a ReachingDefinitionState object

参数:
  • func_addr (int | None)

  • track_liveness (bool)

__init__(func_addr=None, track_liveness=True)[源代码]
参数:
  • func_addr (int | None)

  • track_liveness (bool)

add_def(d)[源代码]
返回类型:

None

参数:

d (Definition)

kill_def(d)[源代码]
返回类型:

None

参数:

d (Definition)

at_new_stmt(codeloc)[源代码]
返回类型:

None

参数:

codeloc (CodeLocation)

at_new_block(code_loc, pred_codelocs)[源代码]
返回类型:

None

参数:
make_liveness_snapshot()[源代码]
返回类型:

None

find_defs_at(code_loc, op=ObservationPointType.OP_BEFORE)[源代码]
返回类型:

set[Definition]

参数:
get_defs(atom, code_loc, op)[源代码]
返回类型:

set[Definition]

参数:
copy()[源代码]
返回类型:

ReachingDefinitionsModel

merge(model)[源代码]
参数:

model (ReachingDefinitionsModel)

get_observation_by_insn(ins_addr, kind)[源代码]
返回类型:

LiveDefinitions | None

参数:
get_observation_by_node(node_addr, kind, node_idx=None)[源代码]
返回类型:

LiveDefinitions | None

参数:
get_observation_by_stmt(arg1, arg2, arg3=None, *, block_idx=None)[源代码]
get_observation_by_exit(node_addr, stmt_idx, src_node_idx=None)[源代码]
返回类型:

LiveDefinitions | None

参数:
  • node_addr (int)

  • stmt_idx (int)

  • src_node_idx (int | None)

Classes to structure the different types of <Tag>s that can be attached to <Definition>s.

  • Tag
    • FunctionTag
      • ParameterTag

      • LocalVariableTag

      • ReturnValueTag

    • InitialValueTag

class angr.knowledge_plugins.key_definitions.tag.Tag(metadata=None)[源代码]

基类:object

A tag for a Definition that can carry different kinds of metadata.

参数:

metadata (object)

__init__(metadata=None)[源代码]
参数:

metadata (object | None)

class angr.knowledge_plugins.key_definitions.tag.FunctionTag(function=None, metadata=None)[源代码]

基类:Tag

A tag for a definition created (or used) in the context of a function.

参数:
__init__(function=None, metadata=None)[源代码]
参数:
  • function (int | None)

  • metadata (object | None)

class angr.knowledge_plugins.key_definitions.tag.SideEffectTag(function=None, metadata=None)[源代码]

基类:FunctionTag

A tag for a definition created or used as a side-effect of a function.

Example: The <MemoryLocation> pointed by rdi during a sprintf.

参数:
class angr.knowledge_plugins.key_definitions.tag.ParameterTag(function=None, metadata=None)[源代码]

基类:FunctionTag

A tag for a definition of a parameter.

参数:
class angr.knowledge_plugins.key_definitions.tag.LocalVariableTag(function=None, metadata=None)[源代码]

基类:FunctionTag

A tag for a definition of a local variable of a function.

参数:
class angr.knowledge_plugins.key_definitions.tag.ReturnValueTag(function=None, metadata=None)[源代码]

基类:FunctionTag

A tag for a definition of a return value of a function.

参数:
class angr.knowledge_plugins.key_definitions.tag.InitialValueTag(metadata=None)[源代码]

基类:Tag

A tag for a definition of an initial value

参数:

metadata (object)

class angr.knowledge_plugins.key_definitions.tag.UnknownSizeTag(metadata=None)[源代码]

基类:Tag

A tag for a definition of an initial value

参数:

metadata (object)

class angr.knowledge_plugins.key_definitions.undefined.Undefined[源代码]

基类:object

A TOP-like value indicating an unknown data source. Should live next to raw integers in DataSets.

class angr.knowledge_plugins.key_definitions.unknown_size.UnknownSize[源代码]

基类:object

A value indicating an unknown size for elements of DataSets. Should "behave" like an integer.

class angr.knowledge_plugins.key_definitions.uses.Uses(uses_by_definition=None, uses_by_location=None)[源代码]

基类:object

Describes uses (including the use location and the use expression) for definitions.

参数:
__init__(uses_by_definition=None, uses_by_location=None)[源代码]
参数:
add_use(definition, codeloc, expr=None)[源代码]

Add a use for a given definition.

参数:
  • definition (Definition) -- The definition that is used.

  • codeloc (CodeLocation) -- The code location where the use occurs.

  • expr (Optional[Any]) -- The expression that uses the specified definition at this location.

get_uses(definition)[源代码]

Retrieve the uses of a given definition.

参数:

definition (Definition) -- The definition for which we get the uses.

返回类型:

set[CodeLocation]

get_uses_with_expr(definition)[源代码]

Retrieve the uses and the corresponding expressions of a given definition.

参数:

definition (Definition) -- The definition for which we get the uses and the corresponding expressions.

返回类型:

set[tuple[CodeLocation, Optional[Any]]]

remove_use(definition, codeloc, expr=None)[源代码]

Remove one use of a given definition.

参数:
  • definition (Definition) -- The definition of which to remove the uses.

  • codeloc (CodeLocation) -- The code location where the use is.

  • expr (Optional[Any]) -- The expression that uses the definition at the given location.

返回类型:

None

返回:

None

remove_uses(definition)[源代码]

Remove all uses of a given definition.

参数:

definition (Definition) -- The definition of which to remove the uses.

返回:

None

get_uses_by_location(codeloc, exprs=False)[源代码]

Retrieve all definitions that are used at a given location.

参数:
返回类型:

set[Definition] | set[tuple[Definition, Optional[Any]]]

返回:

A set of definitions that are used at the given location.

get_uses_by_insaddr(ins_addr, exprs=False)[源代码]

Retrieve all definitions that are used at a given location specified by the instruction address.

参数:
  • ins_addr (int) -- The instruction address.

  • exprs (bool)

返回类型:

set[Definition] | set[tuple[Definition, Optional[Any]]]

返回:

A set of definitions that are used at the given location.

copy()[源代码]

Copy the instance.

返回类型:

Uses

返回:

Return a new <Uses> instance containing the same data.

merge(other)[源代码]

Merge an instance of <Uses> into the current instance.

参数:

other (Uses) -- The other <Uses> from which the data will be added to the current instance.

返回类型:

bool

返回:

True if any merge occurred, False otherwise

class angr.knowledge_plugins.xrefs.XRef(ins_addr=None, block_addr=None, stmt_idx=None, insn_op_idx=None, memory_data=None, dst=None, xref_type=None)[源代码]

基类:Serializable

XRef describes a reference to a MemoryData instance (if a MemoryData instance is available) or just an address.

参数:
  • ins_addr (int | None)

  • block_addr (int | None)

  • stmt_idx (int | None)

  • insn_op_idx (int | None)

  • dst (int | None)

__init__(ins_addr=None, block_addr=None, stmt_idx=None, insn_op_idx=None, memory_data=None, dst=None, xref_type=None)[源代码]
参数:
  • ins_addr (int | None)

  • block_addr (int | None)

  • stmt_idx (int | None)

  • insn_op_idx (int | None)

  • dst (int | None)

ins_addr: int | None
insn_op_idx: int | None
block_addr: int | None
stmt_idx: int | None
memory_data
type
dst
property type_string
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, bits=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

copy()[源代码]
insn_op_type
class angr.knowledge_plugins.xrefs.XRefManager(kb)[源代码]

基类:KnowledgeBasePlugin, Serializable

__init__(kb)[源代码]
copy()[源代码]
add_xref(xref)[源代码]
add_xrefs(xrefs)[源代码]
get_xrefs_by_ins_addr(ins_addr)[源代码]
get_xrefs_by_dst(dst)[源代码]
get_xrefs_by_dst_region(start, end)[源代码]

Get a set of XRef objects that point to a given address region bounded by start and end. Will only return absolute xrefs, not relative ones (like SP offsets)

get_xrefs_by_ins_addr_region(start, end)[源代码]

Get a set of XRef objects that originate at a given address region bounded by start and end. Useful for finding references from a basic block or function.

返回类型:

set[XRef]

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg_model=None, kb=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.knowledge_plugins.xrefs.XRefType[源代码]

基类:object

Offset = 0
Read = 1
Write = 2
static to_string(ty)[源代码]
class angr.knowledge_plugins.xrefs.xref.XRef(ins_addr=None, block_addr=None, stmt_idx=None, insn_op_idx=None, memory_data=None, dst=None, xref_type=None)[源代码]

基类:Serializable

XRef describes a reference to a MemoryData instance (if a MemoryData instance is available) or just an address.

参数:
  • ins_addr (int | None)

  • block_addr (int | None)

  • stmt_idx (int | None)

  • insn_op_idx (int | None)

  • dst (int | None)

__init__(ins_addr=None, block_addr=None, stmt_idx=None, insn_op_idx=None, memory_data=None, dst=None, xref_type=None)[源代码]
参数:
  • ins_addr (int | None)

  • block_addr (int | None)

  • stmt_idx (int | None)

  • insn_op_idx (int | None)

  • dst (int | None)

ins_addr: int | None
insn_op_idx: int | None
block_addr: int | None
stmt_idx: int | None
memory_data
type
dst
property type_string
serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, bits=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

copy()[源代码]
insn_op_type
class angr.knowledge_plugins.xrefs.xref_types.XRefType[源代码]

基类:object

Offset = 0
Read = 1
Write = 2
static to_string(ty)[源代码]
class angr.knowledge_plugins.xrefs.xref_manager.XRefManager(kb)[源代码]

基类:KnowledgeBasePlugin, Serializable

__init__(kb)[源代码]
copy()[源代码]
add_xref(xref)[源代码]
add_xrefs(xrefs)[源代码]
get_xrefs_by_ins_addr(ins_addr)[源代码]
get_xrefs_by_dst(dst)[源代码]
get_xrefs_by_dst_region(start, end)[源代码]

Get a set of XRef objects that point to a given address region bounded by start and end. Will only return absolute xrefs, not relative ones (like SP offsets)

get_xrefs_by_ins_addr_region(start, end)[源代码]

Get a set of XRef objects that originate at a given address region bounded by start and end. Useful for finding references from a basic block or function.

返回类型:

set[XRef]

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

classmethod parse_from_cmessage(cmsg, cfg_model=None, kb=None, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

class angr.code_location.CodeLocation(block_addr, stmt_idx, sim_procedure=None, ins_addr=None, context=None, block_idx=None, **kwargs)[源代码]

基类:object

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

参数:
  • block_addr (int | None)

  • stmt_idx (int | None)

  • ins_addr (int | None)

  • context (Any)

  • block_idx (int | None)

__init__(block_addr, stmt_idx, sim_procedure=None, ins_addr=None, context=None, block_idx=None, **kwargs)[源代码]

Constructor.

参数:
  • block_addr (int | None) -- Address of the block

  • stmt_idx (int | None) -- Statement ID. None for SimProcedures or if the code location is meant to refer to the entire block.

  • sim_procedure (class) -- The corresponding SimProcedure class.

  • ins_addr (Optional[int]) -- The instruction address.

  • context (Optional[Any]) -- A tuple that represents the context of this CodeLocation in contextual mode, or None in contextless mode.

  • kwargs -- Optional arguments, will be stored, but not used in __eq__ or __hash__.

  • block_idx (int | None)

block_addr: int | None
stmt_idx: int | None
sim_procedure
ins_addr: int | None
context: tuple[int] | None
block_idx: int | None
info: dict | None
property short_repr
class angr.code_location.ExternalCodeLocation(call_string=None)[源代码]

基类:CodeLocation

Stands for a program point that originates from outside an analysis' scope. i.e. a value loaded from rdi in a callee where the caller has not been analyzed.

参数:

call_string (tuple[int, ...] | None)

__init__(call_string=None)[源代码]

Constructor.

参数:
  • block_addr -- Address of the block

  • stmt_idx -- Statement ID. None for SimProcedures or if the code location is meant to refer to the entire block.

  • sim_procedure (class) -- The corresponding SimProcedure class.

  • ins_addr -- The instruction address.

  • context -- A tuple that represents the context of this CodeLocation in contextual mode, or None in contextless mode.

  • kwargs -- Optional arguments, will be stored, but not used in __eq__ or __hash__.

  • call_string (tuple[int, ...] | None)

call_string
class angr.keyed_region.StoredObject(start, obj, size)[源代码]

基类:object

__init__(start, obj, size)[源代码]
start
obj
size: UnknownSize | int
property obj_id
class angr.keyed_region.RegionObject(start, size, objects=None)[源代码]

基类:object

Represents one or more objects occupying one or more bytes in KeyedRegion.

__init__(start, size, objects=None)[源代码]
start
size
stored_objects
property is_empty
property end
property internal_objects
includes(offset)[源代码]
split(split_at)[源代码]
add_object(obj)[源代码]
set_object(obj)[源代码]
copy()[源代码]
class angr.keyed_region.KeyedRegion(tree=None, phi_node_contains=None, canonical_size=8)[源代码]

基类:object

KeyedRegion keeps a mapping between stack offsets and all objects covering that offset. It assumes no variable in this region overlap with another variable in this region.

Registers and function frames can all be viewed as a keyed region.

__init__(tree=None, phi_node_contains=None, canonical_size=8)[源代码]
copy()[源代码]
merge(other, replacements=None)[源代码]

Merge another KeyedRegion into this KeyedRegion.

参数:

other (KeyedRegion) -- The other instance to merge with.

返回:

None

merge_to_top(other, replacements=None, top=None)[源代码]

Merge another KeyedRegion into this KeyedRegion, but mark all variables with different values as TOP.

参数:
  • other -- The other instance to merge with.

  • replacements

返回:

self

replace(replacements)[源代码]

Replace variables with other variables.

参数:

replacements (dict) -- A dict of variable replacements.

返回:

self

dbg_repr()[源代码]

Get a debugging representation of this keyed region. :return: A string of debugging output.

add_variable(start, variable)[源代码]

Add a variable to this region at the given offset.

参数:
返回:

None

add_object(start, obj, object_size)[源代码]

Add/Store an object to this region at the given offset.

参数:
  • start

  • obj

  • object_size (int) -- Size of the object

返回:

set_variable(start, variable)[源代码]

Add a variable to this region at the given offset, and remove all other variables that are fully covered by this variable.

参数:
返回:

None

set_object(start, obj, object_size)[源代码]

Add an object to this region at the given offset, and remove all other objects that are fully covered by this object.

参数:
  • start

  • obj

  • object_size

返回:

get_base_addr(addr)[源代码]

Get the base offset (the key we are using to index objects covering the given offset) of a specific offset.

参数:

addr (int)

返回:

返回类型:

int or None

get_variables_by_offset(start)[源代码]

Find variables covering the given region offset.

参数:

start (int)

返回:

A set of variables.

返回类型:

set

get_objects_by_offset(start)[源代码]

Find objects covering the given region offset.

参数:

start

返回:

get_all_variables()[源代码]

Get all variables covering the current region.

返回:

A set of all variables.

Serialization

class angr.serializable.Serializable[源代码]

基类:object

The base class of all protobuf-serializable classes in angr.

serialize_to_cmessage()[源代码]

Serialize the class object and returns a protobuf cmessage object.

返回:

A protobuf cmessage object.

返回类型:

protobuf.cmessage

serialize()[源代码]

Serialize the class object and returns a bytes object.

返回:

A bytes object.

返回类型:

bytes

classmethod parse_from_cmessage(cmsg, **kwargs)[源代码]

Parse a protobuf cmessage and create a class object.

参数:

cmsg -- The probobuf cmessage object.

返回:

A unserialized class object.

返回类型:

cls

classmethod parse(s, **kwargs)[源代码]

Parse a bytes object and create a class object.

参数:

s (bytes) -- A bytes object.

返回:

A class object.

返回类型:

cls

class angr.vaults.VaultPickler(vault, file, *args, assigned_objects=(), **kwargs)[源代码]

基类:Pickler

__init__(vault, file, *args, assigned_objects=(), **kwargs)[源代码]

A persistence-aware pickler. It will check for persistence of any objects except for those with IDs in 'assigned_objects'.

persistent_id(obj)[源代码]
class angr.vaults.VaultUnpickler(vault, file, *args, **kwargs)[源代码]

基类:Unpickler

__init__(vault, file, *args, **kwargs)[源代码]
persistent_load(pid)[源代码]
class angr.vaults.Vault[源代码]

基类:MutableMapping

The vault is a serializer for angr.

keys()[源代码]

Should return the IDs stored by the vault.

__init__()[源代码]
is_stored(i)[源代码]

Checks if the provided id is already in the vault.

load(oid)[源代码]
store(o)[源代码]
dumps(o)[源代码]

Returns a serialized string representing the object, post-deduplication.

参数:

o -- the object

loads(s)[源代码]

Deserializes a string representation of the object.

参数:

s -- the string

static close()[源代码]
class angr.vaults.VaultDict(d=None)[源代码]

基类:Vault

A Vault that uses a dictionary for storage.

__init__(d=None)[源代码]
is_stored(i)[源代码]

Checks if the provided id is already in the vault.

keys()[源代码]

Should return the IDs stored by the vault.

class angr.vaults.VaultDir(d=None)[源代码]

基类:Vault

A Vault that uses a directory for storage.

__init__(d=None)[源代码]
keys()[源代码]

Should return the IDs stored by the vault.

class angr.vaults.VaultShelf(path=None)[源代码]

基类:VaultDict

A Vault that uses a shelve.Shelf for storage.

__init__(path=None)[源代码]
close()[源代码]
class angr.vaults.VaultDirShelf(d=None)[源代码]

基类:VaultDict

A Vault that uses a directory for storage, where every object is stored into a single shelve.Shelf instance. VaultDir creates a file for each object. VaultDirShelf creates only one file for a stored object and everything else it references.

__init__(d=None)[源代码]
store(o)[源代码]
load(oid)[源代码]
keys()[源代码]

Should return the IDs stored by the vault.

Analysis

class angr.analyses.CDG(cfg, start=None, no_construct=False)[源代码]

基类:Analysis

Implements a control dependence graph.

__init__(cfg, start=None, no_construct=False)[源代码]

Constructor.

参数:
  • cfg -- The control flow graph upon which this control dependence graph will build

  • start -- The starting point to begin constructing the control dependence graph

  • no_construct -- Skip the construction step. Only used in unit-testing.

property graph
get_post_dominators()[源代码]

Return the post-dom tree

get_dependants(run)[源代码]

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

get_guardians(run)[源代码]

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

class angr.analyses.CFG(**kwargs)[源代码]

基类:CFGFast

tl;dr: CFG is just a wrapper around CFGFast for compatibility issues. It will be fully replaced by CFGFast in future releases. Feel free to use CFG if you intend to use CFGFast. Please use CFGEmulated if you have to use the old, slow, dynamically-generated version of CFG.

For multiple historical reasons, angr's CFG is accurate but slow, which does not meet what most people expect. We developed CFGFast for light-speed CFG recovery, and renamed the old CFG class to CFGEmulated. For compatibility concerns, CFG was kept as an alias to CFGEmulated.

However, so many new users of angr would load up a binary and generate a CFG immediately after running "pip install angr", and draw the conclusion that "angr's CFG is so slow - angr must be unusable!" Therefore, we made the hard decision: CFG will be an alias to CFGFast, instead of CFGEmulated.

To ease the transition of your existing code and script, the following changes are made:

  • A CFG class, which is a sub class of CFGFast, is created.

  • You will see both a warning message printed out to stderr and an exception raised by angr if you are passing CFG any parameter that only CFGEmulated supports. This exception is not a sub class of AngrError, so you wouldn't capture it with your old code by mistake.

  • In the near future, this wrapper class will be removed completely, and CFG will be a simple alias to CFGFast.

We expect most interfaces are the same between CFGFast and CFGEmulated. Apparently some functionalities (like context-sensitivity, and state keeping) only exist in CFGEmulated, which is when you want to use CFGEmulated instead.

__init__(**kwargs)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

返回:

None

class angr.analyses.DDG(cfg, start=None, call_depth=None, block_addrs=None)[源代码]

基类:Analysis

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

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

The DDG is based on a CFG, which should ideally be a CFGEmulated generated with the following options:

  • keep_state=True to keep all input states

  • state_add_options=angr.options.refs to store memory, register, and temporary value accesses

You may want to consider a high value for context_sensitivity_level as well when generating the CFG.

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

__init__(cfg, start=None, call_depth=None, block_addrs=None)[源代码]
参数:
  • cfg -- Control flow graph. Please make sure each node has an associated state with it, e.g. by passing the keep_state=True and state_add_options=angr.options.refs arguments to CFGEmulated.

  • start -- An address, Specifies where we start the generation of this data dependence graph.

  • call_depth -- None or integers. A non-negative integer specifies how deep we would like to track in the call tree. None disables call_depth limit.

  • block_addrs (iterable or None) -- A collection of block addresses that the DDG analysis should be performed on.

property graph

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

Type:

returns

property data_graph

Get the data dependence graph.

返回:

A networkx DiGraph instance representing data dependence.

返回类型:

networkx.DiGraph

property simplified_data_graph

return:

property ast_graph
pp()[源代码]

Pretty printing.

dbg_repr()[源代码]

Representation for debugging.

get_predecessors(code_location)[源代码]

Returns all predecessors of the code location.

参数:

code_location -- A CodeLocation instance.

返回:

A list of all predecessors.

function_dependency_graph(func)[源代码]

Get a dependency graph for the function func.

参数:

func -- The Function object in CFG.function_manager.

返回:

A networkx.DiGraph instance.

data_sub_graph(pv, simplified=True, killing_edges=False, excluding_types=None)[源代码]

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

参数:
  • pv (ProgramVariable) -- The starting point of the subgraph.

  • simplified (bool) -- When True, the simplified data graph is used, otherwise the data graph is used.

  • killing_edges (bool) -- Are killing edges included or not.

  • excluding_types (iterable) -- Excluding edges whose types are among those excluded types.

返回:

A subgraph.

返回类型:

networkx.MultiDiGraph

find_definitions(variable, location=None, simplified_graph=True)[源代码]

Find all definitions of the given variable.

参数:
  • variable (SimVariable)

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

返回:

A collection of all variable definitions to the specific variable.

返回类型:

list

find_consumers(var_def, simplified_graph=True)[源代码]

Find all consumers to the specified variable definition.

参数:
  • var_def (ProgramVariable) -- The variable definition.

  • simplified_graph (bool) -- True if we want to search in the simplified graph, False otherwise.

返回:

A collection of all consumers to the specified variable definition.

返回类型:

list

find_killers(var_def, simplified_graph=True)[源代码]

Find all killers to the specified variable definition.

参数:
  • var_def (ProgramVariable) -- The variable definition.

  • simplified_graph (bool) -- True if we want to search in the simplified graph, False otherwise.

返回:

A collection of all killers to the specified variable definition.

返回类型:

list

find_sources(var_def, simplified_graph=True)[源代码]

Find all sources to the specified variable definition.

参数:
  • var_def (ProgramVariable) -- The variable definition.

  • simplified_graph (bool) -- True if we want to search in the simplified graph, False otherwise.

返回:

A collection of all sources to the specified variable definition.

返回类型:

list

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

基类:ForwardAnalysis[SimState, VFGNode, VFGJob, BlockID], Analysis

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

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

Steps:

  • Generate a CFG first if CFG is not provided.

  • Identify all merge points (denote the set of merge points as Pw) in the CFG.

  • Cut those loop back edges (can be derived from Pw) so that we gain an acyclic CFG.

  • Identify all variables that are 1) from memory loading 2) from initial values, or 3) phi functions. Denote

    the set of those variables as S_{var}.

  • Start real AI analysis and try to compute a fix point of each merge point. Perform widening/narrowing only on

    variables in S_{var}.

参数:
__init__(cfg=None, context_sensitivity_level=2, start=None, function_start=None, interfunction_level=0, initial_state=None, avoid_runs=None, remove_options=None, timeout=None, max_iterations_before_widening=8, max_iterations=40, widening_interval=3, final_state_callback=None, status_callback=None, record_function_final_states=False)[源代码]
参数:
  • cfg (Optional[CFGEmulated]) -- The control-flow graph to base this analysis on. If none is provided, we will construct a CFGEmulated.

  • context_sensitivity_level (int) -- The level of context-sensitivity of this VFG. It ranges from 0 to infinity. Default 2.

  • function_start (Optional[int]) -- The address of the function to analyze.

  • interfunction_level (int) -- The level of interfunction-ness to be

  • initial_state (Optional[SimState]) -- A state to use as the initial one

  • avoid_runs (Optional[list[int]]) -- A list of runs to avoid

  • remove_options (Optional[set[str]]) -- State options to remove from the initial state. It only works when initial_state is None

  • timeout (int)

  • final_state_callback (Optional[Callable[[SimState, CallStack], Any]]) -- callback function when countering final state

  • status_callback (Optional[Callable[[VFG], Any]]) -- callback function used in _analysis_core_baremetal

  • start (int | None)

  • max_iterations_before_widening (int)

  • max_iterations (int)

  • widening_interval (int)

  • record_function_final_states (bool)

返回类型:

None

property function_initial_states
property function_final_states
get_any_node(addr)[源代码]

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

返回类型:

VFGNode | None

参数:

addr (int)

get_all_nodes(addr)[源代码]
返回类型:

Generator[VFGNode]

irsb_from_node(node)[源代码]
copy()[源代码]
class angr.analyses.VSA_DDG(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)[源代码]

基类:Analysis

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

__init__(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)[源代码]

Constructor.

参数:
  • vfg -- An already constructed VFG. If not specified, a new VFG will be created with other specified parameters. vfg and start_addr cannot both be unspecified.

  • start_addr -- The address where to start the analysis (typically, a function's entry point).

  • interfunction_level -- See VFG analysis.

  • context_sensitivity_level -- See VFG analysis.

  • keep_data -- Whether we keep set of addresses as edges in the graph, or just the cardinality of the sets, which can be used as a "weight".

get_predecessors(code_location)[源代码]

Returns all predecessors of code_location.

参数:

code_location -- A CodeLocation instance.

返回:

A list of all predecessors.

get_all_nodes(simrun_addr, stmt_idx)[源代码]

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

class angr.analyses.AnalysesHub(project)[源代码]

基类:PluginVendor[A]

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

__init__(project)[源代码]
reload_analyses(**kwargs)
class angr.analyses.Analysis[源代码]

基类:object

This class represents an analysis on the program.

变量:
  • 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: list[AnalysisLogEntry] = []
named_errors: defaultdict[str, list[AnalysisLogEntry]] = {}
class angr.analyses.BackwardSlice(cfg, cdg, ddg, targets=None, cfg_node=None, stmt_id=None, control_flow_slice=False, same_function=False, no_construct=False)[源代码]

基类:Analysis

Represents a backward slice of the program.

__init__(cfg, cdg, ddg, targets=None, cfg_node=None, stmt_id=None, control_flow_slice=False, same_function=False, no_construct=False)[源代码]

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

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

参数:
  • cfg -- The control flow graph.

  • cdg -- The control dependence graph.

  • ddg -- The data dependence graph.

  • targets -- A list of "target" that specify targets of the backward slices. Each target can be a tuple in form of (cfg_node, stmt_idx), or a CodeLocation instance.

  • cfg_node -- Deprecated. The target CFGNode to reach. It should exist in the CFG.

  • stmt_id -- Deprecated. The target statement to reach.

  • control_flow_slice -- True/False, indicates whether we should slice only based on CFG. Sometimes when acquiring DDG is difficult or impossible, you can just create a slice on your CFG. Well, if you don't even have a CFG, then...

  • no_construct -- Only used for testing and debugging to easily create a BackwardSlice object.

dbg_repr(max_display=10)[源代码]

Debugging output of this slice.

参数:

max_display -- The maximum number of SimRun slices to show.

返回:

A string representation.

dbg_repr_run(run_addr)[源代码]

Debugging output of a single SimRun slice.

参数:

run_addr -- Address of the SimRun.

返回:

A string representation.

annotated_cfg(start_point=None)[源代码]

Returns an AnnotatedCFG based on slicing result.

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

参数:
  • simrun_addr -- Address of the SimRun.

  • stmt_idx -- Statement ID.

  • taint_type -- Type of the taint, might be one of the following: 'reg', 'tmp', 'mem'.

  • simrun_whitelist -- A list of SimRun addresses that are whitelisted, i.e. the tainted exit will be ignored if it is in those SimRuns.

返回:

True/False

is_taint_impacting_stack_pointers(simrun_addr, stmt_idx, taint_type, simrun_whitelist=None)[源代码]

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

参数:
  • simrun_addr -- Address of the SimRun.

  • stmt_idx -- Statement ID.

  • taint_type -- Type of the taint, might be one of the following: 'reg', 'tmp', 'mem'.

  • simrun_whitelist -- A list of SimRun addresses that are whitelisted.

返回:

True/False.

class angr.analyses.BinDiff(other_project, enable_advanced_backward_slicing=False, cfg_a=None, cfg_b=None)[源代码]

基类:Analysis

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

__init__(other_project, enable_advanced_backward_slicing=False, cfg_a=None, cfg_b=None)[源代码]
参数:

other_project -- The second project to diff

functions_probably_identical(func_a_addr, func_b_addr, check_consts=False)[源代码]

Compare two functions and return True if they appear identical.

参数:
  • func_a_addr -- The address of the first function (in the first binary).

  • func_b_addr -- The address of the second function (in the second binary).

返回:

Whether or not the functions appear to be identical.

property identical_functions

A list of function matches that appear to be identical

Type:

returns

property differing_functions

A list of function matches that appear to differ

Type:

returns

differing_functions_with_consts()[源代码]
返回:

A list of function matches that appear to differ including just by constants

property differing_blocks

A list of block matches that appear to differ

Type:

returns

property identical_blocks

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

property blocks_with_differing_constants

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

Type:

return

property unmatched_functions
get_function_diff(function_addr_a, function_addr_b)[源代码]
参数:
  • function_addr_a -- The address of the first function (in the first binary)

  • function_addr_b -- The address of the second function (in the second binary)

返回:

the FunctionDiff of the two functions

class angr.analyses.BinaryOptimizer(cfg, techniques)[源代码]

基类:Analysis

This is a collection of binary optimization techniques we used in Mechanical Phish during the finals of Cyber Grand Challenge. It focuses on dealing with some serious speed-impacting code constructs, and sort of worked on some CGC binaries compiled with O0. Use this analysis as a reference of how to use data dependency graph and such.

There is no guarantee that BinaryOptimizer will ever work on non-CGC binaries. Feel free to give us PR or MR, but please do not ask for support of non-CGC binaries.

BLOCKS_THRESHOLD = 500
__init__(cfg, techniques)[源代码]
optimize()[源代码]
class angr.analyses.BoyScout(cookiesize=1)[源代码]

基类:Analysis

Try to determine the architecture and endieness of a binary blob

__init__(cookiesize=1)[源代码]
class angr.analyses.CFGArchOptions(arch, **options)[源代码]

基类:object

Stores architecture-specific options and settings, as well as the detailed explanation of those options and settings.

Suppose ao is the CFGArchOptions object, and there is an option called ret_jumpkind_heuristics, you can access it by ao.ret_jumpkind_heuristics and set its value via ao.ret_jumpkind_heuristics = True

变量:
  • OPTIONS (dict) -- A dict of all default options for different architectures.

  • arch (archinfo.Arch) -- The architecture object.

  • _options (dict) -- Values of all CFG options that are specific to the current architecture.

OPTIONS = {'ARMCortexM': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, False)}, 'ARMEL': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, True)}, 'ARMHF': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, True)}}
__init__(arch, **options)[源代码]

Constructor.

参数:
  • arch (archinfo.Arch) -- The architecture instance.

  • options (dict) -- Architecture-specific options, which will be used to initialize this object.

arch = None
class angr.analyses.CFGEmulated(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, indirect_jump_target_limit=100000, resolve_indirect_jumps=True, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, indirect_jump_resolvers=None, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None, state_add_options=None, state_remove_options=None, model=None)[源代码]

基类:ForwardAnalysis, CFGBase

This class represents a control-flow graph.

tag: str | None = 'CFGEmulated'
__init__(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, indirect_jump_target_limit=100000, resolve_indirect_jumps=True, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, indirect_jump_resolvers=None, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None, state_add_options=None, state_remove_options=None, model=None)[源代码]

All parameters are optional.

参数:
  • context_sensitivity_level -- The level of context-sensitivity of this CFG (see documentation for further details). It ranges from 0 to infinity. Default 1.

  • avoid_runs -- A list of runs to avoid.

  • enable_function_hints -- Whether to use function hints (constants that might be used as exit targets) or not.

  • call_depth -- How deep in the call stack to trace.

  • call_tracing_filter -- Filter to apply on a given path and jumpkind to determine if it should be skipped when call_depth is reached.

  • initial_state -- An initial state to use to begin analysis.

  • starts (iterable) -- A collection of starting points to begin analysis. It can contain the following three different types of entries: an address specified as an integer, a 2-tuple that includes an integer address and a jumpkind, or a SimState instance. Unsupported entries in starts will lead to an AngrCFGError being raised.

  • keep_state -- Whether to keep the SimStates for each CFGNode.

  • resolve_indirect_jumps -- Whether to enable the indirect jump resolvers for resolving indirect jumps

  • enable_advanced_backward_slicing -- Whether to enable an intensive technique for resolving indirect jumps

  • enable_symbolic_back_traversal -- Whether to enable an intensive technique for resolving indirect jumps

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • additional_edges -- A dict mapping addresses of basic blocks to addresses of successors to manually include and analyze forward from.

  • no_construct (bool) -- Skip the construction procedure. Only used in unit-testing.

  • normalize (bool) -- If the CFG as well as all Function graphs should be normalized or not.

  • max_iterations (int) -- The maximum number of iterations that each basic block should be "executed". 1 by default. Larger numbers of iterations are usually required for complex analyses like loop analysis.

  • address_whitelist (iterable) -- A list of allowed addresses. Any basic blocks outside of this collection of addresses will be ignored.

  • base_graph (networkx.DiGraph) -- A basic control flow graph to follow. Each node inside this graph must have the following properties: addr and size. CFG recovery will strictly follow nodes and edges shown in the graph, and discard any control flow that does not follow an existing edge in the base graph. For example, you can pass in a Function local transition graph as the base graph, and CFGEmulated will traverse nodes and edges and extract useful information.

  • iropt_level (int) -- The optimization level of VEX IR (0, 1, 2). The default level will be used if iropt_level is None.

  • max_steps (int) -- The maximum number of basic blocks to recover forthe longest path from each start before pausing the recovery procedure.

  • state_add_options -- State options that will be added to the initial state.

  • state_remove_options -- State options that will be removed from the initial state.

copy()[源代码]

Make a copy of the CFG.

返回类型:

CFGEmulated

返回:

A copy of the CFG instance.

resume(starts=None, max_steps=None)[源代码]

Resume a paused or terminated control flow graph recovery.

参数:
  • starts (iterable) -- A collection of new starts to resume from. If starts is None, we will resume CFG recovery from where it was paused before.

  • max_steps (int) -- The maximum number of blocks on the longest path starting from each start before pausing the recovery.

返回:

None

remove_cycles()[源代码]

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

downsize()[源代码]

Remove saved states from all CFGNodes to reduce memory usage.

返回:

None

unroll_loops(max_loop_unrolling_times)[源代码]

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

参数:

max_loop_unrolling_times (int) -- The maximum iterations of unrolling.

返回:

None

force_unroll_loops(max_loop_unrolling_times)[源代码]

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

参数:

max_loop_unrolling_times (int) -- The maximum iterations of unrolling.

返回:

None

immediate_dominators(start, target_graph=None)[源代码]

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

参数:
  • start (str) -- id of the node to navigate forwards from.

  • target_graph (networkx.classes.digraph.DiGraph) -- graph to analyse, default is self.graph.

返回:

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

返回类型:

dict

immediate_postdominators(end, target_graph=None)[源代码]

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

参数:
  • start (str) -- id of the node to navigate forwards from.

  • target_graph (networkx.classes.digraph.DiGraph) -- graph to analyse, default is self.graph.

返回:

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

返回类型:

dict

remove_fakerets()[源代码]

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

返回:

None

get_topological_order(cfg_node)[源代码]

Get the topological order of a CFG Node.

参数:

cfg_node -- A CFGNode instance.

返回:

An integer representing its order, or None if the CFGNode does not exist in the graph.

get_subgraph(starting_node, block_addresses)[源代码]

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

参数:
  • starting_node (CFGNode) -- The beginning of the subgraph

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

返回:

A new CFG that only contain the specific subgraph.

返回类型:

CFGEmulated

get_function_subgraph(start, max_call_depth=None)[源代码]

Get a sub-graph of a certain function.

参数:
  • start -- The function start. Currently it should be an integer.

  • max_call_depth -- Call depth limit. None indicates no limit.

返回:

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

property context_sensitivity_level
property graph
property unresolvables

Get those SimRuns that have non-resolvable exits.

返回:

A set of SimRuns

返回类型:

set

property deadends

Get all CFGNodes that has an out-degree of 0

返回:

A list of CFGNode instances

返回类型:

list

class angr.analyses.CFGFast(binary=None, objects=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_smart_scan=True, force_complete_scan=False, indirect_jump_target_limit=100000, data_references=True, cross_references=False, normalize=False, start_at_entry=True, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, indirect_jump_resolvers=None, base_state=None, exclude_sparse_regions=True, skip_specific_regions=True, heuristic_plt_resolving=None, detect_tail_calls=False, low_priority=False, cfb=None, model=None, elf_eh_frame=True, exceptions=True, skip_unmapped_addrs=True, nodecode_window_size=512, nodecode_threshold=0.3, nodecode_step=16483, indirect_calls_always_return=None, jumptable_resolver_resolves_calls=None, start=None, end=None, collect_data_references=None, extra_cross_references=None, **extra_arch_options)[源代码]

基类:ForwardAnalysis[CFGNode, CFGNode, CFGJob, int], CFGBase

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

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

# Active scanning

  • If the binary has "function symbols" (TODO: this term is not accurate enough), they are starting points of the code scanning

  • If the binary does not have any "function symbol", we will first perform a function prologue scanning on the entire binary, and start from those places that look like function beginnings

  • Otherwise, the binary's entry point will be the starting point for scanning

# Passive scanning

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

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

参数:
  • indirect_calls_always_return (bool | None)

  • jumptable_resolver_resolves_calls (bool | None)

PRINTABLES = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r'
SPECIAL_THUNKS = {'AMD64': {b'\xe8\x07\x00\x00\x00\xf3\x90\x0f\xae\xe8\xeb\xf9H\x89\x04$\xc3': ('jmp', 'rax'), b'\xe8\x07\x00\x00\x00\xf3\x90\x0f\xae\xe8\xeb\xf9H\x8dd$\x08\xc3': ('ret',)}}
tag: str | None = 'CFGFast'
__init__(binary=None, objects=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_smart_scan=True, force_complete_scan=False, indirect_jump_target_limit=100000, data_references=True, cross_references=False, normalize=False, start_at_entry=True, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, indirect_jump_resolvers=None, base_state=None, exclude_sparse_regions=True, skip_specific_regions=True, heuristic_plt_resolving=None, detect_tail_calls=False, low_priority=False, cfb=None, model=None, elf_eh_frame=True, exceptions=True, skip_unmapped_addrs=True, nodecode_window_size=512, nodecode_threshold=0.3, nodecode_step=16483, indirect_calls_always_return=None, jumptable_resolver_resolves_calls=None, start=None, end=None, collect_data_references=None, extra_cross_references=None, **extra_arch_options)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return (Optional[bool]) -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls (Optional[bool]) -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

  • indirect_calls_always_return (bool | None)

  • jumptable_resolver_resolves_calls (bool | None)

返回:

None

property graph
property memory_data
property jump_tables
property insn_addr_to_memory_data
do_full_xrefs(overlay_state=None)[源代码]

Perform xref recovery on all functions.

参数:

overlay (SimState) -- An overlay state for loading constant data.

返回:

None

copy()[源代码]
output()[源代码]
generate_code_cover(**kwargs)
class angr.analyses.CFGFastSoot(support_jni=False, **kwargs)[源代码]

基类:CFGFast

__init__(support_jni=False, **kwargs)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

返回:

None

normalize()[源代码]

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

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

返回:

None

make_functions()[源代码]

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

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

  • A block may only belong to one function.

  • Small functions lying inside the startpoint and the endpoint of another function will be merged with the other function

  • Tail call optimizations are detected.

  • PLT stubs are aligned by 16.

返回:

None

class angr.analyses.CalleeCleanupFinder(starts=None, hook_all=False)[源代码]

基类:Analysis

__init__(starts=None, hook_all=False)[源代码]
analyze(addr)[源代码]
class angr.analyses.CallingConventionAnalysis(func, cfg=None, analyze_callsites=False, caller_func_addr=None, callsite_block_addr=None, callsite_insn_addr=None, func_graph=None, input_args=None, retval_size=None)[源代码]

基类:Analysis

Analyze the calling convention of a function and guess a probable prototype.

The calling convention of a function can be inferred at both its call sites and the function itself. At call sites, we consider all register and stack variables that are not alive after the function call as parameters to this function. In the function itself, we consider all register and stack variables that are read but without initialization as parameters. Then we synthesize the information from both locations and make a reasonable inference of calling convention of this function.

变量:
  • _function -- The function to recover calling convention for.

  • _variable_manager -- A handy accessor to the variable manager.

  • _cfg -- A reference of the CFGModel of the current binary. It is used to discover call sites of the current function in order to perform analysis at call sites.

  • analyze_callsites -- True if we should analyze all call sites of the current function to determine the calling convention and arguments. This can be time-consuming if there are many call sites to analyze.

  • cc -- The recovered calling convention for the function.

参数:
__init__(func, cfg=None, analyze_callsites=False, caller_func_addr=None, callsite_block_addr=None, callsite_insn_addr=None, func_graph=None, input_args=None, retval_size=None)[源代码]
参数:
is_va_start_amd64(func)[源代码]
返回类型:

tuple[bool, int | None]

参数:

func (Function)

class angr.analyses.ClassIdentifier[源代码]

基类:Analysis

This is a class identifier for non stripped or partially stripped binaries, it identifies classes based on the demangled function names, and also assigns functions to their respective classes based on their names. It also uses the results from the VtableFinder analysis to assign the corresponding vtable to the classes.

self.classes contains a mapping between class names and SimCppClass objects

e.g. A::tool() and A::qux() belong to the class A

__init__()[源代码]
class angr.analyses.CodeCaveAnalysis[源代码]

基类:Analysis

Best-effort static location of potential vacant code caves for possible code injection: - Padding functions - Unreachable code

__init__()[源代码]
codecaves: list[CodeCave]
class angr.analyses.CodeTagging(func)[源代码]

基类:Analysis

__init__(func)[源代码]
analyze()[源代码]
has_xor()[源代码]

Detects if there is any xor operation in the function.

返回:

Tags

has_bitshifts()[源代码]

Detects if there is any bitwise operation in the function.

返回:

Tags.

has_sql()[源代码]

Detects if there is any reference to strings that look like SQL queries.

class angr.analyses.CompleteCallingConventionsAnalysis(mode=CallingConventionAnalysisMode.FAST, recover_variables=False, low_priority=False, force=False, cfg=None, analyze_callsites=False, skip_signature_matched_functions=False, max_function_blocks=None, max_function_size=None, workers=0, cc_callback=None, prioritize_func_addrs=None, skip_other_funcs=False, auto_start=True, func_graphs=None)[源代码]

基类:Analysis

Implements full-binary calling convention analysis. During the initial analysis of a binary, you may set recover_variables to True so that it will perform variable recovery on each function before performing calling convention analysis.

参数:
__init__(mode=CallingConventionAnalysisMode.FAST, recover_variables=False, low_priority=False, force=False, cfg=None, analyze_callsites=False, skip_signature_matched_functions=False, max_function_blocks=None, max_function_size=None, workers=0, cc_callback=None, prioritize_func_addrs=None, skip_other_funcs=False, auto_start=True, func_graphs=None)[源代码]
参数:
  • recover_variables -- Recover variables on each function before performing calling convention analysis.

  • low_priority -- Run in the background - periodically release GIL.

  • force -- Perform calling convention analysis on functions even if they have calling conventions or prototypes already specified (or previously recovered).

  • cfg (Optional[CFGModel]) -- The control flow graph model, which will be passed to CallingConventionAnalysis.

  • analyze_callsites (bool) -- Consider artifacts at call sites when performing calling convention analysis.

  • skip_signature_matched_functions (bool) -- Do not perform calling convention analysis on functions that match against existing FLIRT signatures.

  • max_function_blocks (Optional[int]) -- Do not perform calling convention analysis on functions with more than the specified number of blocks. Setting it to None disables this check.

  • max_function_size (Optional[int]) -- Do not perform calling convention analysis on functions whose sizes are more than max_function_size. Setting it to None disables this check.

  • workers (int) -- Number of multiprocessing workers.

  • mode (CallingConventionAnalysisMode)

  • cc_callback (Callable | None)

  • prioritize_func_addrs (Iterable[int] | None)

  • skip_other_funcs (bool)

  • auto_start (bool)

  • func_graphs (dict[int, DiGraph] | None)

work()[源代码]
prioritize_functions(func_addrs_to_prioritize)[源代码]

Prioritize the analysis of specified functions.

参数:

func_addrs_to_prioritize (Iterable[int]) -- A collection of function addresses to analyze first.

static function_needs_variable_recovery(func)[源代码]

Check if running variable recovery on the function is the only way to determine the calling convention of the this function.

We do not need to run variable recovery to determine the calling convention of a function if: - The function is a SimProcedure. - The function is a PLT stub. - The function is a library function and we already know its prototype.

参数:

func -- The function object.

返回:

True if we must run VariableRecovery before we can determine what the calling convention of this function is. False otherwise.

返回类型:

bool

class angr.analyses.CongruencyCheck(throw=False)[源代码]

基类:Analysis

This is an analysis to ensure that angr executes things identically with different execution backends (i.e., unicorn vs vex).

__init__(throw=False)[源代码]

Initializes a CongruencyCheck analysis.

参数:

throw -- whether to raise an exception if an incongruency is found.

set_state_options(left_add_options=None, left_remove_options=None, right_add_options=None, right_remove_options=None)[源代码]

Checks that the specified state options result in the same states over the next depth states.

set_states(left_state, right_state)[源代码]

Checks that the specified paths stay the same over the next depth states.

set_simgr(simgr)[源代码]
run(depth=None)[源代码]

Checks that the paths in the specified path group stay the same over the next depth bytes.

The path group should have a "left" and a "right" stash, each with a single path.

compare_path_group(pg)[源代码]
compare_states(sl, sr)[源代码]

Compares two states for similarity.

compare_paths(pl, pr)[源代码]
class angr.analyses.DataDependencyGraphAnalysis(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]

基类:Analysis

This is a DYNAMIC data dependency graph that utilizes a given SimState to produce a DDG graph that is accurate to the path the program took during execution.

This analysis utilizes the SimActionData objects present in the provided SimState's action history to generate the dependency graph.

参数:
__init__(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]
参数:
  • end_state (SimState) -- Simulation state used to extract all SimActionData

  • start_from (Optional[int]) -- An address or None, Specifies where to start generation of DDG

  • end_at (Optional[int]) -- An address or None, Specifies where to end generation of DDG

  • block_addrs (list[int] | None) -- List of block addresses that the DDG analysis should be run on

  • block_addrs

property graph: DiGraph | None
property simplified_graph: DiGraph | None
property sub_graph: DiGraph | None
get_data_dep(g_node, include_tmp_nodes, backwards)[源代码]
返回类型:

DiGraph | None

参数:
class angr.analyses.Decompiler(func, cfg=None, options=None, preset=None, optimization_passes=None, sp_tracker_track_memory=True, variable_kb=None, peephole_optimizations=None, vars_must_struct=None, flavor='pseudocode', expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=True, inline_functions=frozenset({}), desired_variables=frozenset({}), update_memory_data=True, generate_code=True, use_cache=True, expr_collapse_depth=16)[源代码]

基类:Analysis

The decompiler analysis.

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

参数:
  • func (Function | str | int)

  • cfg (CFGFast | CFGModel | None)

  • preset (str | DecompilationPreset | None)

  • peephole_optimizations (_PEEPHOLE_OPTIMIZATIONS_TYPE)

  • vars_must_struct (set[str] | None)

  • update_memory_data (bool)

  • generate_code (bool)

  • use_cache (bool)

  • expr_collapse_depth (int)

__init__(func, cfg=None, options=None, preset=None, optimization_passes=None, sp_tracker_track_memory=True, variable_kb=None, peephole_optimizations=None, vars_must_struct=None, flavor='pseudocode', expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=True, inline_functions=frozenset({}), desired_variables=frozenset({}), update_memory_data=True, generate_code=True, use_cache=True, expr_collapse_depth=16)[源代码]
参数:
reflow_variable_types(type_constraints, func_typevar, var_to_typevar, codegen)[源代码]

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

返回:

参数:
  • type_constraints (set)

  • var_to_typevar (dict)

find_data_references_and_update_memory_data(seq_node)[源代码]
参数:

seq_node (SequenceNode)

static options_to_params(options)[源代码]

Convert decompilation options to a dict of params.

参数:

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

返回类型:

dict[str, Any]

返回:

A dict of keyword arguments.

class angr.analyses.Disassembly(function=None, ranges=None, thumb=False, include_ir=False, block_bytes=None)[源代码]

基类:Analysis

Produce formatted machine code disassembly.

参数:
__init__(function=None, ranges=None, thumb=False, include_ir=False, block_bytes=None)[源代码]
参数:
func_lookup(block)[源代码]
parse_block(block)[源代码]

Parse instructions for a given block node

返回类型:

None

参数:

block (BlockNode)

render(formatting=None, show_edges=True, show_addresses=True, show_bytes=False, ascii_only=None, color=True)[源代码]

Render the disassembly to a string, with optional edges and addresses.

Color will be added by default, if enabled. To disable color pass an empty formatting dict.

返回类型:

str

参数:
class angr.analyses.DominanceFrontier(func, func_graph=None, entry=None, exception_edges=False)[源代码]

基类:Analysis

Computes the dominance frontier of all nodes in a function graph, and provides an easy-to-use interface for querying the frontier information.

__init__(func, func_graph=None, entry=None, exception_edges=False)[源代码]
class angr.analyses.FactCollector(func, max_depth=5)[源代码]

基类:Analysis

An extremely fast analysis that extracts necessary facts of a function for CallingConventionAnalysis to make decision on the calling convention and prototype of a function.

参数:
__init__(func, max_depth=5)[源代码]
参数:
class angr.analyses.FastConstantPropagation(func, blocks=None, vex_cross_insn_opt=False, load_callback=None)[源代码]

基类:Analysis

An extremely fast constant propagation analysis that finds function-wide constant values with potentially high false negative rates.

参数:
__init__(func, blocks=None, vex_cross_insn_opt=False, load_callback=None)[源代码]
参数:
class angr.analyses.FlirtAnalysis(sig=None)[源代码]

基类:Analysis

FlirtAnalysis accomplishes two purposes:

  • If a FLIRT signature file is specified, it will match the given signature file against the current binary and rename recognized functions accordingly.

  • If no FLIRT signature file is specified, it will use strings to determine possible libraries embedded in the current binary, and then match all possible signatures for the architecture.

参数:

sig (FlirtSignature | str | None)

__init__(sig=None)[源代码]
参数:

sig (FlirtSignature | str | None)

class angr.analyses.ForwardAnalysis(order_jobs=False, allow_merging=False, allow_widening=False, status_callback=None, graph_visitor=None)[源代码]

基类:Generic[AnalysisState, NodeType, JobType, JobKey]

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

In short, ForwardAnalysis performs a forward data-flow analysis by traversing a graph, compute on abstract values, and store results in abstract states. The user can specify what graph to traverse, how a graph should be traversed, how abstract values and abstract states are defined, etc.

ForwardAnalysis has a few options to toggle, making it suitable to be the base class of several different styles of forward data-flow analysis implementations.

ForwardAnalysis supports a special mode when no graph is available for traversal (for example, when a CFG is being initialized and constructed, no other graph can be used). In that case, the graph traversal functionality is disabled, and the optimal graph traversal order is not guaranteed. The user can provide a job sorting method to sort the jobs in queue and optimize traversal order.

Feel free to discuss with me (Fish) if you have any suggestions or complaints.

参数:
__init__(order_jobs=False, allow_merging=False, allow_widening=False, status_callback=None, graph_visitor=None)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

  • status_callback (Callable[[type[ForwardAnalysis]], Any] | None)

返回:

None

property should_abort

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

property graph: DiGraph
property jobs
abort()[源代码]

Abort the analysis :return: None

has_job(job)[源代码]

Checks whether there exists another job which has the same job key. :type job: TypeVar(JobType) :param job: The job to check.

返回类型:

bool

返回:

True if there exists another job with the same key, False otherwise.

参数:

job (JobType)

downsize()[源代码]
class angr.analyses.Identifier(cfg=None, require_predecessors=True, only_find=None)[源代码]

基类:Analysis

__init__(cfg=None, require_predecessors=True, only_find=None)[源代码]
run(only_find=None)[源代码]
can_call_same_name(addr, name)[源代码]
get_func_info(func)[源代码]
static constrain_all_zero(before_state, state, regs)[源代码]
identify_func(function)[源代码]
check_tests(cfg_func, match_func)[源代码]
map_callsites()[源代码]
do_trace(addr_trace, reverse_accesses, func_info)[源代码]
get_call_args(func, callsite)[源代码]
static get_reg_name(arch, reg_offset)[源代码]
参数:
  • arch -- the architecture

  • reg_offset -- Tries to find the name of a register given the offset in the registers.

返回:

The register name

find_stack_vars_x86(func)[源代码]
static make_initial_state(project, stack_length)[源代码]
返回:

an initial state with a symbolic stack and good options for rop

static make_symbolic_state(project, reg_list, stack_length=80)[源代码]

converts an input state into a state with symbolic registers :return: the symbolic state

class angr.analyses.InitializationFinder(func=None, func_graph=None, block=None, max_iterations=1, replacements=None, overlay=None, pointers_only=False)[源代码]

基类:ForwardAnalysis, Analysis

Finds possible initializations for global data sections and generate an overlay to be used in other analyses later on.

__init__(func=None, func_graph=None, block=None, max_iterations=1, replacements=None, overlay=None, pointers_only=False)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

返回:

None

class angr.analyses.LoopFinder(functions=None, normalize=True)[源代码]

基类:Analysis

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

__init__(functions=None, normalize=True)[源代码]
class angr.analyses.PackingDetector(cfg=None, region_size_threshold=32)[源代码]

基类:Analysis

This analysis detects if a binary is likely packed or not. We may extend it to identify which packer is in use in the future.

参数:
PACKED_MIN_BYTES = 256
PACKED_ENTROPY_MIN_THRESHOLD = 0.88
__init__(cfg=None, region_size_threshold=32)[源代码]
参数:
analyze()[源代码]
class angr.analyses.PatchFinderAnalysis[源代码]

基类:Analysis

Looks for binary patches using some basic heuristics: - Looking for interleaved functions - Looking for unaligned functions

__init__()[源代码]
atypical_alignments: list[Function]
possibly_patched_out: list[PatchedOutFunctionality]
class angr.analyses.Pathfinder(start_state, goal_addr, cfg, cache_size=10000)[源代码]

基类:Analysis

参数:
__init__(start_state, goal_addr, cfg, cache_size=10000)[源代码]
参数:
cache_state(state)[源代码]
参数:

state (SimState)

marker_to_state(marker)[源代码]
返回类型:

SimState | None

参数:

marker (SimStateMarker)

analyze()[源代码]
返回类型:

bool

find_best_hypothesis_path()[源代码]
返回类型:

tuple[int, ...]

diagnose_unsat(state)[源代码]
参数:

state (SimState)

test_path(bbl_addr_trace)[源代码]
返回类型:

TestPathReport

参数:

bbl_addr_trace (tuple[int, ...])

class angr.analyses.PropagatorAnalysis(func=None, block=None, func_graph=None, base_state=None, max_iterations=30, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False, func_addr=None, gp=None, cache_results=False, key_prefix=None, profiling=False)[源代码]

基类:ForwardAnalysis, Analysis

PropagatorAnalysis implements copy propagation. It propagates values (either constant values or variables) and expressions inside a block or across a function.

PropagatorAnalysis only supports VEX. For AIL, please use SPropagator.

PropagatorAnalysis performs certain arithmetic operations between constants, including but are not limited to:

  • addition

  • subtraction

  • multiplication

  • division

  • xor

It also performs the following memory operations:

  • Loading values from a known address

  • Writing values to a stack variable

参数:
  • func_addr (int | None)

  • gp (int | None)

  • cache_results (bool)

  • key_prefix (str | None)

  • profiling (bool)

__init__(func=None, block=None, func_graph=None, base_state=None, max_iterations=30, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False, func_addr=None, gp=None, cache_results=False, key_prefix=None, profiling=False)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

  • func_addr (int | None)

  • gp (int | None)

  • cache_results (bool)

  • key_prefix (str | None)

  • profiling (bool)

返回:

None

property prop_key: tuple[str | None, str, int, bool, bool, bool]

Gets a key that represents the function and the "flavor" of the propagation result.

property replacements
class angr.analyses.ProximityGraphAnalysis(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]

基类:Analysis

Generate a proximity graph.

参数:
__init__(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]
参数:
class angr.analyses.ReachingDefinitionsAnalysis(subject=None, func_graph=None, max_iterations=30, track_tmps=False, track_consts=True, observation_points=None, init_state=None, init_context=None, state_initializer=None, cc=None, function_handler=None, observe_all=False, visited_blocks=None, dep_graph=True, observe_callback=None, canonical_size=8, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, interfunction_level=0, track_liveness=True, func_addr=None, element_limit=5, merge_into_tops=True)[源代码]

基类:ForwardAnalysis[ReachingDefinitionsState, NodeType, object, object], Analysis

ReachingDefinitionsAnalysis is a text-book implementation of a static data-flow analysis that works on either a function or a block. It supports both VEX and AIL. By registering observers to observation points, users may use this analysis to generate use-def chains, def-use chains, and reaching definitions, and perform other traditional data-flow analyses such as liveness analysis.

  • I've always wanted to find a better name for this analysis. Now I gave up and decided to live with this name for the foreseeable future (until a better name is proposed by someone else).

  • Aliasing is definitely a problem, and I forgot how aliasing is resolved in this implementation. I'll leave this as a post-graduation TODO.

  • Some more documentation and examples would be nice.

参数:
__init__(subject=None, func_graph=None, max_iterations=30, track_tmps=False, track_consts=True, observation_points=None, init_state=None, init_context=None, state_initializer=None, cc=None, function_handler=None, observe_all=False, visited_blocks=None, dep_graph=True, observe_callback=None, canonical_size=8, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, interfunction_level=0, track_liveness=True, func_addr=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
  • subject (Union[Subject, Block, Block, Function, str, None]) -- The subject of the analysis: a function, or a single basic block

  • func_graph -- Alternative graph for function.graph.

  • max_iterations -- The maximum number of iterations before the analysis is terminated.

  • track_tmps -- Whether or not temporary variables should be taken into consideration during the analysis.

  • observation_points (iterable) -- A collection of tuples of ("node"|"insn", ins_addr, OP_TYPE) defining where reaching definitions should be copied and stored. OP_TYPE can be OP_BEFORE or OP_AFTER.

  • init_state (Optional[ReachingDefinitionsState]) -- An optional initialization state. The analysis creates and works on a copy. Default to None: the analysis then initialize its own abstract state, based on the given <Subject>.

  • init_context -- If init_state is not given, this is used to initialize the context field of the initial state's CodeLocation. The only default-supported type which may go here is a tuple of integers, i.e. a callstack. Anything else requires a custom FunctionHandler.

  • cc -- Calling convention of the function.

  • function_handler (Optional[FunctionHandler]) -- The function handler to update the analysis state and results on function calls.

  • observe_all -- Observe every statement, both before and after.

  • visited_blocks -- A set of previously visited blocks.

  • dep_graph (DepGraph | bool | None) -- An initial dependency graph to add the result of the analysis to. Set it to None to skip dependency graph generation.

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

  • dep_graph -- Set this to True to generate a dependency graph for the subject. It will be available as result.dep_graph.

  • interfunction_level (int) -- The number of functions we should recurse into. This parameter is only used if function_handler is not provided.

  • track_liveness (bool) -- Whether to track liveness information. This can consume sizeable amounts of RAM on large functions. (e.g. ~15GB for a function with 4k nodes)

  • merge_into_tops (bool) -- Merge known values into TOP if TOP is present. If True: {TOP} V {0xabc} = {TOP} If False: {TOP} V {0xabc} = {TOP, 0xabc}

  • state_initializer (RDAStateInitializer | None)

  • func_addr (int | None)

  • element_limit (int)

property observed_results: dict[tuple[str, int, int], LiveDefinitions]
property all_definitions
property all_uses
property one_result
property dep_graph: DepGraph
property visited_blocks
get_reaching_definitions(**kwargs)
get_reaching_definitions_by_insn(ins_addr, op_type)[源代码]
get_reaching_definitions_by_node(node_addr, op_type)[源代码]
node_observe(node_addr, state, op_type, node_idx=None)[源代码]
参数:
  • node_addr (int) -- Address of the node.

  • state (ReachingDefinitionsState) -- The analysis state.

  • op_type (ObservationPointType) -- Type of the observation point. Must be one of the following: OP_BEFORE, OP_AFTER.

  • node_idx (Optional[int]) -- ID of the node. Used in AIL to differentiate blocks with the same address.

返回类型:

None

insn_observe(insn_addr, stmt, block, state, op_type)[源代码]
参数:
返回类型:

None

stmt_observe(stmt_idx, stmt, block, state, op_type)[源代码]
参数:
返回类型:

None

返回:

exit_observe(node_addr, exit_stmt_idx, block, state, node_idx=None)[源代码]
参数:
property subject
callsites_to(target)[源代码]
返回类型:

Iterable[FunctionCallRelationships]

参数:

target (int | str | Function)

class angr.analyses.Reassembler(syntax='intel', remove_cgc_attachments=True, log_relocations=True)[源代码]

基类:Analysis

High-level representation of a binary with a linear representation of all instructions and data regions. After calling "symbolize", it essentially acts as a binary reassembler.

Tested on CGC, x86 and x86-64 binaries.

Disclaimer: The reassembler is an empirical solution. Don't be surprised if it does not work on some binaries.

__init__(syntax='intel', remove_cgc_attachments=True, log_relocations=True)[源代码]
property instructions

Get a list of all instructions in the binary

返回:

A list of (address, instruction)

返回类型:

tuple

property relocations
property inserted_asm_before_label
property inserted_asm_after_label
property main_executable_regions

return:

property main_nonexecutable_regions

return:

section_alignment(section_name)[源代码]

Get the alignment for the specific section. If the section is not found, 16 is used as default.

参数:

section_name (str) -- The section.

返回:

The alignment in bytes.

返回类型:

int

main_executable_regions_contain(addr)[源代码]
参数:

addr

返回:

main_executable_region_limbos_contain(addr)[源代码]

Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes after the beginning of the section. We take care of that here.

参数:

addr (int) -- The address to check.

返回:

A 2-tuple of (bool, the closest base address)

返回类型:

tuple

main_nonexecutable_regions_contain(addr)[源代码]
参数:

addr (int) -- The address to check.

返回:

True if the address is inside a non-executable region, False otherwise.

返回类型:

bool

main_nonexecutable_region_limbos_contain(addr, tolerance_before=64, tolerance_after=64)[源代码]

Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes after the beginning of the section. We take care of that here.

参数:

addr (int) -- The address to check.

返回:

A 2-tuple of (bool, the closest base address)

返回类型:

tuple

register_instruction_reference(insn_addr, ref_addr, sort, operand_offset)[源代码]
register_data_reference(data_addr, ref_addr)[源代码]
add_label(name, addr)[源代码]

Add a new label to the symbol manager.

参数:
  • name (str) -- Name of the label.

  • addr (int) -- Address of the label.

返回:

None

insert_asm(addr, asm_code, before_label=False)[源代码]

Insert some assembly code at the specific address. There must be an instruction starting at that address.

参数:
  • addr (int) -- Address of insertion

  • asm_code (str) -- The assembly code to insert

返回:

None

append_procedure(name, asm_code)[源代码]

Add a new procedure with specific name and assembly code.

参数:
  • name (str) -- The name of the new procedure.

  • asm_code (str) -- The assembly code of the procedure

返回:

None

append_data(name, initial_content, size, readonly=False, sort='unknown')[源代码]

Append a new data entry into the binary with specific name, content, and size.

参数:
  • name (str) -- Name of the data entry. Will be used as the label.

  • initial_content (bytes) -- The initial content of the data entry.

  • size (int) -- Size of the data entry.

  • readonly (bool) -- If the data entry belongs to the readonly region.

  • sort (str) -- Type of the data.

返回:

None

remove_instruction(ins_addr)[源代码]
参数:

ins_addr

返回:

randomize_procedures()[源代码]
返回:

symbolize()[源代码]
assembly(comments=False, symbolized=True)[源代码]
remove_cgc_attachments()[源代码]

Remove CGC attachments.

返回:

True if CGC attachments are found and removed, False otherwise

返回类型:

bool

remove_unnecessary_stuff()[源代码]

Remove unnecessary functions and data

返回:

None

remove_unnecessary_stuff_glibc()[源代码]
fast_memory_load(addr, size, data_type, endness='Iend_LE')[源代码]

Load memory bytes from loader's memory backend.

参数:
  • addr (int) -- The address to begin memory loading.

  • size (int) -- Size in bytes.

  • data_type -- Type of the data.

  • endness (str) -- Endianness of this memory load.

返回:

Data read out of the memory.

返回类型:

int or bytes or str or None

class angr.analyses.SLivenessAnalysis(func, func_graph=None, entry=None, func_addr=None, arg_vvars=None)[源代码]

基类:Analysis

Calculates LiveIn and LiveOut sets for each block in a partial-SSA function.

参数:
__init__(func, func_graph=None, entry=None, func_addr=None, arg_vvars=None)[源代码]
参数:
interference_graph()[源代码]

Generate an interference graph based on the liveness analysis result.

返回类型:

Graph

返回:

A networkx.Graph instance.

class angr.analyses.SPropagatorAnalysis(subject, func_graph=None, only_consts=True, stack_pointer_tracker=None, func_args=None, func_addr=None)[源代码]

基类:Analysis

Constant and expression propagation that only supports SSA AIL graphs.

参数:
__init__(subject, func_graph=None, only_consts=True, stack_pointer_tracker=None, func_args=None, func_addr=None)[源代码]
参数:
property replacements
static is_global_variable_updated(func_graph, block_dict, varid, gv_addr, gv_size, defloc, useloc)[源代码]
返回类型:

bool

参数:
class angr.analyses.SReachingDefinitionsAnalysis(subject, func_addr=None, func_graph=None, func_args=None, track_tmps=False)[源代码]

基类:Analysis

Constant and expression propagation that only supports SSA AIL graphs.

参数:
__init__(subject, func_addr=None, func_graph=None, func_args=None, track_tmps=False)[源代码]
class angr.analyses.SelfModifyingCodeAnalysis(subject, max_bytes=0, state=None)[源代码]

基类:Analysis

Determine if some piece of code is self-modifying.

This determination is made by simply executing. If an address is executed that is also written to, the code is determined to be self-modifying. The determination is stored in the result property. The regions property contains a list of (addr, length) regions that were both written to and executed.

参数:
__init__(subject, max_bytes=0, state=None)[源代码]
参数:
  • subject (None | int | str | Function) -- Subject of analysis

  • max_bytes (int) -- Maximum number of bytes from subject address. 0 for no limit (default).

  • state (Optional[SimState]) -- State to begin executing from from.

regions: list[tuple[int, int]]
result: bool
class angr.analyses.SootClassHierarchy[源代码]

基类:Analysis

Generate complete hierarchy.

__init__()[源代码]
init_hierarchy()[源代码]
has_super_class(cls)[源代码]
is_subclass_including(cls_child, cls_parent)[源代码]
is_subclass(cls_child, cls_parent)[源代码]
is_visible_method(cls, method)[源代码]
is_visible_class(cls_from, cls_to)[源代码]
get_super_classes(cls)[源代码]
get_super_classes_including(cls)[源代码]
get_implementers(interface)[源代码]
get_sub_interfaces_including(interface)[源代码]
get_sub_interfaces(interface)[源代码]
get_sub_classes(cls)[源代码]
get_sub_classes_including(cls)[源代码]
resolve_abstract_dispatch(cls, method)[源代码]
resolve_concrete_dispatch(cls, method)[源代码]
resolve_special_dispatch(method, container)[源代码]
resolve_invoke(invoke_expr, method, container)[源代码]
class angr.analyses.StackPointerTracker(func, reg_offsets, block=None, track_memory=True, cross_insn_opt=True, initial_reg_values=None, resilient=True)[源代码]

基类:Analysis, ForwardAnalysis

Track the offset of stack pointer at the end of each basic block of a function.

参数:
__init__(func, reg_offsets, block=None, track_memory=True, cross_insn_opt=True, initial_reg_values=None, resilient=True)[源代码]
参数:
offset_after(addr, reg)[源代码]
offset_before(addr, reg)[源代码]
offset_after_block(block_addr, reg)[源代码]
offset_before_block(block_addr, reg)[源代码]
constant_after(addr, reg)[源代码]
constant_before(addr, reg)[源代码]
constant_after_block(block_addr, reg)[源代码]
constant_before_block(block_addr, reg)[源代码]
property inconsistent
inconsistent_for(reg)[源代码]
offsets_for(reg)[源代码]
class angr.analyses.StaticHooker(library, binary=None)[源代码]

基类:Analysis

This analysis works on statically linked binaries - it finds the library functions statically linked into the binary and hooks them with the appropriate simprocedures.

Right now it only works on unstripped binaries, but hey! There's room to grow!

__init__(library, binary=None)[源代码]
class angr.analyses.StaticObjectFinder[源代码]

基类:Analysis

This analysis tries to find objects on the heap based on calls to new(), and subsequent calls to constructors with

the 'this' pointer

__init__()[源代码]
class angr.analyses.Typehoon(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]

基类:Analysis

A spiritual tribute to the long-standing typehoon project that @jmg (John Grosen) worked on during his days in the angr team. Now I feel really bad of asking the poor guy to work directly on VEX IR without any fancy static analysis support as we have right now...

Typehoon analysis implements a pushdown system that simplifies and solves type constraints. Our type constraints are largely an implementation of the paper Polymorphic Type Inference for Machine Code by Noonan, Loginov, and Cok from GrammaTech (with missing functionality support and bugs, of course). Type constraints are collected by running VariableRecoveryFast (maybe VariableRecovery later as well) on a function, and then solved using this analysis.

User may specify ground truth, which will override all types at certain program points during constraint solving.

参数:
__init__(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]
参数:
update_variable_types(func_addr, var_to_typevars)[源代码]
参数:

func_addr (int | str)

pp_constraints()[源代码]

Pretty-print constraints between variables using the variable mapping.

返回类型:

None

pp_solution()[源代码]

Pretty-print solutions using the variable mapping.

返回类型:

None

class angr.analyses.VariableRecovery(func, max_iterations=20, store_live_variables=False)[源代码]

基类:ForwardAnalysis, VariableRecoveryBase

Recover "variables" from a function using forced execution.

While variables play a very important role in programming, it does not really exist after compiling. However, we can still identify and recovery their counterparts in binaries. It is worth noting that not every variable in source code can be identified in binaries, and not every recognized variable in binaries have a corresponding variable in the original source code. In short, there is no guarantee that the variables we identified/recognized in a binary are the same variables in its source code.

This analysis uses heuristics to identify and recovers the following types of variables: - Register variables. - Stack variables. - Heap variables. (not implemented yet) - Global variables. (not implemented yet)

This analysis takes a function as input, and performs a data-flow analysis on nodes. It runs concrete execution on every statement and hooks all register/memory accesses to discover all places that are accessing variables. It is slow, but has a more accurate analysis result. For a fast but inaccurate variable recovery, you may consider using VariableRecoveryFast.

This analysis follows SSA, which means every write creates a new variable in registers or memory (statck, heap, etc.). Things may get tricky when overlapping variable (in memory, as you cannot really have overlapping accesses to registers) accesses exist, and in such cases, a new variable will be created, and this new variable will overlap with one or more existing variables. A decision procedure (which is pretty much TODO) is required at the end of this analysis to resolve the conflicts between overlapping variables.

__init__(func, max_iterations=20, store_live_variables=False)[源代码]
参数:

func (knowledge.Function) -- The function to analyze.

class angr.analyses.VariableRecoveryFast(func, func_graph=None, max_iterations=2, low_priority=False, track_sp=True, func_args=None, store_live_variables=False, unify_variables=True, func_arg_vvars=None, vvar_to_vvar=None)[源代码]

基类:ForwardAnalysis, VariableRecoveryBase

Recover "variables" from a function by keeping track of stack pointer offsets and pattern matching VEX statements.

If calling conventions are recovered prior to running VariableRecoveryFast, variables can be recognized more accurately. However, it is not a requirement. In this case, the function graph you pass must contain information indicating the call-out sites inside the analyzed function. These graph edges must be annotated with either "type": "call" or "outside": True.

参数:
__init__(func, func_graph=None, max_iterations=2, low_priority=False, track_sp=True, func_args=None, store_live_variables=False, unify_variables=True, func_arg_vvars=None, vvar_to_vvar=None)[源代码]

Constructor

参数:
返回:

None

class angr.analyses.Veritesting(input_state, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None)[源代码]

基类:Analysis

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

cfg_cache = {}
all_stashes = ('successful', 'errored', 'deadended', 'deviated', 'unconstrained')
__init__(input_state, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None)[源代码]

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

参数:
  • input_state -- The initial state to begin the execution with.

  • boundaries -- Addresses where execution should stop.

  • loop_unrolling_limit -- The maximum times that Veritesting should unroll a loop for.

  • enable_function_inlining -- Whether we should enable function inlining and syscall inlining.

  • terminator -- A callback function that takes a state as parameter. Veritesting will terminate if this function returns True.

  • deviation_filter -- A callback function that takes a state as parameter. Veritesting will put the state into "deviated" stash if this function returns True.

is_not_in_cfg(s)[源代码]

Returns if s.addr is not a proper node in our CFG.

参数:

s (SimState) -- The SimState instance to test.

Returns bool:

False if our CFG contains p.addr, True otherwise.

is_overbound(state)[源代码]

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

param SimState state: SimState instance to check returns bool: True if outside of mem/loop_ctr boundary

class angr.analyses.VtableFinder[源代码]

基类:Analysis

This analysis locates Vtables in a binary based on heuristics taken from - "Reconstruction of Class Hierarchies for Decompilation of C++ Programs"

__init__()[源代码]
is_cross_referenced(addr)[源代码]
is_function(addr)[源代码]
analyze()[源代码]
create_extract_vtable(start_addr, sec_size)[源代码]
class angr.analyses.XRefsAnalysis(func=None, func_graph=None, block=None, max_iterations=1, replacements=None)[源代码]

基类:ForwardAnalysis, Analysis

XRefsAnalysis recovers in-depth x-refs (cross-references) in disassembly code.

Here is an example:

.text:
000023C8                 LDR     R2, =time_now
000023CA                 LDR     R3, [R2]
000023CC                 ADDS    R3, #1
000023CE                 STR     R3, [R2]
000023D0                 BX      LR

.bss:
1FFF36F4 time_now        % 4

You will have the following x-refs for time_now:

23c8 - offset
23ca - read access
23ce - write access
__init__(func=None, func_graph=None, block=None, max_iterations=1, replacements=None)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

返回:

None

angr.analyses.register_analysis(cls, name)[源代码]
class angr.analyses.analysis.AnalysisLogEntry(message, exc_info=False)[源代码]

基类:object

__init__(message, exc_info=False)[源代码]
format()[源代码]
返回类型:

str

class angr.analyses.analysis.AnalysesHub(project)[源代码]

基类:PluginVendor[A]

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

__init__(project)[源代码]
reload_analyses(**kwargs)
class angr.analyses.analysis.KnownAnalysesPlugin(*args, **kwargs)[源代码]

基类:Protocol

Identifier: type[Identifier]
CalleeCleanupFinder: type[CalleeCleanupFinder]
VSA_DDG: type[VSA_DDG]
CDG: type[CDG]
BinDiff: type[BinDiff]
CFGEmulated: type[CFGEmulated]
CFB: type[CFBlanket]
CFBlanket: type[CFBlanket]
CFG: type[CFG]
CFGFast: type[CFGFast]
StaticHooker: type[StaticHooker]
DDG: type[DDG]
CongruencyCheck: type[CongruencyCheck]
Reassembler: type[Reassembler]
BackwardSlice: type[BackwardSlice]
BinaryOptimizer: type[BinaryOptimizer]
VFG: type[VFG]
LoopFinder: type[LoopFinder]
Disassembly: type[Disassembly]
Veritesting: type[Veritesting]
CodeTagging: type[CodeTagging]
BoyScout: type[BoyScout]
VariableRecoveryFast: type[VariableRecoveryFast]
VariableRecovery: type[VariableRecovery]
ReachingDefinitions: type[ReachingDefinitionsAnalysis]
CompleteCallingConventions: type[CompleteCallingConventionsAnalysis]
Clinic: type[Clinic]
Propagator: type[PropagatorAnalysis]
CallingConvention: type[CallingConventionAnalysis]
Decompiler: type[Decompiler]
XRefs: type[XRefsAnalysis]
__init__(*args, **kwargs)
class angr.analyses.analysis.AnalysesHubWithDefault(project)[源代码]

基类:AnalysesHub, KnownAnalysesPlugin

This class has type-hinting for all built-in analyses plugin

class angr.analyses.analysis.AnalysisFactory(project, analysis_cls)[源代码]

基类:Generic[A]

参数:
__init__(project, analysis_cls)[源代码]
参数:
prep(fail_fast=None, kb=None, progress_callback=None, show_progressbar=False)[源代码]
返回类型:

type[TypeVar(A, bound= Analysis)]

参数:
class angr.analyses.analysis.Analysis[源代码]

基类:object

This class represents an analysis on the program.

变量:
  • 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: list[AnalysisLogEntry] = []
named_errors: defaultdict[str, list[AnalysisLogEntry]] = {}
angr.analyses.analysis.register_analysis(cls, name)[源代码]
class angr.analyses.forward_analysis.CallGraphVisitor(callgraph)[源代码]

基类:GraphVisitor

参数:

callgraph (networkx.DiGraph)

__init__(callgraph)[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.ForwardAnalysis(order_jobs=False, allow_merging=False, allow_widening=False, status_callback=None, graph_visitor=None)[源代码]

基类:Generic[AnalysisState, NodeType, JobType, JobKey]

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

In short, ForwardAnalysis performs a forward data-flow analysis by traversing a graph, compute on abstract values, and store results in abstract states. The user can specify what graph to traverse, how a graph should be traversed, how abstract values and abstract states are defined, etc.

ForwardAnalysis has a few options to toggle, making it suitable to be the base class of several different styles of forward data-flow analysis implementations.

ForwardAnalysis supports a special mode when no graph is available for traversal (for example, when a CFG is being initialized and constructed, no other graph can be used). In that case, the graph traversal functionality is disabled, and the optimal graph traversal order is not guaranteed. The user can provide a job sorting method to sort the jobs in queue and optimize traversal order.

Feel free to discuss with me (Fish) if you have any suggestions or complaints.

参数:
__init__(order_jobs=False, allow_merging=False, allow_widening=False, status_callback=None, graph_visitor=None)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

  • status_callback (Callable[[type[ForwardAnalysis]], Any] | None)

返回:

None

property should_abort

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

property graph: DiGraph
property jobs
abort()[源代码]

Abort the analysis :return: None

has_job(job)[源代码]

Checks whether there exists another job which has the same job key. :type job: TypeVar(JobType) :param job: The job to check.

返回类型:

bool

返回:

True if there exists another job with the same key, False otherwise.

参数:

job (JobType)

downsize()[源代码]
class angr.analyses.forward_analysis.FunctionGraphVisitor(func, graph=None)[源代码]

基类:GraphVisitor

参数:

func (knowledge.Function)

__init__(func, graph=None)[源代码]
resume_with_new_graph(graph)[源代码]

We can only reasonably reuse existing results if the node index of the already traversed nodes are the same as the ones from the new graph. Otherwise, we always restart.

返回类型:

bool

返回:

True if we are resuming, False if reset() is called.

参数:

graph (DiGraph)

successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

back_edges()[源代码]

Get a list of back edges. This function is optional. If not overridden, the traverser cannot achieve an optimal graph traversal order.

返回类型:

list[tuple[TypeVar(NodeType), TypeVar(NodeType)]]

返回:

A list of back edges (source -> destination).

class angr.analyses.forward_analysis.LoopVisitor(loop)[源代码]

基类:GraphVisitor

参数:

loop (angr.analyses.loopfinder.Loop) -- The loop to visit.

__init__(loop)[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.SingleNodeGraphVisitor(node)[源代码]

基类:GraphVisitor

参数:

node -- The single node that should be in the graph.

__init__(node)[源代码]
node
node_returned
reset()[源代码]

Reset the internal node traversal state. Must be called prior to visiting future nodes.

返回:

None

next_node()[源代码]

Get the next node to visit.

返回:

A node in the graph.

successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.forward_analysis.ForwardAnalysis(order_jobs=False, allow_merging=False, allow_widening=False, status_callback=None, graph_visitor=None)[源代码]

基类:Generic[AnalysisState, NodeType, JobType, JobKey]

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

In short, ForwardAnalysis performs a forward data-flow analysis by traversing a graph, compute on abstract values, and store results in abstract states. The user can specify what graph to traverse, how a graph should be traversed, how abstract values and abstract states are defined, etc.

ForwardAnalysis has a few options to toggle, making it suitable to be the base class of several different styles of forward data-flow analysis implementations.

ForwardAnalysis supports a special mode when no graph is available for traversal (for example, when a CFG is being initialized and constructed, no other graph can be used). In that case, the graph traversal functionality is disabled, and the optimal graph traversal order is not guaranteed. The user can provide a job sorting method to sort the jobs in queue and optimize traversal order.

Feel free to discuss with me (Fish) if you have any suggestions or complaints.

参数:
__init__(order_jobs=False, allow_merging=False, allow_widening=False, status_callback=None, graph_visitor=None)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

  • status_callback (Callable[[type[ForwardAnalysis]], Any] | None)

返回:

None

property should_abort

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

property graph: DiGraph
property jobs
abort()[源代码]

Abort the analysis :return: None

has_job(job)[源代码]

Checks whether there exists another job which has the same job key. :type job: TypeVar(JobType) :param job: The job to check.

返回类型:

bool

返回:

True if there exists another job with the same key, False otherwise.

参数:

job (JobType)

downsize()[源代码]
class angr.analyses.forward_analysis.job_info.JobInfo(key, job)[源代码]

基类:Generic[JobType, JobKey]

Stores information of each job.

参数:
  • key (JobKey)

  • job (JobType)

__init__(key, job)[源代码]
参数:
  • key (JobKey)

  • job (JobType)

property job: JobType

Get the latest available job.

返回:

The latest available job.

property merged_jobs
property widened_jobs
add_job(job, merged=False, widened=False)[源代码]

Appended a new job to this JobInfo node. :type job: :param job: The new job to append. :param bool merged: Whether it is a merged job or not. :param bool widened: Whether it is a widened job or not.

class angr.analyses.forward_analysis.visitors.CallGraphVisitor(callgraph)[源代码]

基类:GraphVisitor

参数:

callgraph (networkx.DiGraph)

__init__(callgraph)[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.visitors.FunctionGraphVisitor(func, graph=None)[源代码]

基类:GraphVisitor

参数:

func (knowledge.Function)

__init__(func, graph=None)[源代码]
resume_with_new_graph(graph)[源代码]

We can only reasonably reuse existing results if the node index of the already traversed nodes are the same as the ones from the new graph. Otherwise, we always restart.

返回类型:

bool

返回:

True if we are resuming, False if reset() is called.

参数:

graph (DiGraph)

successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

back_edges()[源代码]

Get a list of back edges. This function is optional. If not overridden, the traverser cannot achieve an optimal graph traversal order.

返回类型:

list[tuple[TypeVar(NodeType), TypeVar(NodeType)]]

返回:

A list of back edges (source -> destination).

class angr.analyses.forward_analysis.visitors.LoopVisitor(loop)[源代码]

基类:GraphVisitor

参数:

loop (angr.analyses.loopfinder.Loop) -- The loop to visit.

__init__(loop)[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.visitors.SingleNodeGraphVisitor(node)[源代码]

基类:GraphVisitor

参数:

node -- The single node that should be in the graph.

__init__(node)[源代码]
node
node_returned
reset()[源代码]

Reset the internal node traversal state. Must be called prior to visiting future nodes.

返回:

None

next_node()[源代码]

Get the next node to visit.

返回:

A node in the graph.

successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.visitors.call_graph.CallGraphVisitor(callgraph)[源代码]

基类:GraphVisitor

参数:

callgraph (networkx.DiGraph)

__init__(callgraph)[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.visitors.function_graph.FunctionGraphVisitor(func, graph=None)[源代码]

基类:GraphVisitor

参数:

func (knowledge.Function)

__init__(func, graph=None)[源代码]
resume_with_new_graph(graph)[源代码]

We can only reasonably reuse existing results if the node index of the already traversed nodes are the same as the ones from the new graph. Otherwise, we always restart.

返回类型:

bool

返回:

True if we are resuming, False if reset() is called.

参数:

graph (DiGraph)

successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

back_edges()[源代码]

Get a list of back edges. This function is optional. If not overridden, the traverser cannot achieve an optimal graph traversal order.

返回类型:

list[tuple[TypeVar(NodeType), TypeVar(NodeType)]]

返回:

A list of back edges (source -> destination).

class angr.analyses.forward_analysis.visitors.graph.GraphVisitor[源代码]

基类:Generic[NodeType]

A graph visitor takes a node in the graph and returns its successors. Typically, it visits a control flow graph, and returns successors of a CFGNode each time. This is the base class of all graph visitors.

__init__()[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node (TypeVar(NodeType)) -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node (TypeVar(NodeType)) -- The node to work with.

返回类型:

list[TypeVar(NodeType)]

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回类型:

list[TypeVar(NodeType)]

返回:

A list of sorted nodes.

back_edges()[源代码]

Get a list of back edges. This function is optional. If not overridden, the traverser cannot achieve an optimal graph traversal order.

返回类型:

list[tuple[TypeVar(NodeType), TypeVar(NodeType)]]

返回:

A list of back edges (source -> destination).

nodes()[源代码]

Return an iterator of nodes following an optimal traversal order.

返回类型:

Iterator[TypeVar(NodeType)]

返回:

nodes_iter(**kwargs)
reset()[源代码]

Reset the internal node traversal state. Must be called prior to visiting future nodes.

返回:

None

next_node()[源代码]

Get the next node to visit.

返回类型:

Optional[TypeVar(NodeType)]

返回:

A node in the graph.

all_successors(node, skip_reached_fixedpoint=False)[源代码]

Returns all successors to the specific node.

参数:

node (TypeVar(NodeType)) -- A node in the graph.

返回:

A set of nodes that are all successors to the given node.

返回类型:

set

revisit_successors(node, include_self=True)[源代码]

Revisit a node in the future. As a result, the successors to this node will be revisited as well.

参数:

node (TypeVar(NodeType)) -- The node to revisit in the future.

返回类型:

None

返回:

None

revisit_node(node)[源代码]

Revisit a node in the future. Do not include its successors immediately.

参数:

node (TypeVar(NodeType)) -- The node to revisit in the future.

返回类型:

None

返回:

None

reached_fixedpoint(node)[源代码]

Mark a node as reached fixed-point. This node as well as all its successors will not be visited in the future.

参数:

node (TypeVar(NodeType)) -- The node to mark as reached fixed-point.

返回类型:

None

返回:

None

class angr.analyses.forward_analysis.visitors.loop.LoopVisitor(loop)[源代码]

基类:GraphVisitor

参数:

loop (angr.analyses.loopfinder.Loop) -- The loop to visit.

__init__(loop)[源代码]
successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

class angr.analyses.forward_analysis.visitors.single_node_graph.SingleNodeGraphVisitor(node)[源代码]

基类:GraphVisitor

参数:

node -- The single node that should be in the graph.

__init__(node)[源代码]
node
node_returned
reset()[源代码]

Reset the internal node traversal state. Must be called prior to visiting future nodes.

返回:

None

next_node()[源代码]

Get the next node to visit.

返回:

A node in the graph.

successors(node)[源代码]

Get successors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of successors.

返回类型:

list

predecessors(node)[源代码]

Get predecessors of a node. The node should be in the graph.

参数:

node -- The node to work with.

返回:

A list of predecessors.

sort_nodes(nodes=None)[源代码]

Get a list of all nodes sorted in an optimal traversal order.

参数:

nodes (iterable) -- A collection of nodes to sort. If none, all nodes in the graph will be used to sort.

返回:

A list of sorted nodes.

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

基类:Analysis

Represents a backward slice of the program.

__init__(cfg, cdg, ddg, targets=None, cfg_node=None, stmt_id=None, control_flow_slice=False, same_function=False, no_construct=False)[源代码]

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

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

参数:
  • cfg -- The control flow graph.

  • cdg -- The control dependence graph.

  • ddg -- The data dependence graph.

  • targets -- A list of "target" that specify targets of the backward slices. Each target can be a tuple in form of (cfg_node, stmt_idx), or a CodeLocation instance.

  • cfg_node -- Deprecated. The target CFGNode to reach. It should exist in the CFG.

  • stmt_id -- Deprecated. The target statement to reach.

  • control_flow_slice -- True/False, indicates whether we should slice only based on CFG. Sometimes when acquiring DDG is difficult or impossible, you can just create a slice on your CFG. Well, if you don't even have a CFG, then...

  • no_construct -- Only used for testing and debugging to easily create a BackwardSlice object.

dbg_repr(max_display=10)[源代码]

Debugging output of this slice.

参数:

max_display -- The maximum number of SimRun slices to show.

返回:

A string representation.

dbg_repr_run(run_addr)[源代码]

Debugging output of a single SimRun slice.

参数:

run_addr -- Address of the SimRun.

返回:

A string representation.

annotated_cfg(start_point=None)[源代码]

Returns an AnnotatedCFG based on slicing result.

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

参数:
  • simrun_addr -- Address of the SimRun.

  • stmt_idx -- Statement ID.

  • taint_type -- Type of the taint, might be one of the following: 'reg', 'tmp', 'mem'.

  • simrun_whitelist -- A list of SimRun addresses that are whitelisted, i.e. the tainted exit will be ignored if it is in those SimRuns.

返回:

True/False

is_taint_impacting_stack_pointers(simrun_addr, stmt_idx, taint_type, simrun_whitelist=None)[源代码]

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

参数:
  • simrun_addr -- Address of the SimRun.

  • stmt_idx -- Statement ID.

  • taint_type -- Type of the taint, might be one of the following: 'reg', 'tmp', 'mem'.

  • simrun_whitelist -- A list of SimRun addresses that are whitelisted.

返回:

True/False.

exception angr.analyses.bindiff.UnmatchedStatementsException[源代码]

基类:Exception

class angr.analyses.bindiff.Difference(diff_type, value_a, value_b)[源代码]

基类:object

__init__(diff_type, value_a, value_b)[源代码]
class angr.analyses.bindiff.ConstantChange(offset, value_a, value_b)[源代码]

基类:object

__init__(offset, value_a, value_b)[源代码]
angr.analyses.bindiff.differing_constants(block_a, block_b)[源代码]

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

参数:
  • block_a -- The first block to compare.

  • block_b -- The second block to compare.

返回:

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

angr.analyses.bindiff.compare_statement_dict(statement_1, statement_2)[源代码]
class angr.analyses.bindiff.NormalizedBlock(block, function)[源代码]

基类:object

__init__(block, function)[源代码]
class angr.analyses.bindiff.NormalizedFunction(function)[源代码]

基类:object

参数:

function (Function)

__init__(function)[源代码]
参数:

function (Function)

class angr.analyses.bindiff.FunctionDiff(function_a, function_b, bindiff=None)[源代码]

基类:object

This class computes the a diff between two functions.

参数:
__init__(function_a, function_b, bindiff=None)[源代码]
参数:
  • function_a (Function) -- The first angr Function object to diff.

  • function_b (Function) -- The second angr Function object.

  • bindiff -- An optional Bindiff object. Used for some extra normalization during basic block comparison.

property probably_identical

Whether or not these two functions are identical.

Type:

returns

property identical_blocks

A list of block matches which appear to be identical

Type:

returns

property differing_blocks

A list of block matches which appear to differ

Type:

returns

property blocks_with_differing_constants

A list of block matches which appear to differ

Type:

return

property block_matches
property unmatched_blocks
static get_normalized_block(addr, function)[源代码]
参数:
  • addr -- Where to start the normalized block.

  • function -- A function containing the block address.

返回:

A normalized basic block.

block_similarity(block_a, block_b)[源代码]
参数:
  • block_a -- The first block address.

  • block_b -- The second block address.

返回:

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

blocks_probably_identical(block_a, block_b, check_constants=False)[源代码]
参数:
  • block_a -- The first block address.

  • block_b -- The second block address.

  • check_constants -- Whether or not to require matching constants in blocks.

返回:

Whether or not the blocks appear to be identical.

class angr.analyses.bindiff.BinDiff(other_project, enable_advanced_backward_slicing=False, cfg_a=None, cfg_b=None)[源代码]

基类:Analysis

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

__init__(other_project, enable_advanced_backward_slicing=False, cfg_a=None, cfg_b=None)[源代码]
参数:

other_project -- The second project to diff

functions_probably_identical(func_a_addr, func_b_addr, check_consts=False)[源代码]

Compare two functions and return True if they appear identical.

参数:
  • func_a_addr -- The address of the first function (in the first binary).

  • func_b_addr -- The address of the second function (in the second binary).

返回:

Whether or not the functions appear to be identical.

property identical_functions

A list of function matches that appear to be identical

Type:

returns

property differing_functions

A list of function matches that appear to differ

Type:

returns

differing_functions_with_consts()[源代码]
返回:

A list of function matches that appear to differ including just by constants

property differing_blocks

A list of block matches that appear to differ

Type:

returns

property identical_blocks

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

property blocks_with_differing_constants

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

Type:

return

property unmatched_functions
get_function_diff(function_addr_a, function_addr_b)[源代码]
参数:
  • function_addr_a -- The address of the first function (in the first binary)

  • function_addr_b -- The address of the second function (in the second binary)

返回:

the FunctionDiff of the two functions

class angr.analyses.boyscout.BoyScout(cookiesize=1)[源代码]

基类:Analysis

Try to determine the architecture and endieness of a binary blob

__init__(cookiesize=1)[源代码]
class angr.analyses.calling_convention.CallingConventionAnalysis(func, cfg=None, analyze_callsites=False, caller_func_addr=None, callsite_block_addr=None, callsite_insn_addr=None, func_graph=None, input_args=None, retval_size=None)[源代码]

基类:Analysis

Analyze the calling convention of a function and guess a probable prototype.

The calling convention of a function can be inferred at both its call sites and the function itself. At call sites, we consider all register and stack variables that are not alive after the function call as parameters to this function. In the function itself, we consider all register and stack variables that are read but without initialization as parameters. Then we synthesize the information from both locations and make a reasonable inference of calling convention of this function.

变量:
  • _function -- The function to recover calling convention for.

  • _variable_manager -- A handy accessor to the variable manager.

  • _cfg -- A reference of the CFGModel of the current binary. It is used to discover call sites of the current function in order to perform analysis at call sites.

  • analyze_callsites -- True if we should analyze all call sites of the current function to determine the calling convention and arguments. This can be time-consuming if there are many call sites to analyze.

  • cc -- The recovered calling convention for the function.

参数:
__init__(func, cfg=None, analyze_callsites=False, caller_func_addr=None, callsite_block_addr=None, callsite_insn_addr=None, func_graph=None, input_args=None, retval_size=None)[源代码]
参数:
is_va_start_amd64(func)[源代码]
返回类型:

tuple[bool, int | None]

参数:

func (Function)

class angr.analyses.calling_convention.FactCollector(func, max_depth=5)[源代码]

基类:Analysis

An extremely fast analysis that extracts necessary facts of a function for CallingConventionAnalysis to make decision on the calling convention and prototype of a function.

参数:
__init__(func, max_depth=5)[源代码]
参数:
class angr.analyses.complete_calling_conventions.CallingConventionAnalysisMode(value)[源代码]

基类:Enum

The mode of calling convention analysis.

FAST: Using FactCollector to collect facts, then use facts for calling convention analysis. VARIABLES: Using variables in VariableManager for calling convention analysis.

FAST = 'fast'
VARIABLES = 'variables'
class angr.analyses.complete_calling_conventions.CompleteCallingConventionsAnalysis(mode=CallingConventionAnalysisMode.FAST, recover_variables=False, low_priority=False, force=False, cfg=None, analyze_callsites=False, skip_signature_matched_functions=False, max_function_blocks=None, max_function_size=None, workers=0, cc_callback=None, prioritize_func_addrs=None, skip_other_funcs=False, auto_start=True, func_graphs=None)[源代码]

基类:Analysis

Implements full-binary calling convention analysis. During the initial analysis of a binary, you may set recover_variables to True so that it will perform variable recovery on each function before performing calling convention analysis.

参数:
__init__(mode=CallingConventionAnalysisMode.FAST, recover_variables=False, low_priority=False, force=False, cfg=None, analyze_callsites=False, skip_signature_matched_functions=False, max_function_blocks=None, max_function_size=None, workers=0, cc_callback=None, prioritize_func_addrs=None, skip_other_funcs=False, auto_start=True, func_graphs=None)[源代码]
参数:
  • recover_variables -- Recover variables on each function before performing calling convention analysis.

  • low_priority -- Run in the background - periodically release GIL.

  • force -- Perform calling convention analysis on functions even if they have calling conventions or prototypes already specified (or previously recovered).

  • cfg (Optional[CFGModel]) -- The control flow graph model, which will be passed to CallingConventionAnalysis.

  • analyze_callsites (bool) -- Consider artifacts at call sites when performing calling convention analysis.

  • skip_signature_matched_functions (bool) -- Do not perform calling convention analysis on functions that match against existing FLIRT signatures.

  • max_function_blocks (Optional[int]) -- Do not perform calling convention analysis on functions with more than the specified number of blocks. Setting it to None disables this check.

  • max_function_size (Optional[int]) -- Do not perform calling convention analysis on functions whose sizes are more than max_function_size. Setting it to None disables this check.

  • workers (int) -- Number of multiprocessing workers.

  • mode (CallingConventionAnalysisMode)

  • cc_callback (Callable | None)

  • prioritize_func_addrs (Iterable[int] | None)

  • skip_other_funcs (bool)

  • auto_start (bool)

  • func_graphs (dict[int, DiGraph] | None)

work()[源代码]
prioritize_functions(func_addrs_to_prioritize)[源代码]

Prioritize the analysis of specified functions.

参数:

func_addrs_to_prioritize (Iterable[int]) -- A collection of function addresses to analyze first.

static function_needs_variable_recovery(func)[源代码]

Check if running variable recovery on the function is the only way to determine the calling convention of the this function.

We do not need to run variable recovery to determine the calling convention of a function if: - The function is a SimProcedure. - The function is a PLT stub. - The function is a library function and we already know its prototype.

参数:

func -- The function object.

返回:

True if we must run VariableRecovery before we can determine what the calling convention of this function is. False otherwise.

返回类型:

bool

exception angr.analyses.soot_class_hierarchy.SootClassHierarchyError(msg)[源代码]

基类:Exception

__init__(msg)[源代码]
exception angr.analyses.soot_class_hierarchy.NoConcreteDispatch(msg)[源代码]

基类:SootClassHierarchyError

__init__(msg)[源代码]
class angr.analyses.soot_class_hierarchy.SootClassHierarchy[源代码]

基类:Analysis

Generate complete hierarchy.

__init__()[源代码]
init_hierarchy()[源代码]
has_super_class(cls)[源代码]
is_subclass_including(cls_child, cls_parent)[源代码]
is_subclass(cls_child, cls_parent)[源代码]
is_visible_method(cls, method)[源代码]
is_visible_class(cls_from, cls_to)[源代码]
get_super_classes(cls)[源代码]
get_super_classes_including(cls)[源代码]
get_implementers(interface)[源代码]
get_sub_interfaces_including(interface)[源代码]
get_sub_interfaces(interface)[源代码]
get_sub_classes(cls)[源代码]
get_sub_classes_including(cls)[源代码]
resolve_abstract_dispatch(cls, method)[源代码]
resolve_concrete_dispatch(cls, method)[源代码]
resolve_special_dispatch(method, container)[源代码]
resolve_invoke(invoke_expr, method, container)[源代码]
class angr.analyses.cfg.CFG(**kwargs)[源代码]

基类:CFGFast

tl;dr: CFG is just a wrapper around CFGFast for compatibility issues. It will be fully replaced by CFGFast in future releases. Feel free to use CFG if you intend to use CFGFast. Please use CFGEmulated if you have to use the old, slow, dynamically-generated version of CFG.

For multiple historical reasons, angr's CFG is accurate but slow, which does not meet what most people expect. We developed CFGFast for light-speed CFG recovery, and renamed the old CFG class to CFGEmulated. For compatibility concerns, CFG was kept as an alias to CFGEmulated.

However, so many new users of angr would load up a binary and generate a CFG immediately after running "pip install angr", and draw the conclusion that "angr's CFG is so slow - angr must be unusable!" Therefore, we made the hard decision: CFG will be an alias to CFGFast, instead of CFGEmulated.

To ease the transition of your existing code and script, the following changes are made:

  • A CFG class, which is a sub class of CFGFast, is created.

  • You will see both a warning message printed out to stderr and an exception raised by angr if you are passing CFG any parameter that only CFGEmulated supports. This exception is not a sub class of AngrError, so you wouldn't capture it with your old code by mistake.

  • In the near future, this wrapper class will be removed completely, and CFG will be a simple alias to CFGFast.

We expect most interfaces are the same between CFGFast and CFGEmulated. Apparently some functionalities (like context-sensitivity, and state keeping) only exist in CFGEmulated, which is when you want to use CFGEmulated instead.

__init__(**kwargs)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

返回:

None

class angr.analyses.cfg.CFBlanket(exclude_region_types=None, on_object_added=None)[源代码]

基类:Analysis

A Control-Flow Blanket is a representation for storing all instructions, data entries, and bytes of a full program.

Region types: - section - segment - extern - tls - kernel

参数:
  • exclude_region_types (set[str] | None)

  • on_object_added (Callable[[int, Any], None] | None)

__init__(exclude_region_types=None, on_object_added=None)[源代码]
参数:
  • on_object_added (Optional[Callable[[int, Any], None]]) -- Callable with parameters (addr, obj) called after an object is added to the blanket.

  • exclude_region_types (set[str] | None)

property regions

Return all memory regions.

floor_addr(addr)[源代码]
floor_item(addr)[源代码]
floor_items(addr=None, reverse=False)[源代码]
ceiling_addr(addr)[源代码]
ceiling_item(addr)[源代码]
ceiling_items(addr=None, reverse=False, include_first=True)[源代码]
add_obj(addr, obj)[源代码]

Adds an object obj to the blanket at the specified address addr

add_function(func)[源代码]

Add a function func and all blocks of this function to the blanket.

dbg_repr()[源代码]

The debugging representation of this CFBlanket.

返回:

The debugging representation of this CFBlanket.

返回类型:

str

class angr.analyses.cfg.CFGArchOptions(arch, **options)[源代码]

基类:object

Stores architecture-specific options and settings, as well as the detailed explanation of those options and settings.

Suppose ao is the CFGArchOptions object, and there is an option called ret_jumpkind_heuristics, you can access it by ao.ret_jumpkind_heuristics and set its value via ao.ret_jumpkind_heuristics = True

变量:
  • OPTIONS (dict) -- A dict of all default options for different architectures.

  • arch (archinfo.Arch) -- The architecture object.

  • _options (dict) -- Values of all CFG options that are specific to the current architecture.

OPTIONS = {'ARMCortexM': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, False)}, 'ARMEL': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, True)}, 'ARMHF': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, True)}}
__init__(arch, **options)[源代码]

Constructor.

参数:
  • arch (archinfo.Arch) -- The architecture instance.

  • options (dict) -- Architecture-specific options, which will be used to initialize this object.

arch = None
class angr.analyses.cfg.CFGBase(sort, context_sensitivity_level, normalize=False, binary=None, objects=None, regions=None, exclude_sparse_regions=True, skip_specific_regions=True, force_segment=False, base_state=None, resolve_indirect_jumps=True, indirect_jump_resolvers=None, indirect_jump_target_limit=100000, detect_tail_calls=False, low_priority=False, skip_unmapped_addrs=True, sp_tracking_track_memory=True, model=None)[源代码]

基类:Analysis

The base class for control flow graphs.

tag: str | None = None
__init__(sort, context_sensitivity_level, normalize=False, binary=None, objects=None, regions=None, exclude_sparse_regions=True, skip_specific_regions=True, force_segment=False, base_state=None, resolve_indirect_jumps=True, indirect_jump_resolvers=None, indirect_jump_target_limit=100000, detect_tail_calls=False, low_priority=False, skip_unmapped_addrs=True, sp_tracking_track_memory=True, model=None)[源代码]
参数:
  • sort (str) -- 'fast' or 'emulated'.

  • context_sensitivity_level (int) -- The level of context-sensitivity of this CFG (see documentation for further details). It ranges from 0 to infinity.

  • normalize (bool) -- Whether the CFG as well as all Function graphs should be normalized.

  • binary (cle.backends.Backend) -- The binary to recover CFG on. By default, the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default, it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • base_state (angr.SimState) -- A state to use as a backer for all memory loads.

  • resolve_indirect_jumps (bool) -- Whether to try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • indirect_jump_target_limit (int) -- Maximum indirect jump targets to be recovered.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • detect_tail_calls (bool) -- Aggressive tail-call optimization detection. This option is only respected in make_functions().

  • sp_tracking_track_memory (bool) -- Whether or not to track memory writes if tracking the stack pointer. This increases the accuracy of stack pointer tracking, especially for architectures without a base pointer. Only used if detect_tail_calls is enabled.

  • model (None or CFGModel) -- The CFGModel instance to write to. A new CFGModel instance will be created and registered with the knowledge base if model is None.

返回:

None

property model: CFGModel

Get the CFGModel instance. :return: The CFGModel instance that this analysis currently uses.

property normalized
property context_sensitivity_level
property functions

A reference to the FunctionManager in the current knowledge base.

返回:

FunctionManager with all functions

返回类型:

angr.knowledge_plugins.FunctionManager

make_copy(copy_to)[源代码]

Copy self attributes to the new object.

参数:

copy_to (CFGBase) -- The target to copy to.

返回:

None

copy()[源代码]
output()[源代码]
generate_index()[源代码]

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

返回:

None

get_predecessors(**kwargs)
get_successors(**kwargs)
get_successors_and_jumpkind(**kwargs)
get_all_predecessors(**kwargs)
get_all_successors(**kwargs)
get_node(**kwargs)
get_any_node(**kwargs)
get_all_nodes(**kwargs)
nodes(**kwargs)
nodes_iter(**kwargs)
get_loop_back_edges()[源代码]
get_branching_nodes(**kwargs)
get_exit_stmt_idx(**kwargs)
property graph: networkx.DiGraph[CFGNode]
remove_edge(block_from, block_to)[源代码]
is_thumb_addr(addr)[源代码]
normalize()[源代码]

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

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

返回:

None

mark_function_alignments()[源代码]

Find all potential function alignments and mark them.

Note that it is not always correct to simply remove them, because these functions may not be actual alignments but part of an actual function, and is incorrectly marked as an individual function because of failures in resolving indirect jumps. An example is in the test binary x86_64/dir_gcc_-O0 0x40541d (indirect jump at 0x4051b0). If the indirect jump cannot be correctly resolved, removing function 0x40541d will cause a missing label failure in reassembler.

返回:

None

make_functions()[源代码]

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

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

  • A block may only belong to one function.

  • Small functions lying inside the startpoint and the endpoint of another function will be merged with the other function

  • Tail call optimizations are detected.

  • PLT stubs are aligned by 16.

返回:

None

class angr.analyses.cfg.CFGEmulated(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, indirect_jump_target_limit=100000, resolve_indirect_jumps=True, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, indirect_jump_resolvers=None, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None, state_add_options=None, state_remove_options=None, model=None)[源代码]

基类:ForwardAnalysis, CFGBase

This class represents a control-flow graph.

tag: str | None = 'CFGEmulated'
__init__(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, indirect_jump_target_limit=100000, resolve_indirect_jumps=True, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, indirect_jump_resolvers=None, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None, state_add_options=None, state_remove_options=None, model=None)[源代码]

All parameters are optional.

参数:
  • context_sensitivity_level -- The level of context-sensitivity of this CFG (see documentation for further details). It ranges from 0 to infinity. Default 1.

  • avoid_runs -- A list of runs to avoid.

  • enable_function_hints -- Whether to use function hints (constants that might be used as exit targets) or not.

  • call_depth -- How deep in the call stack to trace.

  • call_tracing_filter -- Filter to apply on a given path and jumpkind to determine if it should be skipped when call_depth is reached.

  • initial_state -- An initial state to use to begin analysis.

  • starts (iterable) -- A collection of starting points to begin analysis. It can contain the following three different types of entries: an address specified as an integer, a 2-tuple that includes an integer address and a jumpkind, or a SimState instance. Unsupported entries in starts will lead to an AngrCFGError being raised.

  • keep_state -- Whether to keep the SimStates for each CFGNode.

  • resolve_indirect_jumps -- Whether to enable the indirect jump resolvers for resolving indirect jumps

  • enable_advanced_backward_slicing -- Whether to enable an intensive technique for resolving indirect jumps

  • enable_symbolic_back_traversal -- Whether to enable an intensive technique for resolving indirect jumps

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • additional_edges -- A dict mapping addresses of basic blocks to addresses of successors to manually include and analyze forward from.

  • no_construct (bool) -- Skip the construction procedure. Only used in unit-testing.

  • normalize (bool) -- If the CFG as well as all Function graphs should be normalized or not.

  • max_iterations (int) -- The maximum number of iterations that each basic block should be "executed". 1 by default. Larger numbers of iterations are usually required for complex analyses like loop analysis.

  • address_whitelist (iterable) -- A list of allowed addresses. Any basic blocks outside of this collection of addresses will be ignored.

  • base_graph (networkx.DiGraph) -- A basic control flow graph to follow. Each node inside this graph must have the following properties: addr and size. CFG recovery will strictly follow nodes and edges shown in the graph, and discard any control flow that does not follow an existing edge in the base graph. For example, you can pass in a Function local transition graph as the base graph, and CFGEmulated will traverse nodes and edges and extract useful information.

  • iropt_level (int) -- The optimization level of VEX IR (0, 1, 2). The default level will be used if iropt_level is None.

  • max_steps (int) -- The maximum number of basic blocks to recover forthe longest path from each start before pausing the recovery procedure.

  • state_add_options -- State options that will be added to the initial state.

  • state_remove_options -- State options that will be removed from the initial state.

copy()[源代码]

Make a copy of the CFG.

返回类型:

CFGEmulated

返回:

A copy of the CFG instance.

resume(starts=None, max_steps=None)[源代码]

Resume a paused or terminated control flow graph recovery.

参数:
  • starts (iterable) -- A collection of new starts to resume from. If starts is None, we will resume CFG recovery from where it was paused before.

  • max_steps (int) -- The maximum number of blocks on the longest path starting from each start before pausing the recovery.

返回:

None

remove_cycles()[源代码]

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

downsize()[源代码]

Remove saved states from all CFGNodes to reduce memory usage.

返回:

None

unroll_loops(max_loop_unrolling_times)[源代码]

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

参数:

max_loop_unrolling_times (int) -- The maximum iterations of unrolling.

返回:

None

force_unroll_loops(max_loop_unrolling_times)[源代码]

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

参数:

max_loop_unrolling_times (int) -- The maximum iterations of unrolling.

返回:

None

immediate_dominators(start, target_graph=None)[源代码]

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

参数:
  • start (str) -- id of the node to navigate forwards from.

  • target_graph (networkx.classes.digraph.DiGraph) -- graph to analyse, default is self.graph.

返回:

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

返回类型:

dict

immediate_postdominators(end, target_graph=None)[源代码]

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

参数:
  • start (str) -- id of the node to navigate forwards from.

  • target_graph (networkx.classes.digraph.DiGraph) -- graph to analyse, default is self.graph.

返回:

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

返回类型:

dict

remove_fakerets()[源代码]

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

返回:

None

get_topological_order(cfg_node)[源代码]

Get the topological order of a CFG Node.

参数:

cfg_node -- A CFGNode instance.

返回:

An integer representing its order, or None if the CFGNode does not exist in the graph.

get_subgraph(starting_node, block_addresses)[源代码]

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

参数:
  • starting_node (CFGNode) -- The beginning of the subgraph

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

返回:

A new CFG that only contain the specific subgraph.

返回类型:

CFGEmulated

get_function_subgraph(start, max_call_depth=None)[源代码]

Get a sub-graph of a certain function.

参数:
  • start -- The function start. Currently it should be an integer.

  • max_call_depth -- Call depth limit. None indicates no limit.

返回:

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

property context_sensitivity_level
property graph
property unresolvables

Get those SimRuns that have non-resolvable exits.

返回:

A set of SimRuns

返回类型:

set

property deadends

Get all CFGNodes that has an out-degree of 0

返回:

A list of CFGNode instances

返回类型:

list

indirect_jumps: dict[int, IndirectJump]
project: Project
kb: KnowledgeBase
class angr.analyses.cfg.CFGFast(binary=None, objects=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_smart_scan=True, force_complete_scan=False, indirect_jump_target_limit=100000, data_references=True, cross_references=False, normalize=False, start_at_entry=True, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, indirect_jump_resolvers=None, base_state=None, exclude_sparse_regions=True, skip_specific_regions=True, heuristic_plt_resolving=None, detect_tail_calls=False, low_priority=False, cfb=None, model=None, elf_eh_frame=True, exceptions=True, skip_unmapped_addrs=True, nodecode_window_size=512, nodecode_threshold=0.3, nodecode_step=16483, indirect_calls_always_return=None, jumptable_resolver_resolves_calls=None, start=None, end=None, collect_data_references=None, extra_cross_references=None, **extra_arch_options)[源代码]

基类:ForwardAnalysis[CFGNode, CFGNode, CFGJob, int], CFGBase

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

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

# Active scanning

  • If the binary has "function symbols" (TODO: this term is not accurate enough), they are starting points of the code scanning

  • If the binary does not have any "function symbol", we will first perform a function prologue scanning on the entire binary, and start from those places that look like function beginnings

  • Otherwise, the binary's entry point will be the starting point for scanning

# Passive scanning

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

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

参数:
  • indirect_calls_always_return (bool | None)

  • jumptable_resolver_resolves_calls (bool | None)

PRINTABLES = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r'
SPECIAL_THUNKS = {'AMD64': {b'\xe8\x07\x00\x00\x00\xf3\x90\x0f\xae\xe8\xeb\xf9H\x89\x04$\xc3': ('jmp', 'rax'), b'\xe8\x07\x00\x00\x00\xf3\x90\x0f\xae\xe8\xeb\xf9H\x8dd$\x08\xc3': ('ret',)}}
tag: str | None = 'CFGFast'
__init__(binary=None, objects=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_smart_scan=True, force_complete_scan=False, indirect_jump_target_limit=100000, data_references=True, cross_references=False, normalize=False, start_at_entry=True, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, indirect_jump_resolvers=None, base_state=None, exclude_sparse_regions=True, skip_specific_regions=True, heuristic_plt_resolving=None, detect_tail_calls=False, low_priority=False, cfb=None, model=None, elf_eh_frame=True, exceptions=True, skip_unmapped_addrs=True, nodecode_window_size=512, nodecode_threshold=0.3, nodecode_step=16483, indirect_calls_always_return=None, jumptable_resolver_resolves_calls=None, start=None, end=None, collect_data_references=None, extra_cross_references=None, **extra_arch_options)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return (Optional[bool]) -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls (Optional[bool]) -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

  • indirect_calls_always_return (bool | None)

  • jumptable_resolver_resolves_calls (bool | None)

返回:

None

property graph
property memory_data
property jump_tables
property insn_addr_to_memory_data
do_full_xrefs(overlay_state=None)[源代码]

Perform xref recovery on all functions.

参数:

overlay (SimState) -- An overlay state for loading constant data.

返回:

None

copy()[源代码]
indirect_jumps: dict[int, IndirectJump]
project: Project
kb: KnowledgeBase
output()[源代码]
generate_code_cover(**kwargs)
class angr.analyses.cfg.CFGFastSoot(support_jni=False, **kwargs)[源代码]

基类:CFGFast

__init__(support_jni=False, **kwargs)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

返回:

None

normalize()[源代码]

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

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

返回:

None

make_functions()[源代码]

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

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

  • A block may only belong to one function.

  • Small functions lying inside the startpoint and the endpoint of another function will be merged with the other function

  • Tail call optimizations are detected.

  • PLT stubs are aligned by 16.

返回:

None

class angr.analyses.cfg.cfb.CFBlanketView(cfb)[源代码]

基类:object

A view into the control-flow blanket.

__init__(cfb)[源代码]
class angr.analyses.cfg.cfb.MemoryRegion(addr, size, type_, object_, cle_region)[源代码]

基类:object

__init__(addr, size, type_, object_, cle_region)[源代码]
class angr.analyses.cfg.cfb.Unknown(addr, size, bytes_=None, object_=None, segment=None, section=None)[源代码]

基类:object

__init__(addr, size, bytes_=None, object_=None, segment=None, section=None)[源代码]
class angr.analyses.cfg.cfb.CFBlanket(exclude_region_types=None, on_object_added=None)[源代码]

基类:Analysis

A Control-Flow Blanket is a representation for storing all instructions, data entries, and bytes of a full program.

Region types: - section - segment - extern - tls - kernel

参数:
  • exclude_region_types (set[str] | None)

  • on_object_added (Callable[[int, Any], None] | None)

__init__(exclude_region_types=None, on_object_added=None)[源代码]
参数:
  • on_object_added (Optional[Callable[[int, Any], None]]) -- Callable with parameters (addr, obj) called after an object is added to the blanket.

  • exclude_region_types (set[str] | None)

property regions

Return all memory regions.

floor_addr(addr)[源代码]
floor_item(addr)[源代码]
floor_items(addr=None, reverse=False)[源代码]
ceiling_addr(addr)[源代码]
ceiling_item(addr)[源代码]
ceiling_items(addr=None, reverse=False, include_first=True)[源代码]
add_obj(addr, obj)[源代码]

Adds an object obj to the blanket at the specified address addr

add_function(func)[源代码]

Add a function func and all blocks of this function to the blanket.

dbg_repr()[源代码]

The debugging representation of this CFBlanket.

返回:

The debugging representation of this CFBlanket.

返回类型:

str

exception angr.analyses.cfg.cfg.OutdatedError[源代码]

基类:Exception

class angr.analyses.cfg.cfg.CFG(**kwargs)[源代码]

基类:CFGFast

tl;dr: CFG is just a wrapper around CFGFast for compatibility issues. It will be fully replaced by CFGFast in future releases. Feel free to use CFG if you intend to use CFGFast. Please use CFGEmulated if you have to use the old, slow, dynamically-generated version of CFG.

For multiple historical reasons, angr's CFG is accurate but slow, which does not meet what most people expect. We developed CFGFast for light-speed CFG recovery, and renamed the old CFG class to CFGEmulated. For compatibility concerns, CFG was kept as an alias to CFGEmulated.

However, so many new users of angr would load up a binary and generate a CFG immediately after running "pip install angr", and draw the conclusion that "angr's CFG is so slow - angr must be unusable!" Therefore, we made the hard decision: CFG will be an alias to CFGFast, instead of CFGEmulated.

To ease the transition of your existing code and script, the following changes are made:

  • A CFG class, which is a sub class of CFGFast, is created.

  • You will see both a warning message printed out to stderr and an exception raised by angr if you are passing CFG any parameter that only CFGEmulated supports. This exception is not a sub class of AngrError, so you wouldn't capture it with your old code by mistake.

  • In the near future, this wrapper class will be removed completely, and CFG will be a simple alias to CFGFast.

We expect most interfaces are the same between CFGFast and CFGEmulated. Apparently some functionalities (like context-sensitivity, and state keeping) only exist in CFGEmulated, which is when you want to use CFGEmulated instead.

__init__(**kwargs)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

返回:

None

class angr.analyses.cfg.cfg_emulated.CFGJob(*args, **kwargs)[源代码]

基类:CFGJobBase

The job class that CFGEmulated uses.

__init__(*args, **kwargs)[源代码]
property block_id
property is_syscall
class angr.analyses.cfg.cfg_emulated.PendingJob(caller_func_addr, returning_source, state, src_block_id, src_exit_stmt_idx, src_exit_ins_addr, call_stack)[源代码]

基类:object

A PendingJob is whatever will be put into our pending_exit list. A pending exit is an entry that created by the returning of a call or syscall. It is "pending" since we cannot immediately figure out whether this entry will be executed or not. If the corresponding call/syscall intentionally doesn't return, then the pending exit will be removed. If the corresponding call/syscall returns, then the pending exit will be removed as well (since a real entry is created from the returning and will be analyzed later). If the corresponding call/syscall might return, but for some reason (for example, an unsupported instruction is met during the analysis) our analysis does not return properly, then the pending exit will be picked up and put into remaining_jobs list.

__init__(caller_func_addr, returning_source, state, src_block_id, src_exit_stmt_idx, src_exit_ins_addr, call_stack)[源代码]
参数:
  • returning_source -- Address of the callee function. It might be None if address of the callee is not resolvable.

  • state -- The state after returning from the callee function. Of course there is no way to get a precise state without emulating the execution of the callee, but at least we can properly adjust the stack and registers to imitate the real returned state.

  • call_stack -- A callstack.

class angr.analyses.cfg.cfg_emulated.CFGEmulated(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, indirect_jump_target_limit=100000, resolve_indirect_jumps=True, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, indirect_jump_resolvers=None, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None, state_add_options=None, state_remove_options=None, model=None)[源代码]

基类:ForwardAnalysis, CFGBase

This class represents a control-flow graph.

tag: str | None = 'CFGEmulated'
__init__(context_sensitivity_level=1, start=None, avoid_runs=None, enable_function_hints=False, call_depth=None, call_tracing_filter=None, initial_state=None, starts=None, keep_state=False, indirect_jump_target_limit=100000, resolve_indirect_jumps=True, enable_advanced_backward_slicing=False, enable_symbolic_back_traversal=False, indirect_jump_resolvers=None, additional_edges=None, no_construct=False, normalize=False, max_iterations=1, address_whitelist=None, base_graph=None, iropt_level=None, max_steps=None, state_add_options=None, state_remove_options=None, model=None)[源代码]

All parameters are optional.

参数:
  • context_sensitivity_level -- The level of context-sensitivity of this CFG (see documentation for further details). It ranges from 0 to infinity. Default 1.

  • avoid_runs -- A list of runs to avoid.

  • enable_function_hints -- Whether to use function hints (constants that might be used as exit targets) or not.

  • call_depth -- How deep in the call stack to trace.

  • call_tracing_filter -- Filter to apply on a given path and jumpkind to determine if it should be skipped when call_depth is reached.

  • initial_state -- An initial state to use to begin analysis.

  • starts (iterable) -- A collection of starting points to begin analysis. It can contain the following three different types of entries: an address specified as an integer, a 2-tuple that includes an integer address and a jumpkind, or a SimState instance. Unsupported entries in starts will lead to an AngrCFGError being raised.

  • keep_state -- Whether to keep the SimStates for each CFGNode.

  • resolve_indirect_jumps -- Whether to enable the indirect jump resolvers for resolving indirect jumps

  • enable_advanced_backward_slicing -- Whether to enable an intensive technique for resolving indirect jumps

  • enable_symbolic_back_traversal -- Whether to enable an intensive technique for resolving indirect jumps

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • additional_edges -- A dict mapping addresses of basic blocks to addresses of successors to manually include and analyze forward from.

  • no_construct (bool) -- Skip the construction procedure. Only used in unit-testing.

  • normalize (bool) -- If the CFG as well as all Function graphs should be normalized or not.

  • max_iterations (int) -- The maximum number of iterations that each basic block should be "executed". 1 by default. Larger numbers of iterations are usually required for complex analyses like loop analysis.

  • address_whitelist (iterable) -- A list of allowed addresses. Any basic blocks outside of this collection of addresses will be ignored.

  • base_graph (networkx.DiGraph) -- A basic control flow graph to follow. Each node inside this graph must have the following properties: addr and size. CFG recovery will strictly follow nodes and edges shown in the graph, and discard any control flow that does not follow an existing edge in the base graph. For example, you can pass in a Function local transition graph as the base graph, and CFGEmulated will traverse nodes and edges and extract useful information.

  • iropt_level (int) -- The optimization level of VEX IR (0, 1, 2). The default level will be used if iropt_level is None.

  • max_steps (int) -- The maximum number of basic blocks to recover forthe longest path from each start before pausing the recovery procedure.

  • state_add_options -- State options that will be added to the initial state.

  • state_remove_options -- State options that will be removed from the initial state.

copy()[源代码]

Make a copy of the CFG.

返回类型:

CFGEmulated

返回:

A copy of the CFG instance.

resume(starts=None, max_steps=None)[源代码]

Resume a paused or terminated control flow graph recovery.

参数:
  • starts (iterable) -- A collection of new starts to resume from. If starts is None, we will resume CFG recovery from where it was paused before.

  • max_steps (int) -- The maximum number of blocks on the longest path starting from each start before pausing the recovery.

返回:

None

remove_cycles()[源代码]

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

downsize()[源代码]

Remove saved states from all CFGNodes to reduce memory usage.

返回:

None

unroll_loops(max_loop_unrolling_times)[源代码]

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

参数:

max_loop_unrolling_times (int) -- The maximum iterations of unrolling.

返回:

None

force_unroll_loops(max_loop_unrolling_times)[源代码]

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

参数:

max_loop_unrolling_times (int) -- The maximum iterations of unrolling.

返回:

None

immediate_dominators(start, target_graph=None)[源代码]

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

参数:
  • start (str) -- id of the node to navigate forwards from.

  • target_graph (networkx.classes.digraph.DiGraph) -- graph to analyse, default is self.graph.

返回:

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

返回类型:

dict

immediate_postdominators(end, target_graph=None)[源代码]

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

参数:
  • start (str) -- id of the node to navigate forwards from.

  • target_graph (networkx.classes.digraph.DiGraph) -- graph to analyse, default is self.graph.

返回:

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

返回类型:

dict

remove_fakerets()[源代码]

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

返回:

None

get_topological_order(cfg_node)[源代码]

Get the topological order of a CFG Node.

参数:

cfg_node -- A CFGNode instance.

返回:

An integer representing its order, or None if the CFGNode does not exist in the graph.

get_subgraph(starting_node, block_addresses)[源代码]

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

参数:
  • starting_node (CFGNode) -- The beginning of the subgraph

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

返回:

A new CFG that only contain the specific subgraph.

返回类型:

CFGEmulated

get_function_subgraph(start, max_call_depth=None)[源代码]

Get a sub-graph of a certain function.

参数:
  • start -- The function start. Currently it should be an integer.

  • max_call_depth -- Call depth limit. None indicates no limit.

返回:

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

property context_sensitivity_level
property graph
property unresolvables

Get those SimRuns that have non-resolvable exits.

返回:

A set of SimRuns

返回类型:

set

property deadends

Get all CFGNodes that has an out-degree of 0

返回:

A list of CFGNode instances

返回类型:

list

indirect_jumps: dict[int, IndirectJump]
project: Project
kb: KnowledgeBase
class angr.analyses.cfg.cfg_base.CFGBase(sort, context_sensitivity_level, normalize=False, binary=None, objects=None, regions=None, exclude_sparse_regions=True, skip_specific_regions=True, force_segment=False, base_state=None, resolve_indirect_jumps=True, indirect_jump_resolvers=None, indirect_jump_target_limit=100000, detect_tail_calls=False, low_priority=False, skip_unmapped_addrs=True, sp_tracking_track_memory=True, model=None)[源代码]

基类:Analysis

The base class for control flow graphs.

tag: str | None = None
__init__(sort, context_sensitivity_level, normalize=False, binary=None, objects=None, regions=None, exclude_sparse_regions=True, skip_specific_regions=True, force_segment=False, base_state=None, resolve_indirect_jumps=True, indirect_jump_resolvers=None, indirect_jump_target_limit=100000, detect_tail_calls=False, low_priority=False, skip_unmapped_addrs=True, sp_tracking_track_memory=True, model=None)[源代码]
参数:
  • sort (str) -- 'fast' or 'emulated'.

  • context_sensitivity_level (int) -- The level of context-sensitivity of this CFG (see documentation for further details). It ranges from 0 to infinity.

  • normalize (bool) -- Whether the CFG as well as all Function graphs should be normalized.

  • binary (cle.backends.Backend) -- The binary to recover CFG on. By default, the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default, it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • base_state (angr.SimState) -- A state to use as a backer for all memory loads.

  • resolve_indirect_jumps (bool) -- Whether to try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • indirect_jump_target_limit (int) -- Maximum indirect jump targets to be recovered.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • detect_tail_calls (bool) -- Aggressive tail-call optimization detection. This option is only respected in make_functions().

  • sp_tracking_track_memory (bool) -- Whether or not to track memory writes if tracking the stack pointer. This increases the accuracy of stack pointer tracking, especially for architectures without a base pointer. Only used if detect_tail_calls is enabled.

  • model (None or CFGModel) -- The CFGModel instance to write to. A new CFGModel instance will be created and registered with the knowledge base if model is None.

返回:

None

indirect_jumps: dict[int, IndirectJump]
property model: CFGModel

Get the CFGModel instance. :return: The CFGModel instance that this analysis currently uses.

property normalized
property context_sensitivity_level
property functions

A reference to the FunctionManager in the current knowledge base.

返回:

FunctionManager with all functions

返回类型:

angr.knowledge_plugins.FunctionManager

make_copy(copy_to)[源代码]

Copy self attributes to the new object.

参数:

copy_to (CFGBase) -- The target to copy to.

返回:

None

copy()[源代码]
output()[源代码]
generate_index()[源代码]

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

返回:

None

get_predecessors(**kwargs)
get_successors(**kwargs)
get_successors_and_jumpkind(**kwargs)
get_all_predecessors(**kwargs)
get_all_successors(**kwargs)
get_node(**kwargs)
get_any_node(**kwargs)
get_all_nodes(**kwargs)
nodes(**kwargs)
nodes_iter(**kwargs)
get_loop_back_edges()[源代码]
get_branching_nodes(**kwargs)
get_exit_stmt_idx(**kwargs)
property graph
remove_edge(block_from, block_to)[源代码]
is_thumb_addr(addr)[源代码]
normalize()[源代码]

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

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

返回:

None

mark_function_alignments()[源代码]

Find all potential function alignments and mark them.

Note that it is not always correct to simply remove them, because these functions may not be actual alignments but part of an actual function, and is incorrectly marked as an individual function because of failures in resolving indirect jumps. An example is in the test binary x86_64/dir_gcc_-O0 0x40541d (indirect jump at 0x4051b0). If the indirect jump cannot be correctly resolved, removing function 0x40541d will cause a missing label failure in reassembler.

返回:

None

make_functions()[源代码]

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

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

  • A block may only belong to one function.

  • Small functions lying inside the startpoint and the endpoint of another function will be merged with the other function

  • Tail call optimizations are detected.

  • PLT stubs are aligned by 16.

返回:

None

project: Project
kb: KnowledgeBase
exception angr.analyses.cfg.cfg_fast.ContinueScanningNotification[源代码]

基类:RuntimeError

A notification raised by _next_code_addr_core() to indicate no code address is found and _next_code_addr_core() should be invoked again.

class angr.analyses.cfg.cfg_fast.ARMDecodingMode[源代码]

基类:object

Enums indicating decoding mode for ARM code.

ARM = 0
THUMB = 1
class angr.analyses.cfg.cfg_fast.DecodingAssumption(addr, size, mode)[源代码]

基类:object

Describes the decoding mode (ARM/THUMB) for a given basic block identified by its address.

参数:
__init__(addr, size, mode)[源代码]
参数:
add_data_seg(addr, size)[源代码]
返回类型:

None

参数:
class angr.analyses.cfg.cfg_fast.FunctionReturn(callee_func_addr, caller_func_addr, call_site_addr, return_to)[源代码]

基类:object

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

__init__(callee_func_addr, caller_func_addr, call_site_addr, return_to)[源代码]
callee_func_addr
caller_func_addr
call_site_addr
return_to
class angr.analyses.cfg.cfg_fast.PendingJobs(kb, deregister_job_callback)[源代码]

基类:object

A collection of pending jobs during CFG recovery.

__init__(kb, deregister_job_callback)[源代码]
add_job(job)[源代码]
pop_job(returning=True)[源代码]

Pop a job from the pending jobs list.

When returning == True, we prioritize the jobs whose functions are known to be returning (function.returning is True). As an optimization, we are sorting the pending jobs list according to job.function.returning.

参数:

returning (bool) -- Only pop a pending job if the corresponding function returns.

返回:

A pending job if we can find one, or None if we cannot find any that satisfies the requirement.

返回类型:

angr.analyses.cfg.cfg_fast.CFGJob

cleanup()[源代码]

Remove those pending exits if: a) they are the return exits of non-returning SimProcedures b) they are the return exits of non-returning syscalls b) they are the return exits of non-returning functions

返回:

None

add_returning_function(func_addr)[源代码]

Mark a function as returning.

参数:

func_addr (int) -- Address of the function that returns.

返回:

None

add_nonreturning_function(func_addr)[源代码]

Mark a function as not returning.

参数:

func_addr (int) -- Address of the function that does not return.

返回:

None

clear_updated_functions()[源代码]

Clear the updated_functions set.

返回:

None

class angr.analyses.cfg.cfg_fast.FunctionEdge[源代码]

基类:object

Describes an edge in functions' transition graphs. Base class for all types of edges.

apply(cfg)[源代码]
ins_addr
src_func_addr
stmt_idx
class angr.analyses.cfg.cfg_fast.FunctionTransitionEdge(src_node, dst_addr, src_func_addr, to_outside=False, dst_func_addr=None, stmt_idx=None, ins_addr=None, is_exception=False)[源代码]

基类:FunctionEdge

Describes a transition edge in functions' transition graphs.

__init__(src_node, dst_addr, src_func_addr, to_outside=False, dst_func_addr=None, stmt_idx=None, ins_addr=None, is_exception=False)[源代码]
src_node
dst_addr
to_outside
dst_func_addr
is_exception
apply(cfg)[源代码]
class angr.analyses.cfg.cfg_fast.FunctionCallEdge(src_node, dst_addr, ret_addr, src_func_addr, syscall=False, stmt_idx=None, ins_addr=None)[源代码]

基类:FunctionEdge

Describes a call edge in functions' transition graphs.

__init__(src_node, dst_addr, ret_addr, src_func_addr, syscall=False, stmt_idx=None, ins_addr=None)[源代码]
src_node
dst_addr
ret_addr
syscall
apply(cfg)[源代码]
class angr.analyses.cfg.cfg_fast.FunctionFakeRetEdge(src_node, dst_addr, src_func_addr, confirmed=None)[源代码]

基类:FunctionEdge

Describes a FakeReturn (also called fall-through) edge in functions' transition graphs.

__init__(src_node, dst_addr, src_func_addr, confirmed=None)[源代码]
src_node
dst_addr
confirmed
apply(cfg)[源代码]
class angr.analyses.cfg.cfg_fast.FunctionReturnEdge(ret_from_addr, ret_to_addr, dst_func_addr)[源代码]

基类:FunctionEdge

Describes a return (from a function call or a syscall) edge in functions' transition graphs.

__init__(ret_from_addr, ret_to_addr, dst_func_addr)[源代码]
ret_from_addr
ret_to_addr
dst_func_addr
apply(cfg)[源代码]
class angr.analyses.cfg.cfg_fast.CFGJobType(value)[源代码]

基类:Enum

Defines the type of work of a CFGJob

NORMAL = 0
FUNCTION_PROLOGUE = 1
COMPLETE_SCANNING = 2
IFUNC_HINTS = 3
DATAREF_HINTS = 4
class angr.analyses.cfg.cfg_fast.CFGJob(addr, func_addr, jumpkind, ret_target=None, last_addr=None, src_node=None, src_ins_addr=None, src_stmt_idx=None, returning_source=None, syscall=False, func_edges=None, job_type=CFGJobType.NORMAL, gp=None)[源代码]

基类:object

Defines a job to work on during the CFG recovery

参数:
  • addr (int)

  • func_addr (int)

  • jumpkind (str)

  • ret_target (int | None)

  • last_addr (int | None)

  • src_node (CFGNode | None)

  • src_ins_addr (int | None)

  • src_stmt_idx (int | None)

  • syscall (bool)

  • func_edges (list | None)

  • job_type (CFGJobType)

  • gp (int | None)

__init__(addr, func_addr, jumpkind, ret_target=None, last_addr=None, src_node=None, src_ins_addr=None, src_stmt_idx=None, returning_source=None, syscall=False, func_edges=None, job_type=CFGJobType.NORMAL, gp=None)[源代码]
参数:
  • addr (int)

  • func_addr (int)

  • jumpkind (str)

  • ret_target (int | None)

  • last_addr (int | None)

  • src_node (CFGNode | None)

  • src_ins_addr (int | None)

  • src_stmt_idx (int | None)

  • syscall (bool)

  • func_edges (list | None)

  • job_type (CFGJobType)

  • gp (int | None)

addr
func_addr
jumpkind
ret_target
last_addr
src_node
src_ins_addr
src_stmt_idx
returning_source
syscall
job_type
gp
add_function_edge(edge)[源代码]
apply_function_edges(cfg, clear=False)[源代码]
class angr.analyses.cfg.cfg_fast.CFGFast(binary=None, objects=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_smart_scan=True, force_complete_scan=False, indirect_jump_target_limit=100000, data_references=True, cross_references=False, normalize=False, start_at_entry=True, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, indirect_jump_resolvers=None, base_state=None, exclude_sparse_regions=True, skip_specific_regions=True, heuristic_plt_resolving=None, detect_tail_calls=False, low_priority=False, cfb=None, model=None, elf_eh_frame=True, exceptions=True, skip_unmapped_addrs=True, nodecode_window_size=512, nodecode_threshold=0.3, nodecode_step=16483, indirect_calls_always_return=None, jumptable_resolver_resolves_calls=None, start=None, end=None, collect_data_references=None, extra_cross_references=None, **extra_arch_options)[源代码]

基类:ForwardAnalysis[CFGNode, CFGNode, CFGJob, int], CFGBase

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

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

# Active scanning

  • If the binary has "function symbols" (TODO: this term is not accurate enough), they are starting points of the code scanning

  • If the binary does not have any "function symbol", we will first perform a function prologue scanning on the entire binary, and start from those places that look like function beginnings

  • Otherwise, the binary's entry point will be the starting point for scanning

# Passive scanning

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

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

参数:
  • indirect_calls_always_return (bool | None)

  • jumptable_resolver_resolves_calls (bool | None)

PRINTABLES = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r'
SPECIAL_THUNKS = {'AMD64': {b'\xe8\x07\x00\x00\x00\xf3\x90\x0f\xae\xe8\xeb\xf9H\x89\x04$\xc3': ('jmp', 'rax'), b'\xe8\x07\x00\x00\x00\xf3\x90\x0f\xae\xe8\xeb\xf9H\x8dd$\x08\xc3': ('ret',)}}
tag: str | None = 'CFGFast'
__init__(binary=None, objects=None, regions=None, pickle_intermediate_results=False, symbols=True, function_prologues=True, resolve_indirect_jumps=True, force_segment=False, force_smart_scan=True, force_complete_scan=False, indirect_jump_target_limit=100000, data_references=True, cross_references=False, normalize=False, start_at_entry=True, function_starts=None, extra_memory_regions=None, data_type_guessing_handlers=None, arch_options=None, indirect_jump_resolvers=None, base_state=None, exclude_sparse_regions=True, skip_specific_regions=True, heuristic_plt_resolving=None, detect_tail_calls=False, low_priority=False, cfb=None, model=None, elf_eh_frame=True, exceptions=True, skip_unmapped_addrs=True, nodecode_window_size=512, nodecode_threshold=0.3, nodecode_step=16483, indirect_calls_always_return=None, jumptable_resolver_resolves_calls=None, start=None, end=None, collect_data_references=None, extra_cross_references=None, **extra_arch_options)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return (Optional[bool]) -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls (Optional[bool]) -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

  • indirect_calls_always_return (bool | None)

  • jumptable_resolver_resolves_calls (bool | None)

返回:

None

property graph
property memory_data
property jump_tables
property insn_addr_to_memory_data
do_full_xrefs(overlay_state=None)[源代码]

Perform xref recovery on all functions.

参数:

overlay (SimState) -- An overlay state for loading constant data.

返回:

None

copy()[源代码]
indirect_jumps: dict[int, IndirectJump]
project: Project
kb: KnowledgeBase
output()[源代码]
generate_code_cover(**kwargs)
class angr.analyses.cfg.cfg_arch_options.CFGArchOptions(arch, **options)[源代码]

基类:object

Stores architecture-specific options and settings, as well as the detailed explanation of those options and settings.

Suppose ao is the CFGArchOptions object, and there is an option called ret_jumpkind_heuristics, you can access it by ao.ret_jumpkind_heuristics and set its value via ao.ret_jumpkind_heuristics = True

变量:
  • OPTIONS (dict) -- A dict of all default options for different architectures.

  • arch (archinfo.Arch) -- The architecture object.

  • _options (dict) -- Values of all CFG options that are specific to the current architecture.

OPTIONS = {'ARMCortexM': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, False)}, 'ARMEL': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, True)}, 'ARMHF': {'pattern_match_ifuncs': (<class 'bool'>, True), 'ret_jumpkind_heuristics': (<class 'bool'>, True), 'switch_mode_on_nodecode': (<class 'bool'>, True)}}
__init__(arch, **options)[源代码]

Constructor.

参数:
  • arch (archinfo.Arch) -- The architecture instance.

  • options (dict) -- Architecture-specific options, which will be used to initialize this object.

arch = None
class angr.analyses.cfg.cfg_job_base.BlockID(addr, callsite_tuples, jump_type)[源代码]

基类:object

A context-sensitive key for a SimRun object.

__init__(addr, callsite_tuples, jump_type)[源代码]
callsite_repr()[源代码]
static new(addr, callstack_suffix, jumpkind)[源代码]
property func_addr
class angr.analyses.cfg.cfg_job_base.FunctionKey(addr, callsite_tuples)[源代码]

基类:object

A context-sensitive key for a function.

__init__(addr, callsite_tuples)[源代码]
callsite_repr()[源代码]
static new(addr, callsite_tuples)[源代码]
class angr.analyses.cfg.cfg_job_base.CFGJobBase(addr, state, context_sensitivity_level, block_id=None, src_block_id=None, src_exit_stmt_idx=None, src_ins_addr=None, jumpkind=None, call_stack=None, is_narrowing=False, skip=False, final_return_address=None)[源代码]

基类:object

Describes an entry in CFG or VFG. Only used internally by the analysis.

参数:
__init__(addr, state, context_sensitivity_level, block_id=None, src_block_id=None, src_exit_stmt_idx=None, src_ins_addr=None, jumpkind=None, call_stack=None, is_narrowing=False, skip=False, final_return_address=None)[源代码]
参数:
property call_stack
call_stack_copy()[源代码]
get_call_stack_suffix()[源代码]
property func_addr
property current_stack_pointer
class angr.analyses.cfg.indirect_jump_resolvers.amd64_elf_got.AMD64ElfGotResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver that resolves GOT entries on AMD64 ELF binaries.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.arm_elf_fast.ArmElfFastResolver(project)[源代码]

基类:IndirectJumpResolver

Resolves indirect jumps in ARM ELF binaries

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

The main resolving function.

参数:
  • cfg -- A CFG instance.

  • addr (int) -- Address of the IRSB.

  • func_addr (int) -- Address of the function.

  • block -- The IRSB.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool)

返回:

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.x86_pe_iat.X86PeIatResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver for IAT in x86 PEs and xbes.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

angr.analyses.cfg.indirect_jump_resolvers.mips_elf_fast.enable_profiling()[源代码]
angr.analyses.cfg.indirect_jump_resolvers.mips_elf_fast.disable_profiling()[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.mips_elf_fast.Case2Result(value)[源代码]

基类:Enum

Describes the result of resolving case 2 function calls.

SUCCESS = 0
FAILURE = 1
RESUME = 2
class angr.analyses.cfg.indirect_jump_resolvers.mips_elf_fast.MipsElfFastResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver for R9-based indirect function calls in MIPS ELFs.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Wrapper for _resolve that slowly increments the max_depth used by Blade for finding sources until we can resolve the addr or we reach the default max_depth

参数:
  • cfg -- A CFG instance.

  • addr (int) -- IRSB address.

  • func_addr (int) -- The function address.

  • block (pyvex.IRSB) -- The IRSB.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool)

返回:

If it was resolved and targets alongside it

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.x86_elf_pic_plt.X86ElfPicPltResolver(project)[源代码]

基类:IndirectJumpResolver

In X86 ELF position-independent code, PLT stubs uses ebx to resolve library calls, where ebx stores the address to the beginning of the GOT. We resolve the target by forcing ebx to be the beginning of the GOT and simulate the execution in fast path mode.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

angr.analyses.cfg.indirect_jump_resolvers.default_resolvers.default_indirect_jump_resolvers(obj, project)[源代码]
exception angr.analyses.cfg.indirect_jump_resolvers.jumptable.NotAJumpTableNotification[源代码]

基类:AngrError

Exception raised to indicate this is not (or does not appear to be) a jump table.

class angr.analyses.cfg.indirect_jump_resolvers.jumptable.UninitReadMeta[源代码]

基类:object

Uninitialized read remapping details.

uninit_read_base = 201326592
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.AddressTransformationTypes(value)[源代码]

基类:int, Enum

Address transformation operations.

Assignment = 0
SignedExtension = 1
UnsignedExtension = 2
Truncation = 3
Or1 = 4
ShiftLeft = 5
ShiftRight = 6
Add = 7
Load = 8
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.AddressTransformation(op, operands, first_load=False)[源代码]

基类:object

Describe and record an address transformation operation.

参数:
__init__(op, operands, first_load=False)[源代码]
参数:
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.AddressOperand[源代码]

基类:object

The class for the singleton class AddressSingleton. It represents the address being transformed before using as an indirect jump target.

class angr.analyses.cfg.indirect_jump_resolvers.jumptable.Tmp(tmp_idx)[源代码]

基类:object

For modeling Tmp variables.

__init__(tmp_idx)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTargetBaseAddr(stmt_loc, stmt, tmp, base_addr=None, tmp_1=None)[源代码]

基类:object

Model for jump targets and their data origin.

参数:
__init__(stmt_loc, stmt, tmp, base_addr=None, tmp_1=None)[源代码]
参数:
property base_addr_available
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.ConstantValueManager(project, kb, func, ij_addr)[源代码]

基类:object

Manages the loading of registers who hold constant values.

参数:
__init__(project, kb, func, ij_addr)[源代码]
参数:
project
kb
func
indirect_jump_addr
mapping: dict[Any, dict[Any, Base]] | None
reg_read_callback(state)[源代码]
参数:

state (SimState)

class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTableProcessorState(arch)[源代码]

基类:object

The state used in JumpTableProcessor.

__init__(arch)[源代码]
arch
is_jumptable: bool | None
stmts_to_instrument
regs_to_initialize
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.RegOffsetAnnotation(reg_offset)[源代码]

基类:Annotation

Register Offset annotation.

参数:

reg_offset (RegisterOffset)

__init__(reg_offset)[源代码]
参数:

reg_offset (RegisterOffset)

reg_offset
property relocatable

Returns whether this annotation can be relocated in a simplification.

返回:

True if it can be relocated, false otherwise.

property eliminatable

Returns whether this annotation can be eliminated in a simplification.

返回:

True if eliminatable, False otherwise

class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTableProcessor(project, indirect_jump_node_pred_addrs, bp_sp_diff=256)[源代码]

基类:SimEngineNostmtVEX[JumpTableProcessorState, BV, JumpTableProcessorState], ClaripyDataVEXEngineMixin[JumpTableProcessorState, BV, JumpTableProcessorState, None]

Implements a simple and stupid data dependency tracking for stack and register variables.

Also determines which statements to instrument during static execution of the slice later. For example, the following example is not uncommon in non-optimized binaries:

    mov  [rbp+var_54], 1
loc_4051a6:
    cmp  [rbp+var_54], 6
    ja   loc_405412 (default)
loc_4051b0:
    mov  eax, [rbp+var_54]
    mov  rax, qword [rax*8+0x223a01]
    jmp  rax

We want to instrument the first instruction and replace the constant 1 with a symbolic variable, otherwise we will not be able to recover all jump targets later in block 0x4051b0.

参数:

indirect_jump_node_pred_addrs (set[int])

__init__(project, indirect_jump_node_pred_addrs, bp_sp_diff=256)[源代码]
参数:

indirect_jump_node_pred_addrs (set[int])

class angr.analyses.cfg.indirect_jump_resolvers.jumptable.StoreHook[源代码]

基类:object

Hook for memory stores.

static hook(state)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.LoadHook[源代码]

基类:object

Hook for memory loads.

__init__()[源代码]
hook_before(state)[源代码]
hook_after(state)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.PutHook[源代码]

基类:object

Hook for register writes.

static hook(state)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.RegisterInitializerHook(reg_offset, reg_bits, initial_value)[源代码]

基类:object

Hook for register init.

__init__(reg_offset, reg_bits, initial_value)[源代码]
hook(state)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.BSSHook(project, bss_regions)[源代码]

基类:object

Hook for BSS read/write.

__init__(project, bss_regions)[源代码]
bss_memory_read_hook(state)[源代码]
bss_memory_write_hook(state)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.MIPSGPHook(gp_offset, gp)[源代码]

基类:object

Hooks all reads from and writes into the gp register for MIPS32 binaries.

参数:
__init__(gp_offset, gp)[源代码]
参数:
gp_register_read_hook(state)[源代码]
gp_register_write_hook(state)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTableResolver(project, resolve_calls=True)[源代码]

基类:IndirectJumpResolver

A generic jump table resolver.

This is a fast jump table resolution. For performance concerns, we made the following assumptions:
  • The final jump target comes from the memory.

  • The final jump target must be directly read out of the memory, without any further modification or altering.

Progressively larger program slices will be analyzed to determine jump table location and size. If the size of the table cannot be determined, a guess will be made based on how many entries in the table appear valid.

参数:

resolve_calls (bool)

__init__(project, resolve_calls=True)[源代码]
参数:

resolve_calls (bool)

filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolves jump tables.

参数:
  • cfg -- A CFG instance.

  • addr (int) -- IRSB address.

  • func_addr (int) -- The function address.

  • block (pyvex.IRSB) -- The IRSB.

  • func_graph_complete (bool)

返回:

A bool indicating whether the indirect jump is resolved successfully, and a list of resolved targets

返回类型:

tuple

angr.analyses.cfg.indirect_jump_resolvers.const_resolver.exists_in_replacements(replacements, block_loc, tmp_var)[源代码]
class angr.analyses.cfg.indirect_jump_resolvers.const_resolver.ConstantResolver(project)[源代码]

基类:IndirectJumpResolver

Resolve an indirect jump by running a constant propagation on the entire function and check if the indirect jump can be resolved to a constant value. This resolver must be run after all other more specific resolvers.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

This function does the actual resolve. Our process is easy: Propagate all values inside the function specified, then extract the tmp_var used for the indirect jump from the basic block. Use the tmp var to locate the constant value stored in the replacements. If not present, returns False tuple.

参数:
  • cfg -- CFG with specified function

  • addr (int) -- Address of indirect jump

  • func_addr (int) -- Address of function of indirect jump

  • block (Block) -- Block of indirect jump (Block object)

  • jumpkind (str) -- VEX jumpkind (Ijk_Boring or Ijk_Call)

  • func_graph_complete (bool)

返回:

Bool tuple with replacement address

class angr.analyses.cfg.indirect_jump_resolvers.resolver.IndirectJumpResolver(project, timeless=False, base_state=None)[源代码]

基类:object

__init__(project, timeless=False, base_state=None)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.AMD64ElfGotResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver that resolves GOT entries on AMD64 ELF binaries.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.AMD64PeIatResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect call/jump resolver for IAT in amd64 PEs.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.ArmElfFastResolver(project)[源代码]

基类:IndirectJumpResolver

Resolves indirect jumps in ARM ELF binaries

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

The main resolving function.

参数:
  • cfg -- A CFG instance.

  • addr (int) -- Address of the IRSB.

  • func_addr (int) -- Address of the function.

  • block -- The IRSB.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool)

返回:

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.ConstantResolver(project)[源代码]

基类:IndirectJumpResolver

Resolve an indirect jump by running a constant propagation on the entire function and check if the indirect jump can be resolved to a constant value. This resolver must be run after all other more specific resolvers.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

This function does the actual resolve. Our process is easy: Propagate all values inside the function specified, then extract the tmp_var used for the indirect jump from the basic block. Use the tmp var to locate the constant value stored in the replacements. If not present, returns False tuple.

参数:
  • cfg -- CFG with specified function

  • addr (int) -- Address of indirect jump

  • func_addr (int) -- Address of function of indirect jump

  • block (Block) -- Block of indirect jump (Block object)

  • jumpkind (str) -- VEX jumpkind (Ijk_Boring or Ijk_Call)

  • func_graph_complete (bool)

返回:

Bool tuple with replacement address

class angr.analyses.cfg.indirect_jump_resolvers.JumpTableResolver(project, resolve_calls=True)[源代码]

基类:IndirectJumpResolver

A generic jump table resolver.

This is a fast jump table resolution. For performance concerns, we made the following assumptions:
  • The final jump target comes from the memory.

  • The final jump target must be directly read out of the memory, without any further modification or altering.

Progressively larger program slices will be analyzed to determine jump table location and size. If the size of the table cannot be determined, a guess will be made based on how many entries in the table appear valid.

参数:

resolve_calls (bool)

__init__(project, resolve_calls=True)[源代码]
参数:

resolve_calls (bool)

filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolves jump tables.

参数:
  • cfg -- A CFG instance.

  • addr (int) -- IRSB address.

  • func_addr (int) -- The function address.

  • block (pyvex.IRSB) -- The IRSB.

  • func_graph_complete (bool)

返回:

A bool indicating whether the indirect jump is resolved successfully, and a list of resolved targets

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.MemoryLoadResolver(project)[源代码]

基类:IndirectJumpResolver

Resolve an indirect jump that looks like the following:

.text:

call off_3314A8

.data: off_3314A8 dd offset sub_1E426F

This indirect jump resolver may not be the best solution for all cases (e.g., when the .data section can be intentionally altered by the binary itself).

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]
参数:
  • cfg -- CFG with specified function

  • addr (int) -- Address of indirect jump

  • func_addr (int) -- Address of function of indirect jump

  • block (IRSB) -- Block of indirect jump (Block object)

  • jumpkind (str) -- VEX jumpkind (Ijk_Boring or Ijk_Call)

  • func_graph_complete (bool)

返回:

Bool tuple with replacement address

class angr.analyses.cfg.indirect_jump_resolvers.MipsElfFastResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver for R9-based indirect function calls in MIPS ELFs.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Wrapper for _resolve that slowly increments the max_depth used by Blade for finding sources until we can resolve the addr or we reach the default max_depth

参数:
  • cfg -- A CFG instance.

  • addr (int) -- IRSB address.

  • func_addr (int) -- The function address.

  • block (pyvex.IRSB) -- The IRSB.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool)

返回:

If it was resolved and targets alongside it

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.MipsElfGotResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver that resolves GOT stub entries in MIPS ELF binaries.

Reference: MIPS Assembly Language Programmer's Guide, Calling Position Independent Functions

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.X86ElfPicPltResolver(project)[源代码]

基类:IndirectJumpResolver

In X86 ELF position-independent code, PLT stubs uses ebx to resolve library calls, where ebx stores the address to the beginning of the GOT. We resolve the target by forcing ebx to be the beginning of the GOT and simulate the execution in fast path mode.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.indirect_jump_resolvers.X86PeIatResolver(project)[源代码]

基类:IndirectJumpResolver

A timeless indirect jump resolver for IAT in x86 PEs and xbes.

__init__(project)[源代码]
filter(cfg, addr, func_addr, block, jumpkind)[源代码]

Check if this resolution method may be able to resolve the indirect jump or not.

参数:
  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

返回:

True if it is possible for this resolution method to resolve the specific indirect jump, False otherwise.

返回类型:

bool

resolve(cfg, addr, func_addr, block, jumpkind, func_graph_complete=True, **kwargs)[源代码]

Resolve an indirect jump.

参数:
  • cfg -- The CFG analysis object.

  • addr (int) -- Basic block address of this indirect jump.

  • func_addr (int) -- Address of the function that this indirect jump belongs to.

  • block -- The basic block. The type is determined by the backend being used. It's pyvex.IRSB if pyvex is used as the backend.

  • jumpkind (str) -- The jumpkind.

  • func_graph_complete (bool) -- True if the function graph is complete at this point (except for nodes that this indirect jump node dominates).

返回:

A tuple of a boolean indicating whether the resolution is successful or not, and a list of resolved targets (ints).

返回类型:

tuple

class angr.analyses.cfg.cfg_fast_soot.CFGFastSoot(support_jni=False, **kwargs)[源代码]

基类:CFGFast

__init__(support_jni=False, **kwargs)[源代码]
参数:
  • binary -- The binary to recover CFG on. By default the main binary is used.

  • objects -- A list of objects to recover the CFG on. By default it will recover the CFG of all loaded objects.

  • regions (iterable) -- A list of tuples in the form of (start address, end address) describing memory regions that the CFG should cover.

  • pickle_intermediate_results (bool) -- If we want to store the intermediate results or not.

  • symbols (bool) -- Get function beginnings from symbols in the binary.

  • function_prologues (bool) -- Scan the binary for function prologues, and use those positions as function beginnings

  • resolve_indirect_jumps (bool) -- Try to resolve indirect jumps. This is necessary to resolve jump targets from jump tables, etc.

  • force_segment (bool) -- Force CFGFast to rely on binary segments instead of sections.

  • force_complete_scan (bool) -- Perform a complete scan on the binary and maximize the number of identified code blocks.

  • data_references (bool) -- Enables the collection of references to data used by individual instructions. This does not collect 'cross-references', particularly those that involve multiple instructions. For that, see cross_references

  • cross_references (bool) -- Whether CFGFast should collect "cross-references" from the entire program or not. This will populate the knowledge base with references to and from each recognizable address constant found in the code. Note that, because this performs constant propagation on the entire program, it may be much slower and consume more memory. This option implies data_references=True.

  • normalize (bool) -- Normalize the CFG as well as all function graphs after CFG recovery.

  • start_at_entry (bool) -- Begin CFG recovery at the entry point of this project. Setting it to False prevents CFGFast from viewing the entry point as one of the starting points of code scanning.

  • function_starts (list) -- A list of extra function starting points. CFGFast will try to resume scanning from each address in the list.

  • extra_memory_regions (list) -- A list of 2-tuple (start-address, end-address) that shows extra memory regions. Integers falling inside will be considered as pointers.

  • indirect_jump_resolvers (list) -- A custom list of indirect jump resolvers. If this list is None or empty, default indirect jump resolvers specific to this architecture and binary types will be loaded.

  • base_state -- A state to use as a backer for all memory loads

  • detect_tail_calls (bool) -- Enable aggressive tail-call optimization detection.

  • elf_eh_frame (bool) -- Retrieve function starts (and maybe sizes later) from the .eh_frame of ELF binaries.

  • skip_unmapped_addrs -- Ignore all branches into unmapped regions. True by default. You may want to set it to False if you are analyzing manually patched binaries or malware samples.

  • indirect_calls_always_return -- Should CFG assume indirect calls must return or not. Assuming indirect calls must return will significantly reduce the number of constant propagation runs, but may reduce the overall CFG recovery precision when facing non-returning indirect calls. By default, we only assume indirect calls always return for large binaries (region > 50KB).

  • jumptable_resolver_resolves_calls -- Whether JumpTableResolver should resolve indirect calls or not. Most indirect calls in C++ binaries or UEFI binaries cannot be resolved using jump table resolver and must be resolved using their specific resolvers. By default, we will only disable JumpTableResolver from resolving indirect calls for large binaries (region > 50 KB).

  • start (int) -- (Deprecated) The beginning address of CFG recovery.

  • end (int) -- (Deprecated) The end address of CFG recovery.

  • arch_options (CFGArchOptions) -- Architecture-specific options.

  • extra_arch_options (dict) -- Any key-value pair in kwargs will be seen as an arch-specific option and will be used to set the option value in self._arch_options.

Extra parameters that angr.Analysis takes:

参数:
  • progress_callback -- Specify a callback function to get the progress during CFG recovery.

  • show_progressbar (bool) -- Should CFGFast show a progressbar during CFG recovery or not.

返回:

None

normalize()[源代码]

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

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

返回:

None

make_functions()[源代码]

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

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

  • A block may only belong to one function.

  • Small functions lying inside the startpoint and the endpoint of another function will be merged with the other function

  • Tail call optimizations are detected.

  • PLT stubs are aligned by 16.

返回:

None

class angr.analyses.cdg.CDG(cfg, start=None, no_construct=False)[源代码]

基类:Analysis

Implements a control dependence graph.

__init__(cfg, start=None, no_construct=False)[源代码]

Constructor.

参数:
  • cfg -- The control flow graph upon which this control dependence graph will build

  • start -- The starting point to begin constructing the control dependence graph

  • no_construct -- Skip the construction step. Only used in unit-testing.

property graph
get_post_dominators()[源代码]

Return the post-dom tree

get_dependants(run)[源代码]

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

get_guardians(run)[源代码]

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

exception angr.analyses.datagraph_meta.DataGraphError[源代码]

基类:Exception

class angr.analyses.datagraph_meta.DataGraphMeta[源代码]

基类:object

__init__()[源代码]
get_irsb_at(addr)[源代码]
pp(imarks=False)[源代码]

Pretty print the graph. @imarks determine whether the printed graph represents instructions (coarse grained) for easier navigation, or exact statements.

class angr.analyses.code_tagging.CodeTags[源代码]

基类:object

HAS_XOR = 'HAS_XOR'
HAS_BITSHIFTS = 'HAS_BITSHIFTS'
HAS_SQL = 'HAS_SQL'
LARGE_SWITCH = 'LARGE_SWITCH'
class angr.analyses.code_tagging.CodeTagging(func)[源代码]

基类:Analysis

__init__(func)[源代码]
analyze()[源代码]
has_xor()[源代码]

Detects if there is any xor operation in the function.

返回:

Tags

has_bitshifts()[源代码]

Detects if there is any bitwise operation in the function.

返回:

Tags.

has_sql()[源代码]

Detects if there is any reference to strings that look like SQL queries.

class angr.angrdb.AngrDB(project=None)[源代码]

基类:object

AngrDB provides a storage solution for an angr project, its knowledge bases, and some other types of data. It is designed to use an SQL-based database as the storage backend.

ALL_TABLES = ['objects']
VERSION = 1
__init__(project=None)[源代码]
static open_db(db_str='sqlite:///:memory:')[源代码]
static session_scope(Session)[源代码]
static save_info(session, key, value)[源代码]

Save an information entry to the database.

参数:
  • session

  • key

  • value

返回:

static get_info(session, key)[源代码]

Get an information entry from the database.

参数:
  • session

  • key

返回:

update_dbinfo(session, extra_info=None)[源代码]

Update the information in database.

参数:
返回:

get_dbinfo(session, extra_info=None)[源代码]

Get database information.

参数:
返回:

A dict of information entries.

db_compatible(version)[源代码]

Checks if the given database version is compatible with the current AngrDB class.

参数:

version (int) -- The version of the database.

返回:

True if compatible, False otherwise.

返回类型:

bool

dump(db_path, kbs=None, extra_info=None)[源代码]
参数:
load(db_path, kb_names=None, other_kbs=None, extra_info=None)[源代码]
参数:
class angr.angrdb.db.AngrDB(project=None)[源代码]

基类:object

AngrDB provides a storage solution for an angr project, its knowledge bases, and some other types of data. It is designed to use an SQL-based database as the storage backend.

ALL_TABLES = ['objects']
VERSION = 1
__init__(project=None)[源代码]
static open_db(db_str='sqlite:///:memory:')[源代码]
static session_scope(Session)[源代码]
static save_info(session, key, value)[源代码]

Save an information entry to the database.

参数:
  • session

  • key

  • value

返回:

static get_info(session, key)[源代码]

Get an information entry from the database.

参数:
  • session

  • key

返回:

update_dbinfo(session, extra_info=None)[源代码]

Update the information in database.

参数:
返回:

get_dbinfo(session, extra_info=None)[源代码]

Get database information.

参数:
返回:

A dict of information entries.

db_compatible(version)[源代码]

Checks if the given database version is compatible with the current AngrDB class.

参数:

version (int) -- The version of the database.

返回:

True if compatible, False otherwise.

返回类型:

bool

dump(db_path, kbs=None, extra_info=None)[源代码]
参数:
load(db_path, kb_names=None, other_kbs=None, extra_info=None)[源代码]
参数:
class angr.angrdb.models.DbInformation(**kwargs)[源代码]

基类:Base

Stores information related to the current database. Basically a key-value store.

id
key
value
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbObject(**kwargs)[源代码]

基类:Base

Models a binary object.

id
main_object
path
content
backend
backend_args
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbKnowledgeBase(**kwargs)[源代码]

基类:Base

Models a knowledge base.

id
name
cfgs
funcs
xrefs
comments
labels
var_collections
structured_code
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbCFGModel(**kwargs)[源代码]

基类:Base

Models a CFGFast instance.

id
kb_id
kb
ident
blob
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbFunction(**kwargs)[源代码]

基类:Base

Models a Function instance.

id
kb_id
kb
addr
blob
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbVariableCollection(**kwargs)[源代码]

基类:Base

Models a VariableManagerInternal instance.

id
kb_id
kb
func_addr
ident
blob
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbStructuredCode(**kwargs)[源代码]

基类:Base

Models a StructuredCode instance.

id
kb_id
kb
func_addr
flavor
expr_comments
stmt_comments
configuration
const_formats
ite_exprs
errors
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbXRefs(**kwargs)[源代码]

基类:Base

Models an XRefManager instance.

id
kb_id
kb
blob
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbComment(**kwargs)[源代码]

基类:Base

Models a comment.

id
kb_id
kb
addr
comment
type
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.models.DbLabel(**kwargs)[源代码]

基类:Base

Models a label.

id
kb_id
kb
addr
name
__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class angr.angrdb.serializers.KnowledgeBaseSerializer[源代码]

基类:object

Serialize/unserialize a KnowledgeBase object.

static dump(session, kb)[源代码]
参数:
  • session -- The database session object.

  • kb (KnowledgeBase) -- The KnowledgeBase instance to serialize.

返回:

None

static load(session, project, name)[源代码]
参数:

session

返回:

class angr.angrdb.serializers.LoaderSerializer[源代码]

基类:object

Serialize/unserialize a CLE Loader object into/from an angr DB.

Corner cases: - For certain backends (e.g., CART), we do not store the data of the main object. angr will unpack the CART file

again after loading the database.

NO_MAINBIN_BACKENDS = [<class 'cle.backends.cartfile.CARTFile'>]
LOAD_ARG_BLACKLIST = {'is_main_bin', 'loader'}
backend2name = {<class 'cle.backends.blob.Blob'>: 'blob', <class 'cle.backends.cartfile.CARTFile'>: 'cart', <class 'cle.backends.cgc.backedcgc.BackedCGC'>: 'backedcgc', <class 'cle.backends.cgc.cgc.CGC'>: 'cgc', <class 'cle.backends.coff.Coff'>: 'COFF', <class 'cle.backends.elf.elf.ELF'>: 'elf', <class 'cle.backends.elf.elfcore.ELFCore'>: 'elfcore', <class 'cle.backends.ihex.Hex'>: 'hex', <class 'cle.backends.java.apk.Apk'>: 'apk', <class 'cle.backends.java.jar.Jar'>: 'jar', <class 'cle.backends.macho.macho.MachO'>: 'mach-o', <class 'cle.backends.minidump.Minidump'>: 'minidump', <class 'cle.backends.named_region.NamedRegion'>: 'named_region', <class 'cle.backends.pe.pe.PE'>: 'pe', <class 'cle.backends.srec.SRec'>: 'srec', <class 'cle.backends.static_archive.StaticArchive'>: 'AR', <class 'cle.backends.te.TE'>: 'te', <class 'cle.backends.uefi_firmware.UefiFirmware'>: 'uefi', <class 'cle.backends.xbe.XBE'>: 'xbe'}
static json_serialize_load_args(load_args)[源代码]
返回类型:

str

参数:

load_args (dict[str, Any])

static should_skip_main_binary(loader)[源代码]
返回类型:

tuple[bool, Backend | None]

static dump(session, loader)[源代码]
static load(session)[源代码]
class angr.angrdb.serializers.cfg_model.CFGModelSerializer[源代码]

基类:object

Serialize/unserialize a CFGModel.

static dump(session, db_kb, ident, cfg_model)[源代码]
参数:
  • session

  • db_kb (DbKnowledgeBase) -- The database object for KnowledgeBase.

  • ident (str) -- Identifier of the CFG model.

  • cfg_model (CFGModel) -- The CFG model to dump.

返回:

None

static load(session, db_kb, ident, cfg_manager, loader=None)[源代码]
class angr.angrdb.serializers.comments.CommentsSerializer[源代码]

基类:object

Serialize/unserialize comments to/from a database session.

static dump(session, db_kb, comments)[源代码]
参数:
返回:

None

static load(session, db_kb, kb)[源代码]
参数:
返回:

class angr.angrdb.serializers.funcs.FunctionManagerSerializer[源代码]

基类:object

Serialize/unserialize a function manager and its functions.

static dump(session, db_kb, func_manager)[源代码]
参数:
返回:

static load(session, db_kb, kb)[源代码]
参数:
返回:

A loaded function manager.

class angr.angrdb.serializers.kb.KnowledgeBaseSerializer[源代码]

基类:object

Serialize/unserialize a KnowledgeBase object.

static dump(session, kb)[源代码]
参数:
  • session -- The database session object.

  • kb (KnowledgeBase) -- The KnowledgeBase instance to serialize.

返回:

None

static load(session, project, name)[源代码]
参数:

session

返回:

class angr.angrdb.serializers.labels.LabelsSerializer[源代码]

基类:object

Serialize/unserialize labels to/from a database session.

static dump(session, db_kb, labels)[源代码]
参数:
返回:

None

static load(session, db_kb, kb)[源代码]
参数:
返回:

class angr.angrdb.serializers.loader.LoadArgsJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[源代码]

基类:JSONEncoder

A JSON encoder that supports serializing bytes.

default(o)[源代码]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
class angr.angrdb.serializers.loader.LoadArgsJSONDecoder[源代码]

基类:JSONDecoder

A JSON decoder that supports unserializing into bytes.

__init__()[源代码]

object_hook, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).

object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

If strict is false (true is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including '\t' (tab), '\n', '\r' and '\0'.

class angr.angrdb.serializers.loader.LoaderSerializer[源代码]

基类:object

Serialize/unserialize a CLE Loader object into/from an angr DB.

Corner cases: - For certain backends (e.g., CART), we do not store the data of the main object. angr will unpack the CART file

again after loading the database.

NO_MAINBIN_BACKENDS = [<class 'cle.backends.cartfile.CARTFile'>]
LOAD_ARG_BLACKLIST = {'is_main_bin', 'loader'}
backend2name = {<class 'cle.backends.blob.Blob'>: 'blob', <class 'cle.backends.cartfile.CARTFile'>: 'cart', <class 'cle.backends.cgc.backedcgc.BackedCGC'>: 'backedcgc', <class 'cle.backends.cgc.cgc.CGC'>: 'cgc', <class 'cle.backends.coff.Coff'>: 'COFF', <class 'cle.backends.elf.elf.ELF'>: 'elf', <class 'cle.backends.elf.elfcore.ELFCore'>: 'elfcore', <class 'cle.backends.ihex.Hex'>: 'hex', <class 'cle.backends.java.apk.Apk'>: 'apk', <class 'cle.backends.java.jar.Jar'>: 'jar', <class 'cle.backends.macho.macho.MachO'>: 'mach-o', <class 'cle.backends.minidump.Minidump'>: 'minidump', <class 'cle.backends.named_region.NamedRegion'>: 'named_region', <class 'cle.backends.pe.pe.PE'>: 'pe', <class 'cle.backends.srec.SRec'>: 'srec', <class 'cle.backends.static_archive.StaticArchive'>: 'AR', <class 'cle.backends.te.TE'>: 'te', <class 'cle.backends.uefi_firmware.UefiFirmware'>: 'uefi', <class 'cle.backends.xbe.XBE'>: 'xbe'}
static json_serialize_load_args(load_args)[源代码]
返回类型:

str

参数:

load_args (dict[str, Any])

static should_skip_main_binary(loader)[源代码]
返回类型:

tuple[bool, Backend | None]

static dump(session, loader)[源代码]
static load(session)[源代码]
class angr.angrdb.serializers.xrefs.XRefsSerializer[源代码]

基类:object

Serialize/unserialize an XRefs object to/from a database session.

static dump(session, db_kb, xrefs)[源代码]
参数:
返回:

static load(session, db_kb, kb, cfg_model=None)[源代码]
参数:
返回:

class angr.angrdb.serializers.variables.VariableManagerSerializer[源代码]

基类:object

Serialize/unserialize a variable manager and its variables.

static dump(session, db_kb, var_manager)[源代码]
参数:
static dump_internal(session, db_kb, internal_manager, func_addr, ident=None)[源代码]
参数:
static load(session, db_kb, kb, ident=None)[源代码]
参数:
static load_internal(db_varcoll, variable_manager)[源代码]
返回类型:

VariableManagerInternal

参数:

variable_manager (VariableManager)

class angr.angrdb.serializers.structured_code.StructuredCodeManagerSerializer[源代码]

基类:object

Serialize/unserialize a structured code manager.

static dump(session, db_kb, code_manager)[源代码]
参数:
返回:

static dict_strkey_to_intkey(d)[源代码]
返回类型:

dict[int, Any]

参数:

d (dict[str, Any])

static load(session, db_kb, kb)[源代码]
参数:
返回类型:

StructuredCodeManager

返回:

A loaded structured code manager

class angr.analyses.decompiler.structuring.recursive_structurer.RecursiveStructurer(region, cond_proc=None, func=None, structurer_cls=None, **kwargs)[源代码]

基类:Analysis

Recursively structure a region and all of its subregions.

参数:
__init__(region, cond_proc=None, func=None, structurer_cls=None, **kwargs)[源代码]
参数:
angr.analyses.decompiler.structuring.DEFAULT_STRUCTURER

SAILRStructurer 的别名

class angr.analyses.decompiler.structuring.DreamStructurer(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, **kwargs)[源代码]

基类:StructurerBase

Structure a region using a structuring algorithm that is similar to the one in Dream decompiler (described in the "no more gotos" paper). Note that this implementation has quite a few improvements over the original described version and should not be used to evaluate the performance of the original algorithm described in that paper.

The current function graph is provided so that we can detect certain edge cases, for example, jump table entries no longer exist due to empty node removal during structuring or prior steps.

参数:
NAME: str = 'dream'
__init__(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, **kwargs)[源代码]
参数:
class angr.analyses.decompiler.structuring.PhoenixStructurer(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, improve_algorithm=False, use_multistmtexprs=MultiStmtExprMode.MAX_ONE_CALL, **kwargs)[源代码]

基类:StructurerBase

Structure a region using a structuring algorithm that is similar to the one in Phoenix decompiler (described in the "phoenix decompiler" paper). Note that this implementation has quite a few improvements over the original described version and should not be used to evaluate the performance of the original algorithm described in that paper.

参数:
NAME: str = 'phoenix'
__init__(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, improve_algorithm=False, use_multistmtexprs=MultiStmtExprMode.MAX_ONE_CALL, **kwargs)[源代码]
参数:
static dump_graph(graph, path)[源代码]
返回类型:

None

参数:
  • graph (DiGraph)

  • path (str)

static switch_case_entry_node_has_common_successor_case_1(graph, jump_table, case_nodes, node_pred)[源代码]
返回类型:

bool

static switch_case_entry_node_has_common_successor_case_2(graph, jump_table, case_nodes, node_pred)[源代码]
返回类型:

bool

class angr.analyses.decompiler.structuring.RecursiveStructurer(region, cond_proc=None, func=None, structurer_cls=None, **kwargs)[源代码]

基类:Analysis

Recursively structure a region and all of its subregions.

参数:
__init__(region, cond_proc=None, func=None, structurer_cls=None, **kwargs)[源代码]
参数:
class angr.analyses.decompiler.structuring.SAILRStructurer(region, improve_phoenix=True, **kwargs)[源代码]

基类:PhoenixStructurer

The SAILR structuring algorithm is the phoenix-based algorithm from the USENIX 2024 paper SAILR. The entirety of the algorithm is implemented across this class and various optimization passes in the decompiler. To find each optimization class, simply search for optimizations which reference this class.NAME.

At a high-level, SAILR does three things different from the traditional Phoenix schema-based algorithm: 1. It recursively structures the graph, rather than doing it in a single pass. This allows decisions to be made

based on the current state of what the decompilation would look like.

  1. It performs deoptimizations targeting specific optimizations that introduces gotos and mis-structured code.

    It can only do this because of the recursive nature of the algorithm.

  2. It uses a more advanced heuristic for virtualizing edges, which is implemented in this class.

Additionally, some changes in Phoenix are only activated when SAILR is used.

NAME: str = 'sailr'
__init__(region, improve_phoenix=True, **kwargs)[源代码]
angr.analyses.decompiler.structuring.structurer_class_from_name(name)[源代码]
返回类型:

type | None

参数:

name (str)

class angr.analyses.decompiler.structuring.dream.DreamStructurer(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, **kwargs)[源代码]

基类:StructurerBase

Structure a region using a structuring algorithm that is similar to the one in Dream decompiler (described in the "no more gotos" paper). Note that this implementation has quite a few improvements over the original described version and should not be used to evaluate the performance of the original algorithm described in that paper.

The current function graph is provided so that we can detect certain edge cases, for example, jump table entries no longer exist due to empty node removal during structuring or prior steps.

参数:
NAME: str = 'dream'
__init__(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, **kwargs)[源代码]
参数:
project: Project
kb: KnowledgeBase
exception angr.analyses.decompiler.structuring.structurer_nodes.EmptyBlockNotice[源代码]

基类:Exception

class angr.analyses.decompiler.structuring.structurer_nodes.MultiNode(nodes, addr=None, idx=None)[源代码]

基类:object

__init__(nodes, addr=None, idx=None)[源代码]
nodes
addr
idx
copy()[源代码]
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.BaseNode[源代码]

基类:object

static test_empty_node(node)[源代码]
static test_empty_condition_node(cond_node)[源代码]
addr: int | None
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.SequenceNode(addr, nodes=None)[源代码]

基类:BaseNode

参数:

addr (int | None)

__init__(addr, nodes=None)[源代码]
参数:

addr (int | None)

addr: int | None
nodes
add_node(node)[源代码]
insert_node(pos, node)[源代码]
remove_node(node)[源代码]
node_position(node)[源代码]
copy()[源代码]
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.CodeNode(node, reaching_condition)[源代码]

基类:BaseNode

__init__(node, reaching_condition)[源代码]
node
reaching_condition
property addr
property idx
dbg_repr(indent=0)[源代码]
copy()[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.ConditionNode(addr, reaching_condition, condition, true_node, false_node=None)[源代码]

基类:BaseNode

参数:

addr (int | None)

__init__(addr, reaching_condition, condition, true_node, false_node=None)[源代码]
addr: int | None
reaching_condition
condition
true_node
false_node
dbg_repr(indent=0)[源代码]
node
class angr.analyses.decompiler.structuring.structurer_nodes.CascadingConditionNode(addr, condition_and_nodes, else_node=None)[源代码]

基类:BaseNode

参数:
__init__(addr, condition_and_nodes, else_node=None)[源代码]
参数:
addr: int | None
condition_and_nodes
else_node
class angr.analyses.decompiler.structuring.structurer_nodes.LoopNode(sort, condition, sequence_node, addr=None, continue_addr=None, initializer=None, iterator=None)[源代码]

基类:BaseNode

参数:
  • sort (str)

  • condition (ailment.Expr.Expression | None)

  • sequence_node (SequenceNode)

  • addr (int | None)

  • continue_addr (int | None)

  • initializer (ailment.Stmt.Assignment | None)

  • iterator (ailment.Stmt.Assignment | None)

__init__(sort, condition, sequence_node, addr=None, continue_addr=None, initializer=None, iterator=None)[源代码]
参数:
sort: str
condition: Expression | None
sequence_node: SequenceNode
initializer: Assignment | None
iterator: Assignment | None
copy()[源代码]
property addr
property continue_addr
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.BreakNode(addr, target)[源代码]

基类:BaseNode

参数:

addr (int | None)

__init__(addr, target)[源代码]
addr: int | None
target
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.ContinueNode(addr, target)[源代码]

基类:BaseNode

参数:

addr (int | None)

__init__(addr, target)[源代码]
addr: int | None
target
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.ConditionalBreakNode(addr, condition, target)[源代码]

基类:BreakNode

参数:

addr (int | None)

__init__(addr, condition, target)[源代码]
condition
dbg_repr(indent=0)[源代码]
class angr.analyses.decompiler.structuring.structurer_nodes.SwitchCaseNode(switch_expr, cases, default_node, addr=None)[源代码]

基类:BaseNode

参数:
__init__(switch_expr, cases, default_node, addr=None)[源代码]
参数:

cases (OrderedDict[int | tuple[int, ...], SequenceNode])

switch_expr
cases: OrderedDict[int | tuple[int, ...], SequenceNode]
default_node
addr: int | None
class angr.analyses.decompiler.structuring.structurer_nodes.IncompleteSwitchCaseNode(addr, head, cases)[源代码]

基类:BaseNode

Describes an incomplete set of switch-case nodes. Usually an intermediate result. Should always be restructured into a SwitchCaseNode by the end of structuring. Only used in Phoenix structurer.

参数:
__init__(addr, head, cases)[源代码]
参数:

cases (list)

addr: int | None
head
cases: list
class angr.analyses.decompiler.structuring.structurer_nodes.IncompleteSwitchCaseHeadStatement(*args, **kwargs)[源代码]

基类:Statement

Describes a switch-case head. This is only created by LoweredSwitchSimplifier.

__init__(idx, switch_variable, case_addrs, **kwargs)[源代码]
switch_variable
case_addrs: list[tuple[Block, int | str, int, int | None, int]]
replace(old_expr, new_expr)[源代码]
likes(other)[源代码]
addr
matches(other)[源代码]
class angr.analyses.decompiler.structuring.structurer_base.StructurerBase(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, **kwargs)[源代码]

基类:Analysis

The base class for analysis passes that structures a region.

The current function graph is provided so that we can detect certain edge cases, for example, jump table entries no longer exist due to empty node removal during structuring or prior steps.

参数:
NAME: str = None
__init__(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, **kwargs)[源代码]
参数:
static replace_nodes(graph, old_node_0, new_node, old_node_1=None, self_loop=True)[源代码]
static replace_node_in_node(parent_node, old_node, new_node)[源代码]
返回类型:

None

参数:
static is_a_jump_target(stmt, addr)[源代码]
返回类型:

bool

参数:
static has_nonlabel_nonphi_statements(node)[源代码]
返回类型:

bool

参数:

node (BaseNode)

exception angr.analyses.decompiler.structuring.phoenix.GraphChangedNotification[源代码]

基类:Exception

A notification for graph that is currently worked on being changed. Once this notification is caught, the graph schema matching process for the current region restarts.

class angr.analyses.decompiler.structuring.phoenix.MultiStmtExprMode(value)[源代码]

基类:str, Enum

Mode of multi-statement expression creation during structuring.

NEVER = 'Never'
ALWAYS = 'Always'
MAX_ONE_CALL = 'Only when less than one call'
class angr.analyses.decompiler.structuring.phoenix.PhoenixStructurer(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, improve_algorithm=False, use_multistmtexprs=MultiStmtExprMode.MAX_ONE_CALL, **kwargs)[源代码]

基类:StructurerBase

Structure a region using a structuring algorithm that is similar to the one in Phoenix decompiler (described in the "phoenix decompiler" paper). Note that this implementation has quite a few improvements over the original described version and should not be used to evaluate the performance of the original algorithm described in that paper.

参数:
NAME: str = 'phoenix'
__init__(region, parent_map=None, condition_processor=None, func=None, case_entry_to_switch_head=None, parent_region=None, improve_algorithm=False, use_multistmtexprs=MultiStmtExprMode.MAX_ONE_CALL, **kwargs)[源代码]
参数:
whitelist_edges: set[tuple[int, int]]
switch_case_known_heads: set[Block]
dowhile_known_tail_nodes: set
static dump_graph(graph, path)[源代码]
返回类型:

None

参数:
  • graph (DiGraph)

  • path (str)

static switch_case_entry_node_has_common_successor_case_1(graph, jump_table, case_nodes, node_pred)[源代码]
返回类型:

bool

static switch_case_entry_node_has_common_successor_case_2(graph, jump_table, case_nodes, node_pred)[源代码]
返回类型:

bool

project: Project
kb: KnowledgeBase
class angr.analyses.decompiler.AILSimplifier(func, func_graph=None, remove_dead_memdefs=False, stack_arg_offsets=None, unify_variables=False, ail_manager=None, gp=None, narrow_expressions=False, only_consts=False, fold_callexprs_into_conditions=False, use_callee_saved_regs_at_return=True, rewrite_ccalls=True, removed_vvar_ids=None, arg_vvars=None, avoid_vvar_ids=None)[源代码]

基类:Analysis

Perform function-level simplifications.

参数:
__init__(func, func_graph=None, remove_dead_memdefs=False, stack_arg_offsets=None, unify_variables=False, ail_manager=None, gp=None, narrow_expressions=False, only_consts=False, fold_callexprs_into_conditions=False, use_callee_saved_regs_at_return=True, rewrite_ccalls=True, removed_vvar_ids=None, arg_vvars=None, avoid_vvar_ids=None)[源代码]
参数:
class angr.analyses.decompiler.BlockSimplifier(block, func_addr=None, remove_dead_memdefs=False, stack_pointer_tracker=None, peephole_optimizations=None, cached_reaching_definitions=None, cached_propagator=None)[源代码]

基类:Analysis

Simplify an AIL block.

参数:
__init__(block, func_addr=None, remove_dead_memdefs=False, stack_pointer_tracker=None, peephole_optimizations=None, cached_reaching_definitions=None, cached_propagator=None)[源代码]
参数:
class angr.analyses.decompiler.CStructuredCodeGenerator(func, sequence, indent=0, cfg=None, variable_kb=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False)[源代码]

基类:BaseStructuredCodeGenerator, Analysis

参数:
__init__(func, sequence, indent=0, cfg=None, variable_kb=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False)[源代码]
参数:
reapply_options(options)[源代码]
cleanup()[源代码]

Remove existing rendering results.

regenerate_text()[源代码]

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

返回类型:

None

RENDER_TYPE

tuple[str, PositionMapping, PositionMapping, InstructionMapping, dict[Any, set[Any]]] 的别名

render_text(cfunc)[源代码]
返回类型:

RENDER_TYPE

参数:

cfunc (CFunction)

reload_variable_types()[源代码]
返回类型:

None

default_simtype_from_bits(n, signed=True)[源代码]
返回类型:

SimType

参数:
class angr.analyses.decompiler.CallSiteMaker(block, reaching_definitions=None, stack_pointer_tracker=None, ail_manager=None)[源代码]

基类:Analysis

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

__init__(block, reaching_definitions=None, stack_pointer_tracker=None, ail_manager=None)[源代码]
class angr.analyses.decompiler.Clinic(func, remove_dead_memdefs=False, exception_edges=False, sp_tracker_track_memory=True, fold_callexprs_into_conditions=False, insert_labels=True, optimization_passes=None, cfg=None, peephole_optimizations=None, must_struct=None, variable_kb=None, reset_variable_names=False, rewrite_ites_to_diamonds=True, cache=None, mode=ClinicMode.DECOMPILE, sp_shift=0, inline_functions=frozenset({}), inlined_counts=None, inlining_parents=None, vvar_id_start=0, optimization_scratch=None, desired_variables=None, force_loop_single_exit=True, complete_successors=False, unsound_fix_abnormal_switches=True)[源代码]

基类:Analysis

A Clinic deals with AILments.

参数:
__init__(func, remove_dead_memdefs=False, exception_edges=False, sp_tracker_track_memory=True, fold_callexprs_into_conditions=False, insert_labels=True, optimization_passes=None, cfg=None, peephole_optimizations=None, must_struct=None, variable_kb=None, reset_variable_names=False, rewrite_ites_to_diamonds=True, cache=None, mode=ClinicMode.DECOMPILE, sp_shift=0, inline_functions=frozenset({}), inlined_counts=None, inlining_parents=None, vvar_id_start=0, optimization_scratch=None, desired_variables=None, force_loop_single_exit=True, complete_successors=False, unsound_fix_abnormal_switches=True)[源代码]
参数:
block(addr, size)[源代码]

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

参数:
返回:

dbg_repr()[源代码]
返回:

calculate_stack_depth()[源代码]
copy_graph(graph=None)[源代码]
返回类型:

DiGraph

parse_variable_addr(addr)[源代码]
返回类型:

tuple[Any, Any] | None

参数:

addr (Expression)

new_block_addr()[源代码]

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

返回类型:

int

返回:

The block address.

static remove_empty_nodes(graph)[源代码]
返回类型:

DiGraph

参数:

graph (DiGraph)

class angr.analyses.decompiler.Decompiler(func, cfg=None, options=None, preset=None, optimization_passes=None, sp_tracker_track_memory=True, variable_kb=None, peephole_optimizations=None, vars_must_struct=None, flavor='pseudocode', expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=True, inline_functions=frozenset({}), desired_variables=frozenset({}), update_memory_data=True, generate_code=True, use_cache=True, expr_collapse_depth=16)[源代码]

基类:Analysis

The decompiler analysis.

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

参数:
  • func (Function | str | int)

  • cfg (CFGFast | CFGModel | None)

  • preset (str | DecompilationPreset | None)

  • peephole_optimizations (_PEEPHOLE_OPTIMIZATIONS_TYPE)

  • vars_must_struct (set[str] | None)

  • update_memory_data (bool)

  • generate_code (bool)

  • use_cache (bool)

  • expr_collapse_depth (int)

__init__(func, cfg=None, options=None, preset=None, optimization_passes=None, sp_tracker_track_memory=True, variable_kb=None, peephole_optimizations=None, vars_must_struct=None, flavor='pseudocode', expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=True, inline_functions=frozenset({}), desired_variables=frozenset({}), update_memory_data=True, generate_code=True, use_cache=True, expr_collapse_depth=16)[源代码]
参数:
reflow_variable_types(type_constraints, func_typevar, var_to_typevar, codegen)[源代码]

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

返回:

参数:
  • type_constraints (set)

  • var_to_typevar (dict)

find_data_references_and_update_memory_data(seq_node)[源代码]
参数:

seq_node (SequenceNode)

static options_to_params(options)[源代码]

Convert decompilation options to a dict of params.

参数:

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

返回类型:

dict[str, Any]

返回:

A dict of keyword arguments.

class angr.analyses.decompiler.GraphDephication(func, ail_graph, vvar_to_vvar_mapping=None, rewrite=False)[源代码]

基类:DephicationBase

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

参数:
__init__(func, ail_graph, vvar_to_vvar_mapping=None, rewrite=False)[源代码]
参数:
  • func (Function | str) -- The subject of the analysis: a function, or a single basic block

  • ail_graph -- The AIL graph to transform.

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

  • rewrite (bool)

class angr.analyses.decompiler.ImportSourceCode(function, flavor='source', source_root=None, encoding='utf-8')[源代码]

基类:BaseStructuredCodeGenerator, Analysis

__init__(function, flavor='source', source_root=None, encoding='utf-8')[源代码]
regenerate_text()[源代码]
class angr.analyses.decompiler.RegionIdentifier(func, cond_proc=None, graph=None, update_graph=True, largest_successor_tree_outside_loop=True, force_loop_single_exit=True, complete_successors=False, entry_node_addr=None)[源代码]

基类:Analysis

Identifies regions within a function graph and creates a recursive GraphRegion object. Note, that the analysis may modify the graph in-place. If you want to keep the original graph, set the update_graph parameter to False.

参数:

entry_node_addr (tuple[int, int | None] | None)

__init__(func, cond_proc=None, graph=None, update_graph=True, largest_successor_tree_outside_loop=True, force_loop_single_exit=True, complete_successors=False, entry_node_addr=None)[源代码]
参数:

entry_node_addr (tuple[int, int | None] | None)

static slice_graph(graph, node, frontier, include_frontier=False)[源代码]

Generate a slice of the graph from the head node to the given frontier.

参数:
  • graph (networkx.DiGraph) -- The graph to work on.

  • node -- The starting node in the graph.

  • frontier -- A list of frontier nodes.

  • include_frontier (bool) -- Whether the frontier nodes are included in the slice or not.

返回:

A subgraph.

返回类型:

networkx.DiGraph

class angr.analyses.decompiler.RegionSimplifier(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]

基类:Analysis

Simplifies a given region.

参数:
  • simplify_switches (bool)

  • simplify_ifelse (bool)

__init__(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]
参数:
  • simplify_switches (bool)

  • simplify_ifelse (bool)

class angr.analyses.decompiler.SeqNodeDephication(func, seq_node, vvar_to_vvar_mapping=None, rewrite=False)[源代码]

基类:DephicationBase

SeqNodeDephication removes phi expressions from an AIL SeqNode and its children.

参数:
__init__(func, seq_node, vvar_to_vvar_mapping=None, rewrite=False)[源代码]
参数:
class angr.analyses.decompiler.Ssailification(func, ail_graph, entry=None, canonical_size=8, stack_pointer_tracker=None, func_addr=None, ail_manager=None, ssa_stackvars=False, ssa_tmps=False, func_args=None, vvar_id_start=0)[源代码]

基类:Analysis

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

参数:
__init__(func, ail_graph, entry=None, canonical_size=8, stack_pointer_tracker=None, func_addr=None, ail_manager=None, ssa_stackvars=False, ssa_tmps=False, func_args=None, vvar_id_start=0)[源代码]
参数:
  • func (Function | str) -- The subject of the analysis: a function, or a single basic block

  • ail_graph -- The AIL graph to transform.

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

  • func_addr (int | None)

  • ssa_stackvars (bool)

  • ssa_tmps (bool)

  • func_args (set[VirtualVariable] | None)

  • vvar_id_start (int)

angr.analyses.decompiler.StructuredCodeGenerator

CStructuredCodeGenerator 的别名

exception angr.analyses.decompiler.ail_simplifier.HasCallNotification[源代码]

基类:Exception

Notifies the existence of a call statement.

exception angr.analyses.decompiler.ail_simplifier.HasVVarNotification[源代码]

基类:Exception

Notifies the existence of a VirtualVariable.

class angr.analyses.decompiler.ail_simplifier.AILBlockTempCollector(**kwargs)[源代码]

基类:AILBlockWalker

Collects any temporaries used in a block.

__init__(**kwargs)[源代码]
class angr.analyses.decompiler.ail_simplifier.AILSimplifier(func, func_graph=None, remove_dead_memdefs=False, stack_arg_offsets=None, unify_variables=False, ail_manager=None, gp=None, narrow_expressions=False, only_consts=False, fold_callexprs_into_conditions=False, use_callee_saved_regs_at_return=True, rewrite_ccalls=True, removed_vvar_ids=None, arg_vvars=None, avoid_vvar_ids=None)[源代码]

基类:Analysis

Perform function-level simplifications.

参数:
__init__(func, func_graph=None, remove_dead_memdefs=False, stack_arg_offsets=None, unify_variables=False, ail_manager=None, gp=None, narrow_expressions=False, only_consts=False, fold_callexprs_into_conditions=False, use_callee_saved_regs_at_return=True, rewrite_ccalls=True, removed_vvar_ids=None, arg_vvars=None, avoid_vvar_ids=None)[源代码]
参数:
exception angr.analyses.decompiler.ailgraph_walker.RemoveNodeNotice[源代码]

基类:Exception

class angr.analyses.decompiler.ailgraph_walker.AILGraphWalker(graph, handler, replace_nodes=False)[源代码]

基类:object

Walks an AIL graph and optionally replaces each node with a new node.

参数:

replace_nodes (bool)

__init__(graph, handler, replace_nodes=False)[源代码]
参数:

replace_nodes (bool)

walk()[源代码]
class angr.analyses.decompiler.block_simplifier.HasCallExprWalker[源代码]

基类:AILBlockWalkerBase

Test if an expression contains a call expression inside.

__init__()[源代码]
class angr.analyses.decompiler.block_simplifier.BlockSimplifier(block, func_addr=None, remove_dead_memdefs=False, stack_pointer_tracker=None, peephole_optimizations=None, cached_reaching_definitions=None, cached_propagator=None)[源代码]

基类:Analysis

Simplify an AIL block.

参数:
__init__(block, func_addr=None, remove_dead_memdefs=False, stack_pointer_tracker=None, peephole_optimizations=None, cached_reaching_definitions=None, cached_propagator=None)[源代码]
参数:
class angr.analyses.decompiler.callsite_maker.CallSiteMaker(block, reaching_definitions=None, stack_pointer_tracker=None, ail_manager=None)[源代码]

基类:Analysis

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

__init__(block, reaching_definitions=None, stack_pointer_tracker=None, ail_manager=None)[源代码]
class angr.analyses.decompiler.ccall_rewriters.rewriter_base.CCallRewriterBase(ccall, arch)[源代码]

基类:object

The base class for CCall rewriters.

参数:

ccall (ailment.Expr.VEXCCallExpression)

__init__(ccall, arch)[源代码]
参数:

ccall (VEXCCallExpression)

arch
result: Expression | None
class angr.analyses.decompiler.ccall_rewriters.amd64_ccalls.AMD64CCallRewriter(ccall, arch)[源代码]

基类:CCallRewriterBase

Implements VEX ccall rewriter for AMD64.

参数:

ccall (ailment.Expr.VEXCCallExpression)

class angr.analyses.decompiler.clinic.BlockCache(rd, prop)

基类:tuple

prop

Alias for field number 1

rd

Alias for field number 0

class angr.analyses.decompiler.clinic.ClinicMode(value)[源代码]

基类:Enum

Analysis mode for Clinic.

DECOMPILE = 1
COLLECT_DATA_REFS = 2
class angr.analyses.decompiler.clinic.DataRefDesc(data_addr, data_size, block_addr, stmt_idx, ins_addr, data_type_str)[源代码]

基类:object

The fields of this class is compatible with items inside IRSB.data_refs.

参数:
  • data_addr (int)

  • data_size (int)

  • block_addr (int)

  • stmt_idx (int)

  • ins_addr (int)

  • data_type_str (str)

data_addr: int
data_size: int
block_addr: int
stmt_idx: int
ins_addr: int
data_type_str: str
__init__(data_addr, data_size, block_addr, stmt_idx, ins_addr, data_type_str)
参数:
  • data_addr (int)

  • data_size (int)

  • block_addr (int)

  • stmt_idx (int)

  • ins_addr (int)

  • data_type_str (str)

返回类型:

None

class angr.analyses.decompiler.clinic.Clinic(func, remove_dead_memdefs=False, exception_edges=False, sp_tracker_track_memory=True, fold_callexprs_into_conditions=False, insert_labels=True, optimization_passes=None, cfg=None, peephole_optimizations=None, must_struct=None, variable_kb=None, reset_variable_names=False, rewrite_ites_to_diamonds=True, cache=None, mode=ClinicMode.DECOMPILE, sp_shift=0, inline_functions=frozenset({}), inlined_counts=None, inlining_parents=None, vvar_id_start=0, optimization_scratch=None, desired_variables=None, force_loop_single_exit=True, complete_successors=False, unsound_fix_abnormal_switches=True)[源代码]

基类:Analysis

A Clinic deals with AILments.

参数:
__init__(func, remove_dead_memdefs=False, exception_edges=False, sp_tracker_track_memory=True, fold_callexprs_into_conditions=False, insert_labels=True, optimization_passes=None, cfg=None, peephole_optimizations=None, must_struct=None, variable_kb=None, reset_variable_names=False, rewrite_ites_to_diamonds=True, cache=None, mode=ClinicMode.DECOMPILE, sp_shift=0, inline_functions=frozenset({}), inlined_counts=None, inlining_parents=None, vvar_id_start=0, optimization_scratch=None, desired_variables=None, force_loop_single_exit=True, complete_successors=False, unsound_fix_abnormal_switches=True)[源代码]
参数:
block(addr, size)[源代码]

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

参数:
返回:

dbg_repr()[源代码]
返回:

calculate_stack_depth()[源代码]
copy_graph(graph=None)[源代码]
返回类型:

DiGraph

parse_variable_addr(addr)[源代码]
返回类型:

tuple[Any, Any] | None

参数:

addr (Expression)

new_block_addr()[源代码]

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

返回类型:

int

返回:

The block address.

static remove_empty_nodes(graph)[源代码]
返回类型:

DiGraph

参数:

graph (DiGraph)

class angr.analyses.decompiler.condition_processor.ConditionProcessor(arch, condition_mapping=None)[源代码]

基类:object

Convert between claripy AST and AIL expressions. Also calculates reaching conditions of all nodes on a graph.

__init__(arch, condition_mapping=None)[源代码]
clear()[源代码]
recover_edge_condition(graph, src, dst)[源代码]
参数:

graph (DiGraph)

recover_edge_conditions(region, graph=None)[源代码]
返回类型:

dict

recover_reaching_conditions(region, graph=None, with_successors=False, case_entry_to_switch_head=None, simplify_conditions=True)[源代码]

Recover the reaching conditions for each block in an acyclic graph. Note that we assume the graph that's passed in is acyclic.

参数:
  • case_entry_to_switch_head (dict[int, int] | None)

  • simplify_conditions (bool)

remove_claripy_bool_asts(node, memo=None)[源代码]
classmethod get_last_statement(block)[源代码]

This is the buggy version of get_last_statements, because, you know, there can always be more than one last statement due to the existence of branching statements (like, If-then-else). All methods using get_last_statement() should switch to get_last_statements() and properly handle multiple last statements.

classmethod get_last_statements(block)[源代码]
返回类型:

list[Statement | None]

EXC_COUNTER = 1000
convert_claripy_bool_ast(cond, memo=None)[源代码]

Convert recovered reaching conditions from claripy ASTs to ailment Expressions

返回:

None

convert_claripy_bool_ast_core(cond, memo)[源代码]
claripy_ast_from_ail_condition(condition, nobool=False, *, ins_addr=0)[源代码]
返回类型:

Bool | Bits

参数:
static claripy_ast_to_sympy_expr(ast, memo=None)[源代码]
static sympy_expr_to_claripy_ast(expr, memo)[源代码]
参数:

memo (dict)

static simplify_condition(cond, depth_limit=8, variables_limit=8)[源代码]
static simplify_condition_deprecated(cond)[源代码]
create_jump_target_var(jumptable_head_addr)[源代码]
参数:

jumptable_head_addr (int)

class angr.analyses.decompiler.decompilation_options.DecompilationOption(name, description, value_type, cls, param, value_range=None, category='General', default_value=None, clears_cache=True, candidate_values=None, convert=None)[源代码]

基类:object

Describes a decompilation option.

参数:
__init__(name, description, value_type, cls, param, value_range=None, category='General', default_value=None, clears_cache=True, candidate_values=None, convert=None)[源代码]
参数:
angr.analyses.decompiler.decompilation_options.O

DecompilationOption 的别名

angr.analyses.decompiler.decompilation_options.get_structurer_option()[源代码]
返回类型:

DecompilationOption | None

class angr.analyses.decompiler.decompilation_cache.DecompilationCache(addr)[源代码]

基类:object

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

__init__(addr)[源代码]
parameters: dict[str, Any]
addr
type_constraints: set | None
func_typevar
var_to_typevar: dict | None
codegen: BaseStructuredCodeGenerator | None
clinic: Clinic | None
ite_exprs: set[tuple[int, Any]] | None
binop_operators: dict[OpDescriptor, str] | None
errors: list[str]
property local_types
class angr.analyses.decompiler.decompiler.Decompiler(func, cfg=None, options=None, preset=None, optimization_passes=None, sp_tracker_track_memory=True, variable_kb=None, peephole_optimizations=None, vars_must_struct=None, flavor='pseudocode', expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=True, inline_functions=frozenset({}), desired_variables=frozenset({}), update_memory_data=True, generate_code=True, use_cache=True, expr_collapse_depth=16)[源代码]

基类:Analysis

The decompiler analysis.

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

参数:
  • func (Function | str | int)

  • cfg (CFGFast | CFGModel | None)

  • preset (str | DecompilationPreset | None)

  • peephole_optimizations (_PEEPHOLE_OPTIMIZATIONS_TYPE)

  • vars_must_struct (set[str] | None)

  • update_memory_data (bool)

  • generate_code (bool)

  • use_cache (bool)

  • expr_collapse_depth (int)

__init__(func, cfg=None, options=None, preset=None, optimization_passes=None, sp_tracker_track_memory=True, variable_kb=None, peephole_optimizations=None, vars_must_struct=None, flavor='pseudocode', expr_comments=None, stmt_comments=None, ite_exprs=None, binop_operators=None, decompile=True, regen_clinic=True, inline_functions=frozenset({}), desired_variables=frozenset({}), update_memory_data=True, generate_code=True, use_cache=True, expr_collapse_depth=16)[源代码]
参数:
reflow_variable_types(type_constraints, func_typevar, var_to_typevar, codegen)[源代码]

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

返回:

参数:
  • type_constraints (set)

  • var_to_typevar (dict)

find_data_references_and_update_memory_data(seq_node)[源代码]
参数:

seq_node (SequenceNode)

static options_to_params(options)[源代码]

Convert decompilation options to a dict of params.

参数:

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

返回类型:

dict[str, Any]

返回:

A dict of keyword arguments.

class angr.analyses.decompiler.empty_node_remover.EmptyNodeRemover(node, claripy_ast_conditions=True)[源代码]

基类:object

Rewrites a node and its children to remove empty nodes.

The following optimizations are performed at the same time: - Convert if (A) { } else { ... } to if(!A) { ... } else { }

变量:

_claripy_ast_conditions -- True if all node conditions are claripy ASTs. False if all node conditions are AIL expressions.

参数:

claripy_ast_conditions (bool)

__init__(node, claripy_ast_conditions=True)[源代码]
参数:

claripy_ast_conditions (bool)

class angr.analyses.decompiler.expression_narrower.ExprNarrowingInfo(narrowable, to_size=None, use_exprs=None, phi_vars=None)[源代码]

基类:object

Stores the analysis result of _narrowing_needed().

参数:
__init__(narrowable, to_size=None, use_exprs=None, phi_vars=None)[源代码]
参数:
narrowable
to_size
use_exprs
phi_vars
class angr.analyses.decompiler.expression_narrower.NarrowingInfoExtractor(target_expr)[源代码]

基类:AILBlockWalkerBase

Walks a statement or an expression and extracts the operations that are applied on the given expression.

For example, for target expression rax, (rax & 0xff) + 0x1 means the following operations are applied on rax: rax & 0xff (rax & 0xff) + 0x1

The previous expression is always used in the succeeding expression.

参数:

target_expr (Expression)

__init__(target_expr)[源代码]
参数:

target_expr (Expression)

class angr.analyses.decompiler.expression_narrower.ExpressionNarrower(project, rd, narrowables, addr2blocks, new_blocks)[源代码]

基类:AILBlockWalker

Narrows an expression regardless of whether the expression is a definition or a use.

参数:
__init__(project, rd, narrowables, addr2blocks, new_blocks)[源代码]
参数:
walk(block)[源代码]

Walk the block and rebuild it if necessary. The block will be rebuilt in-place (by updating statements in the original block when self._update_block is set to True), or a new block will be created and returned.

参数:

block (Block) -- The block to walk.

返回:

The new block that is rebuilt, or None if the block is not changed or when self._update_block is set to True.

class angr.analyses.decompiler.graph_region.GraphRegion(head, graph, successors, graph_with_successors, cyclic, full_graph, cyclic_ancestor=False)[源代码]

基类:object

GraphRegion represents a region of nodes.

变量:
  • head -- The head of the region.

  • graph -- The region graph.

  • successors -- A set of successors of nodes in the graph. These successors do not belong to the current region.

  • graph_with_successors -- The region graph that includes successor nodes.

参数:
  • successors (set | None)

  • graph_with_successors (networkx.DiGraph | None)

  • full_graph (networkx.DiGraph | None)

  • cyclic_ancestor (bool)

__init__(head, graph, successors, graph_with_successors, cyclic, full_graph, cyclic_ancestor=False)[源代码]
参数:
  • successors (set | None)

  • graph_with_successors (DiGraph | None)

  • full_graph (DiGraph | None)

  • cyclic_ancestor (bool)

head
graph
successors
graph_with_successors
full_graph
cyclic
cyclic_ancestor
copy()[源代码]
返回类型:

GraphRegion

recursive_copy(nodes_map=None)[源代码]
property addr
static dbg_get_repr(obj, ident=0)[源代码]
dbg_print(ident=0)[源代码]
replace_region(sub_region, updated_sub_region, replace_with, virtualized_edges)[源代码]
参数:
replace_region_with_region(sub_region, replace_with)[源代码]
参数:
class angr.analyses.decompiler.jump_target_collector.JumpTargetCollector(node)[源代码]

基类:object

Collect all jump targets.

__init__(node)[源代码]
class angr.analyses.decompiler.jumptable_entry_condition_rewriter.JumpTableEntryConditionRewriter(jumptable_entry_conds)[源代码]

基类:SequenceWalker

Remove artificial jump table entry conditions that ConditionProcessor introduced when dealing with jump tables.

__init__(jumptable_entry_conds)[源代码]
class angr.analyses.decompiler.optimization_passes.BasePointerSaveSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes the effects of base pointer stack storage at function invocation and restoring at function return.

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['cgc', 'linux']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify base pointer saving'
DESCRIPTION = 'Removes the effects of base pointer stack storage at function invocation and restoring at function return.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.CallStatementRewriter(func, **kwargs)[源代码]

基类:OptimizationPass

Rewrite call statements to assignments if needed.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 3
NAME = 'Unify call statements on demand.'
DESCRIPTION = 'Rewrite call statements to assignments if needed.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.CodeMotionOptimization(func, *args, max_iters=10, node_idx_start=0, **kwargs)[源代码]

基类:OptimizationPass

Moves common statements out of blocks that share the same predecessors or the same successors. This is done to reduce the number of statements in a block and to make the blocks more similar to each other.

As an example: if (x) {

b = 2; a = 1; c = 3;

} else {

b = 2; c = 3;

}

Will be turned into: if (x) {

a = 1;

} b = 2; c = 3;

Current limitations (for very conservative operations): - moving statements above conditional jumps is not supported - only immediate children and parents are considered for moving statements - when moving statements down, a block is only considered if already has a matching statement at the end

参数:

node_idx_start (int)

ARCHES = None
PLATFORMS = None
NAME = 'Merge common statements in sub-scopes'
STAGE: OptimizationPassStage = 4
DESCRIPTION = '\n    Moves common statements out of blocks that share the same predecessors or the same\n    successors. This is done to reduce the number of statements in a block and to make the\n    blocks more similar to each other.\n\n    As an example:\n    if (x) {\n        b = 2;\n        a = 1;\n        c = 3;\n    } else {\n        b = 2;\n        c = 3;\n    }\n\n    Will be turned into:\n    if (x) {\n        a = 1;\n    }\n    b = 2;\n    c = 3;\n\n    Current limitations (for very conservative operations):\n    - moving statements above conditional jumps is not supported\n    - only immediate children and parents are considered for moving statements\n    - when moving statements down, a block is only considered if already has a matching statement at the end\n    '
__init__(func, *args, max_iters=10, node_idx_start=0, **kwargs)[源代码]
参数:

node_idx_start (int)

static update_graph_with_super_edits(original_graph, super_graph, updated_blocks)[源代码]

This function updates an graph when doing block edits on a supergraph version of that same graph. The updated blocks must be provided as a dictionary where the keys are original block in the supergraph and the values are the new blocks that should replace them.

The supergraph MUST be generated using the to_ail_supergraph function, since it stores the original nodes each super node represents. This is necessary to update the original graph with the new super nodes.

返回类型:

bool

参数:
  • original_graph (DiGraph)

  • super_graph (DiGraph)

  • updated_blocks (dict[Block, Block])

class angr.analyses.decompiler.optimization_passes.ConstPropOptReverter(func, region_identifier=None, reaching_definitions=None, **kwargs)[源代码]

基类:OptimizationPass

This optimization reverts the effects of constant propagation done by the compiler as discussed in the USENIX 2024 paper SAILR. This optimization's main goal is to enable later optimizations that rely on symbolic variables to be more effective. This optimization pass will convert two statements with a difference of a const and a symbolic variable into two statements with the symbolic variables.

As an example: x = 75 puts(x) puts(75)

will be converted to: x = 75 puts(x) puts(x)

ARCHES = None
PLATFORMS = None
STRUCTURING: list[str] | None = ['sailr', 'dream']
STAGE: OptimizationPassStage = 7
NAME = 'Revert Constant Propagation Optimizations'
DESCRIPTION = "This optimization reverts the effects of constant propagation done by the compiler as discussed in the\n    USENIX 2024 paper SAILR. This optimization's main goal is to enable later optimizations that rely on\n    symbolic variables to be more effective. This optimization pass will convert two statements with a difference of\n    a const and a symbolic variable into two statements with the symbolic variables.\n\n    As an example:\n    x = 75\n    puts(x)\n    puts(75)\n\n    will be converted to:\n    x = 75\n    puts(x)\n    puts(x)"
__init__(func, region_identifier=None, reaching_definitions=None, **kwargs)[源代码]
static find_conflicting_call_args(call0, call1)[源代码]
参数:
class angr.analyses.decompiler.optimization_passes.ConstantDereferencesSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Makes the following simplifications:

*(*(const_addr))  ==>  *(value) iff  *const_addr == value
ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 2
NAME = 'Simplify constant dereferences'
DESCRIPTION = 'Makes the following simplifications::\n\n        *(*(const_addr))  ==>  *(value) iff  *const_addr == value'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.CrossJumpReverter(func, node_idx_start=0, max_opt_iters=3, max_call_duplications=1, **kwargs)[源代码]

基类:StructuringOptimizationPass

This is an implementation to revert the compiler optimization Cross Jumping, and ISC optimization discussed in the USENIX 2024 paper SAILR. This optimization is somewhat aggressive and as such should be run last in your decompiler deoptimization chain. This deoptimization will take any goto it finds and attempt to duplicate its target block if its target only has one outgoing edge.

There are some heuristics in place to prevent duplication everywhere. First, this deoptimization will only run a max of max_opt_iters times. Second, it will not duplicate a block with too many calls.

参数:
  • node_idx_start (int)

  • max_opt_iters (int)

  • max_call_duplications (int)

STAGE: OptimizationPassStage = 7
NAME = 'Duplicate linear blocks with gotos'
DESCRIPTION = 'This is an implementation to revert the compiler optimization Cross Jumping, and ISC optimization discussed\nin the USENIX 2024 paper SAILR. This optimization is somewhat aggressive and as such should be run last in your\ndecompiler deoptimization chain. This deoptimization will take any goto it finds and attempt to duplicate its\ntarget block if its target only has one outgoing edge.\n\nThere are some heuristics in place to prevent duplication everywhere. First, this deoptimization will only run\na max of max_opt_iters times. Second, it will not duplicate a block with too many calls.'
__init__(func, node_idx_start=0, max_opt_iters=3, max_call_duplications=1, **kwargs)[源代码]
参数:
  • node_idx_start (int)

  • max_opt_iters (int)

  • max_call_duplications (int)

class angr.analyses.decompiler.optimization_passes.DeadblockRemover(func, **kwargs)[源代码]

基类:OptimizationPass

Removes condition-unreachable blocks from the graph.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 6
NAME = 'Remove blocks with unsatisfiable conditions'
DESCRIPTION = 'Removes condition-unreachable blocks from the graph.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.DivSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies various division optimizations back to "div".

ARCHES = ['X86', 'AMD64', 'ARMCortexM', 'ARMHF', 'ARMEL']
PLATFORMS = None
STAGE: OptimizationPassStage = 4
NAME = 'Simplify arithmetic division'
DESCRIPTION = 'Simplifies various division optimizations back to "div".'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.DuplicationReverter(func, max_guarding_conditions=4, **kwargs)[源代码]

基类:StructuringOptimizationPass

This (de)optimization reverts the effects of many compiler optimizations that cause code duplication in the decompilation. This deoptimization is the implementation of the USENIX 2024 paper SAILR's ISD doptimization. As such, the main goal of this optimization is to remove code duplication by merging semantically similar blocks in the AIL graph.

NAME = 'Revert Statement Duplication Optimizations'
DESCRIPTION = "This (de)optimization reverts the effects of many compiler optimizations that cause code duplication in\n    the decompilation. This deoptimization is the implementation of the USENIX 2024 paper SAILR's ISD\n    doptimization. As such, the main goal of this optimization is to remove code duplication by merging\n    semantically similar blocks in the AIL graph."
__init__(func, max_guarding_conditions=4, **kwargs)[源代码]
static boolean_operators_in_condition(condition)[源代码]

TODO: this entire boolean checking semantic we use needs to be removed, see how it is used for other dels needed we need to replace it with a boolean variable insertion on both branches that lead to the new block say we have: if (A()) {

do_thing();

} if (B()) {

do_thing():

}

We want to translate it to: int should_do_thing = 0; if (A())

should_do_thing = 1;

if (B())

should_do_thing = 1;

if (should_do_thing):

do_thing();

Although longer, this code can be optimized to look like: int should_do_thing = A() || B(); if (should_do_thing)

do_thing();

参数:

condition (Expression)

stmt_can_move_to(stmt, block, new_idx, io_finder=None)[源代码]
maximize_similarity_of_blocks(block1, block2, graph)[源代码]

This attempts to rearrange the order of statements in block1 and block2 to maximize the similarity between them. This implementation is a little outdated since CodeMotion optimization was implemented, but it should be disabled until we have a good SSA implementation.

TODO: reimplement me when we have better SSA

返回类型:

tuple[Block, Block]

create_merged_subgraph(blocks, graph, maximize_similarity=False)[源代码]
返回类型:

AILMergeGraph

参数:

graph (DiGraph)

similar_conditional_when_single_corrected(block1, block2, graph)[源代码]
参数:
collect_conditions_between_nodes(graph, source, sinks, max_depth=15)[源代码]
参数:
shared_common_conditional_dom(nodes, graph)[源代码]

Takes n nodes and returns True only if all the nodes are dominated by the same node, which must be a ConditionalJump

@param nodes: @param graph: @return:

参数:

graph (DiGraph)

class angr.analyses.decompiler.optimization_passes.ExprOpSwapper(func, binop_operators=None, **kwargs)[源代码]

基类:SequenceOptimizationPass

Swap operands (and the operator accordingly) in a BinOp expression.

参数:

binop_operators (dict[OpDescriptor, str] | None)

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['windows', 'linux', 'cgc']
STAGE: OptimizationPassStage = 8
NAME = 'Swap operands of expressions as requested'
DESCRIPTION = 'Swap operands (and the operator accordingly) in a BinOp expression.'
__init__(func, binop_operators=None, **kwargs)[源代码]
参数:

binop_operators (dict[OpDescriptor, str] | None)

class angr.analyses.decompiler.optimization_passes.FlipBooleanCmp(func, flip_size=10, **kwargs)[源代码]

基类:SequenceOptimizationPass

In the scenario in which a false node has no apparent successors, flip the condition on that if-stmt. This is only useful when StructuredCodeGenerator has simplify_else_scopes enabled, as this will allow the flipped if-stmt to remove the redundant else.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 8
NAME = 'Flip small ret booleans'
DESCRIPTION = 'When false node has no successors, flip condition so else scope can be simplified later'
__init__(func, flip_size=10, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.ITEExprConverter(func, ite_exprs=None, **kwargs)[源代码]

基类:OptimizationPass

Transform specific expressions into If-Then-Else expressions, or tertiary expressions in C when given a single-use expression address. Requires outside analysis to provide the target expressions.

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['windows', 'linux', 'cgc']
STAGE: OptimizationPassStage = 7
NAME = 'Transform single-use expressions that were assigned to in different If-Else branches into ternary expressions'
DESCRIPTION = 'Transform specific expressions into If-Then-Else expressions, or tertiary expressions in C when\n    given a single-use expression address. Requires outside analysis to provide the target expressions.'
__init__(func, ite_exprs=None, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.ITERegionConverter(func, max_updates=10, **kwargs)[源代码]

基类:OptimizationPass

Transform regions of the form if (c) {x = a} else {x = b} into x = c ? a : b.

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['windows', 'linux', 'cgc']
STAGE: OptimizationPassStage = 4
NAME = 'Transform ITE-assignment regions into ternary expression assignments'
DESCRIPTION = 'Transform regions of the form `if (c) {x = a} else {x = b}` into `x = c ? a : b`.'
__init__(func, max_updates=10, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.InlinedStringTransformationSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies inlined string transformation routines.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 4
NAME = 'Simplify string transformations'
DESCRIPTION = 'Simplify string transformations that are commonly used in obfuscated functions.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.LoweredSwitchSimplifier(func, min_distinct_cases=2, **kwargs)[源代码]

基类:StructuringOptimizationPass

This optimization recognizes and reverts switch cases that have been lowered and possibly split into multiple if-else statements. This optimization, discussed in the USENIX 2024 paper SAILR, aims to undo the compiler optimization known as "Switch Lowering", present in both GCC and Clang. An in-depth discussion of this optimization can be found in the paper or in our documentation of the optimization: https://github.com/mahaloz/sailr-eval/issues/14#issue-2232616411

Note, this optimization does not occur in MSVC, which uses a different optimization strategy for switch cases. As a hack for now, we only run this deoptimization on Linux binaries.

PLATFORMS = ['linux']
NAME = 'Convert lowered switch-cases (if-else) to switch-cases'
DESCRIPTION = 'Convert lowered switch-cases (if-else) to switch-cases. Only works when the Phoenix structuring algorithm is in use.'
__init__(func, min_distinct_cases=2, **kwargs)[源代码]
static restore_graph(node, last_stmt, graph, full_graph)[源代码]
参数:
static cases_issubset(cases_0, cases_1)[源代码]

Test if cases_0 is a subset of cases_1.

返回类型:

bool

参数:
class angr.analyses.decompiler.optimization_passes.ModSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies optimized forms of modulo computation back to "mod".

ARCHES = ['X86', 'AMD64', 'ARMCortexM', 'ARMHF', 'ARMEL']
PLATFORMS = ['linux', 'windows']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify optimized mod forms'
DESCRIPTION = 'Simplifies optimized forms of modulo computation back to "mod".'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.OptimizationPassStage(value)[源代码]

基类:Enum

Enums about optimization pass stages.

Note that the region identification pass (RegionIdentifier) may modify existing AIL blocks without updating the topology of the original AIL graph. For example, loop successor refinement may modify create a new AIL block with an artificial address, and alter existing jump targets of jump statements and conditional jump statements to point to this new block. However, loop successor refinement does not update the topology of the original AIL graph, which means this new AIL block does not exist in the original AIL graph. As a result, until this behavior of RegionIdentifier changes in the future, DURING_REGION_IDENTIFICATION optimization passes should not modify existing jump targets.

AFTER_AIL_GRAPH_CREATION = 0
BEFORE_SSA_LEVEL0_TRANSFORMATION = 1
AFTER_SINGLE_BLOCK_SIMPLIFICATION = 2
AFTER_MAKING_CALLSITES = 3
AFTER_GLOBAL_SIMPLIFICATION = 4
AFTER_VARIABLE_RECOVERY = 5
BEFORE_REGION_IDENTIFICATION = 6
DURING_REGION_IDENTIFICATION = 7
AFTER_STRUCTURING = 8
class angr.analyses.decompiler.optimization_passes.RegisterSaveAreaSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Optimizes away register spilling effects, including callee-saved registers.

This optimization runs between SSA-level0 and SSA-level1, which means registers are converted to vvars but stack accesses stay unchanged.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 2
NAME = 'Simplify register save areas'
DESCRIPTION = 'Optimizes away register spilling effects, including callee-saved registers.\n\n    This optimization runs between SSA-level0 and SSA-level1, which means registers are converted to vvars but stack\n    accesses stay unchanged.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.RetAddrSaveSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes code in function prologues and epilogues for saving and restoring return address registers (ra, lr, etc.), generally seen in non-leaf functions.

ARCHES = ['MIPS32', 'MIPS64']
PLATFORMS = ['linux']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify return address storage'
DESCRIPTION = 'Removes code in function prologues and epilogues for saving and restoring return address registers (ra, lr, etc.),\n    generally seen in non-leaf functions.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.ReturnDeduplicator(func, **kwargs)[源代码]

基类:OptimizationPass

Transforms: - if (cond) { ... return x; } return x;

into: - if (cond) { ... } return x;

TODO: its possible that this can be expanded to all rets that are equivalent. Testing needed.

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['windows', 'linux', 'cgc']
STAGE: OptimizationPassStage = 7
NAME = 'Deduplicates return statements that may have been duplicated'
DESCRIPTION = 'Transforms:\n    - if (cond) { ... return x; } return x;\n\n    into:\n    - if (cond) { ... } return x;\n\n    TODO: its possible that this can be expanded to all rets that are equivalent. Testing needed.'
STRUCTURING: list[str] | None = ['sailr', 'dream']
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.ReturnDuplicatorHigh(func, max_calls_in_regions=2, minimize_copies_for_regions=True, region_identifier=None, vvar_id_start=None, scratch=None, **kwargs)[源代码]

基类:OptimizationPass, ReturnDuplicatorBase

This is a light-level goto-less version of the ReturnDuplicator optimization pass. It will only duplicate return-only blocks.

参数:
  • max_calls_in_regions (int)

  • minimize_copies_for_regions (bool)

  • vvar_id_start (int | None)

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

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 5
NAME = 'Duplicate return-only blocks (high)'
DESCRIPTION = '\n    This is a light-level goto-less version of the ReturnDuplicator optimization pass. It will only\n    duplicate return-only blocks.\n    '
STRUCTURING: list[str] | None = ['sailr', 'dream']
__init__(func, max_calls_in_regions=2, minimize_copies_for_regions=True, region_identifier=None, vvar_id_start=None, scratch=None, **kwargs)[源代码]
参数:
  • max_calls_in_regions (int)

  • minimize_copies_for_regions (bool)

  • vvar_id_start (int | None)

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

class angr.analyses.decompiler.optimization_passes.ReturnDuplicatorLow(func, max_opt_iters=4, max_calls_in_regions=2, prevent_new_gotos=True, minimize_copies_for_regions=True, region_identifier=None, vvar_id_start=None, scratch=None, **kwargs)[源代码]

基类:StructuringOptimizationPass, ReturnDuplicatorBase

An optimization pass that reverts a subset of Irreducible Statement Condensing (ISC) optimizations, as described in the USENIX 2024 paper SAILR. This is the heavy/goto version of the ReturnDuplicator optimization pass.

Some compilers, including GCC, Clang, and MSVC, apply various optimizations to reduce the number of statements in code. These optimizations will take equivalent statements, or a subset of them, and replace them with a single copy that is jumped to by gotos -- optimizing for space and sometimes speed.

This optimization pass will revert those gotos by re-duplicating the condensed blocks. Since Return statements are the most common, we use this optimization pass to revert only gotos to return statements. Additionally, we perform some additional readability fixups, like not re-duplicating returns to shared components.

参数:
  • func -- The function to optimize.

  • node_idx_start -- The index to start at when creating new nodes. This is used by Clinic to ensure that node indices are unique across multiple passes.

  • max_opt_iters (int) -- The maximum number of optimization iterations to perform.

  • max_calls_in_regions (int) -- The maximum number of calls that can be in a region. This is used to prevent duplicating too much code.

  • prevent_new_gotos (bool) -- If True, this optimization pass will prevent new gotos from being created.

  • minimize_copies_for_regions (bool) -- If True, this optimization pass will minimize the number of copies by doing only a single copy for connected in_edges that form a region.

  • vvar_id_start (int | None)

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

ARCHES = None
PLATFORMS = None
NAME = 'Duplicate returns connect with gotos (low)'
DESCRIPTION = 'An optimization pass that reverts a subset of Irreducible Statement Condensing (ISC) optimizations, as described\nin the USENIX 2024 paper SAILR. This is the heavy/goto version of the ReturnDuplicator optimization pass.\n\nSome compilers, including GCC, Clang, and MSVC, apply various optimizations to reduce the number of statements in\ncode. These optimizations will take equivalent statements, or a subset of them, and replace them with a single\ncopy that is jumped to by gotos -- optimizing for space and sometimes speed.\n\nThis optimization pass will revert those gotos by re-duplicating the condensed blocks. Since Return statements\nare the most common, we use this optimization pass to revert only gotos to return statements. Additionally, we\nperform some additional readability fixups, like not re-duplicating returns to shared components.'
__init__(func, max_opt_iters=4, max_calls_in_regions=2, prevent_new_gotos=True, minimize_copies_for_regions=True, region_identifier=None, vvar_id_start=None, scratch=None, **kwargs)[源代码]
参数:
  • max_opt_iters (int)

  • max_calls_in_regions (int)

  • prevent_new_gotos (bool)

  • minimize_copies_for_regions (bool)

  • vvar_id_start (int | None)

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

class angr.analyses.decompiler.optimization_passes.StackCanarySimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes stack canary checks from decompilation results.

ARCHES = ['X86', 'AMD64']
PLATFORMS = ['cgc', 'linux']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify stack canaries'
DESCRIPTION = 'Removes stack canary checks from decompilation results.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.SwitchDefaultCaseDuplicator(func, **kwargs)[源代码]

基类:OptimizationPass

For each switch-case construct (identified by jump tables), duplicate the default-case node when we detect situations where the default-case node is seemingly reused by edges outside the switch-case construct. This code reuse is usually caused by compiler code deduplication.

Ideally this pass should be implemented as an ISC optimization reversion.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 0
NAME = 'Duplicate default-case nodes to undo default-case node reuse caused by compiler code deduplication'
DESCRIPTION = 'For each switch-case construct (identified by jump tables), duplicate the default-case node when we detect\n    situations where the default-case node is seemingly reused by edges outside the switch-case construct. This code\n    reuse is usually caused by compiler code deduplication.\n\n    Ideally this pass should be implemented as an ISC optimization reversion.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.SwitchReusedEntryRewriter(func, **kwargs)[源代码]

基类:OptimizationPass

For each switch-case construct (identified by jump tables), rewrite the entry into a goto block when we detect situations where an entry node is reused by edges in switch-case constructs that are not the current one. This code reuse is usually caused by compiler code deduplication.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 0
NAME = 'Rewrite switch-case entry nodes with multiple predecessors into goto statements.'
DESCRIPTION = 'For each switch-case construct (identified by jump tables), rewrite the entry into a goto block when we detect\n    situations where an entry node is reused by edges in switch-case constructs that are not the current one. This code\n    reuse is usually caused by compiler code deduplication.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.TagSlicer(func, **kwargs)[源代码]

基类:OptimizationPass

Removes unmarked statements from the graph.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 5
NAME = 'Remove unmarked statements from the graph.'
DESCRIPTION = 'Removes unmarked statements from the graph.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.WinStackCanarySimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes stack canary checks from decompilation results for Windows PE files.

we need to run this pass before performing any full-function simplification. Otherwise the effects of _security_cookie will be propagated.

ARCHES = ['X86', 'AMD64']
PLATFORMS = ['windows']
STAGE: OptimizationPassStage = 2
NAME = 'Simplify stack canaries in Windows PE files'
DESCRIPTION = 'Removes stack canary checks from decompilation results for Windows PE files.\n\n    we need to run this pass before performing any full-function simplification. Otherwise the effects of\n    _security_cookie will be propagated.'
__init__(func, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.X86GccGetPcSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies __x86.get_pc_thunk calls.

ARCHES = ['X86']
PLATFORMS = ['linux']
STAGE: OptimizationPassStage = 1
NAME = 'Simplify getpc()'
DESCRIPTION = 'Simplifies __x86.get_pc_thunk calls.'
__init__(func, **kwargs)[源代码]
angr.analyses.decompiler.optimization_passes.get_optimization_passes(arch, platform)[源代码]
angr.analyses.decompiler.optimization_passes.register_optimization_pass(opt_pass, *, presets=None)[源代码]
参数:

presets (list[str | DecompilationPreset] | None)

class angr.analyses.decompiler.optimization_passes.const_derefs.BlockWalker(project)[源代码]

基类:AILBlockWalker

参数:

project (Project)

__init__(project)[源代码]
参数:

project (Project)

walk(block)[源代码]

Walk the block and rebuild it if necessary. The block will be rebuilt in-place (by updating statements in the original block when self._update_block is set to True), or a new block will be created and returned.

参数:

block (Block) -- The block to walk.

返回:

The new block that is rebuilt, or None if the block is not changed or when self._update_block is set to True.

class angr.analyses.decompiler.optimization_passes.const_derefs.ConstantDereferencesSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Makes the following simplifications:

*(*(const_addr))  ==>  *(value) iff  *const_addr == value
ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 2
NAME = 'Simplify constant dereferences'
DESCRIPTION = 'Makes the following simplifications::\n\n        *(*(const_addr))  ==>  *(value) iff  *const_addr == value'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
exception angr.analyses.decompiler.optimization_passes.optimization_pass.MultipleBlocksException[源代码]

基类:Exception

An exception that is raised in _get_block() where multiple blocks satisfy the criteria but only one block was requested.

class angr.analyses.decompiler.optimization_passes.optimization_pass.OptimizationPassStage(value)[源代码]

基类:Enum

Enums about optimization pass stages.

Note that the region identification pass (RegionIdentifier) may modify existing AIL blocks without updating the topology of the original AIL graph. For example, loop successor refinement may modify create a new AIL block with an artificial address, and alter existing jump targets of jump statements and conditional jump statements to point to this new block. However, loop successor refinement does not update the topology of the original AIL graph, which means this new AIL block does not exist in the original AIL graph. As a result, until this behavior of RegionIdentifier changes in the future, DURING_REGION_IDENTIFICATION optimization passes should not modify existing jump targets.

AFTER_AIL_GRAPH_CREATION = 0
BEFORE_SSA_LEVEL0_TRANSFORMATION = 1
AFTER_SINGLE_BLOCK_SIMPLIFICATION = 2
AFTER_MAKING_CALLSITES = 3
AFTER_GLOBAL_SIMPLIFICATION = 4
AFTER_VARIABLE_RECOVERY = 5
BEFORE_REGION_IDENTIFICATION = 6
DURING_REGION_IDENTIFICATION = 7
AFTER_STRUCTURING = 8
class angr.analyses.decompiler.optimization_passes.optimization_pass.BaseOptimizationPass(func)[源代码]

基类:object

The base class for any optimization pass.

ARCHES = []
PLATFORMS = []
STAGE: OptimizationPassStage
STRUCTURING: list[str] | None = None
NAME = 'N/A'
DESCRIPTION = 'N/A'
__init__(func)[源代码]
property project: Project
property kb
analyze()[源代码]
class angr.analyses.decompiler.optimization_passes.optimization_pass.OptimizationPass(func, blocks_by_addr=None, blocks_by_addr_and_idx=None, graph=None, variable_kb=None, region_identifier=None, reaching_definitions=None, vvar_id_start=0, entry_node_addr=None, scratch=None, force_loop_single_exit=True, complete_successors=False, avoid_vvar_ids=None, **kwargs)[源代码]

基类:BaseOptimizationPass

The base class for any function-level graph optimization pass.

参数:
  • vvar_id_start (int)

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

  • force_loop_single_exit (bool)

  • complete_successors (bool)

  • avoid_vvar_ids (set[int] | None)

__init__(func, blocks_by_addr=None, blocks_by_addr_and_idx=None, graph=None, variable_kb=None, region_identifier=None, reaching_definitions=None, vvar_id_start=0, entry_node_addr=None, scratch=None, force_loop_single_exit=True, complete_successors=False, avoid_vvar_ids=None, **kwargs)[源代码]
参数:
  • vvar_id_start (int)

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

  • force_loop_single_exit (bool)

  • complete_successors (bool)

  • avoid_vvar_ids (set[int] | None)

property blocks_by_addr: dict[int, set[Block]]
property blocks_by_addr_and_idx: dict[tuple[int, int | None], Block]
new_block_addr()[源代码]

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

返回类型:

int

返回:

The block address.

class angr.analyses.decompiler.optimization_passes.optimization_pass.SequenceOptimizationPass(func, seq=None, **kwargs)[源代码]

基类:BaseOptimizationPass

The base class for any sequence node optimization pass.

__init__(func, seq=None, **kwargs)[源代码]
class angr.analyses.decompiler.optimization_passes.optimization_pass.StructuringOptimizationPass(func, prevent_new_gotos=True, strictly_less_gotos=False, recover_structure_fails=True, must_improve_rel_quality=True, max_opt_iters=1, simplify_ail=True, require_gotos=True, readd_labels=False, **kwargs)[源代码]

基类:OptimizationPass

The base class for any optimization pass that requires structuring. Optimization passes that inherit from this class should directly depend on structuring artifacts, such as regions and gotos. Otherwise, they should use OptimizationPass. This is the heaviest (computation time) optimization pass class.

By default this type of optimization should work: - on any architecture - on any platform - during region identification (to have iterative structuring) - only with the SAILR structuring algorithm

ARCHES = None
PLATFORMS = None
STRUCTURING: list[str] | None = ['sailr']
STAGE: OptimizationPassStage = 7
__init__(func, prevent_new_gotos=True, strictly_less_gotos=False, recover_structure_fails=True, must_improve_rel_quality=True, max_opt_iters=1, simplify_ail=True, require_gotos=True, readd_labels=False, **kwargs)[源代码]
analyze()[源代码]

Wrapper for _analyze() that verifies the graph is structurable before and after the optimization.

class angr.analyses.decompiler.optimization_passes.stack_canary_simplifier.StackCanarySimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes stack canary checks from decompilation results.

ARCHES = ['X86', 'AMD64']
PLATFORMS = ['cgc', 'linux']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify stack canaries'
DESCRIPTION = 'Removes stack canary checks from decompilation results.'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.base_ptr_save_simplifier.BasePointerSaveSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes the effects of base pointer stack storage at function invocation and restoring at function return.

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['cgc', 'linux']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify base pointer saving'
DESCRIPTION = 'Removes the effects of base pointer stack storage at function invocation and restoring at function return.'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.div_simplifier.DivSimplifierAILEngine(*args, **kwargs)[源代码]

基类:SimplifierAILEngine

An AIL pass for the div simplifier

class angr.analyses.decompiler.optimization_passes.div_simplifier.DivSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies various division optimizations back to "div".

ARCHES = ['X86', 'AMD64', 'ARMCortexM', 'ARMHF', 'ARMEL']
PLATFORMS = None
STAGE: OptimizationPassStage = 4
NAME = 'Simplify arithmetic division'
DESCRIPTION = 'Simplifies various division optimizations back to "div".'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
exception angr.analyses.decompiler.optimization_passes.ite_expr_converter.NodeFoundNotification[源代码]

基类:Exception

A notification that the target node has been found.

class angr.analyses.decompiler.optimization_passes.ite_expr_converter.BlockLocator(block)[源代码]

基类:RegionWalker

Recursively locate block in a GraphRegion instance.

It might be reasonable to move this class into its own file.

__init__(block)[源代码]
walk_node(region, node)[源代码]
class angr.analyses.decompiler.optimization_passes.ite_expr_converter.ExpressionReplacer(block_addr, target_expr, callback)[源代码]

基类:AILBlockWalker

Replace expressions.

__init__(block_addr, target_expr, callback)[源代码]
class angr.analyses.decompiler.optimization_passes.ite_expr_converter.ITEExprConverter(func, ite_exprs=None, **kwargs)[源代码]

基类:OptimizationPass

Transform specific expressions into If-Then-Else expressions, or tertiary expressions in C when given a single-use expression address. Requires outside analysis to provide the target expressions.

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['windows', 'linux', 'cgc']
STAGE: OptimizationPassStage = 7
NAME = 'Transform single-use expressions that were assigned to in different If-Else branches into ternary expressions'
DESCRIPTION = 'Transform specific expressions into If-Then-Else expressions, or tertiary expressions in C when\n    given a single-use expression address. Requires outside analysis to provide the target expressions.'
__init__(func, ite_exprs=None, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.lowered_switch_simplifier.Case(original_node, node_type, variable_hash, expr, value, target, target_idx, next_addr)[源代码]

基类:object

Describes a case in a switch-case construct.

参数:
  • node_type (str | None)

  • value (int | str)

  • target_idx (int | None)

__init__(original_node, node_type, variable_hash, expr, value, target, target_idx, next_addr)[源代码]
参数:
  • node_type (str | None)

  • value (int | str)

  • target_idx (int | None)

original_node
node_type
variable_hash
expr
value
target
target_idx
next_addr
class angr.analyses.decompiler.optimization_passes.lowered_switch_simplifier.StableVarExprHasher(expr)[源代码]

基类:AILBlockWalkerBase

Obtain a stable hash of an AIL expression with respect to all variables and all operations applied on variables.

参数:

expr (Expression)

__init__(expr)[源代码]
参数:

expr (Expression)

class angr.analyses.decompiler.optimization_passes.lowered_switch_simplifier.LoweredSwitchSimplifier(func, min_distinct_cases=2, **kwargs)[源代码]

基类:StructuringOptimizationPass

This optimization recognizes and reverts switch cases that have been lowered and possibly split into multiple if-else statements. This optimization, discussed in the USENIX 2024 paper SAILR, aims to undo the compiler optimization known as "Switch Lowering", present in both GCC and Clang. An in-depth discussion of this optimization can be found in the paper or in our documentation of the optimization: https://github.com/mahaloz/sailr-eval/issues/14#issue-2232616411

Note, this optimization does not occur in MSVC, which uses a different optimization strategy for switch cases. As a hack for now, we only run this deoptimization on Linux binaries.

PLATFORMS = ['linux']
NAME = 'Convert lowered switch-cases (if-else) to switch-cases'
DESCRIPTION = 'Convert lowered switch-cases (if-else) to switch-cases. Only works when the Phoenix structuring algorithm is in use.'
__init__(func, min_distinct_cases=2, **kwargs)[源代码]
static restore_graph(node, last_stmt, graph, full_graph)[源代码]
参数:
static cases_issubset(cases_0, cases_1)[源代码]

Test if cases_0 is a subset of cases_1.

返回类型:

bool

参数:
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.mod_simplifier.ModSimplifierAILEngine(*args, **kwargs)[源代码]

基类:SimplifierAILEngine

class angr.analyses.decompiler.optimization_passes.mod_simplifier.ModSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies optimized forms of modulo computation back to "mod".

ARCHES = ['X86', 'AMD64', 'ARMCortexM', 'ARMHF', 'ARMEL']
PLATFORMS = ['linux', 'windows']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify optimized mod forms'
DESCRIPTION = 'Simplifies optimized forms of modulo computation back to "mod".'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.engine_base.SimplifierAILState(arch, variables=None)[源代码]

基类:object

The abstract state used in SimplifierAILEngine.

__init__(arch, variables=None)[源代码]
copy()[源代码]
merge(*others)[源代码]
store_variable(old, new)[源代码]
参数:

old (VirtualVariable)

get_variable(old)[源代码]
参数:

old (VirtualVariable)

remove_variable(old)[源代码]
class angr.analyses.decompiler.optimization_passes.engine_base.SimplifierAILEngine(*args, **kwargs)[源代码]

基类:SimEngineLightAIL[SimplifierAILState, Expression, Statement, Block]

Essentially implements a peephole optimization engine for AIL statements (because we do not perform memory or register loads).

class angr.analyses.decompiler.optimization_passes.expr_op_swapper.OuterWalker(desc)[源代码]

基类:SequenceWalker

A sequence walker that finds nodes and invokes expression replacer to replace expressions.

__init__(desc)[源代码]
class angr.analyses.decompiler.optimization_passes.expr_op_swapper.ExpressionReplacer(block_addr, target_expr_predicate, callback)[源代码]

基类:AILBlockWalker

Replace expressions.

__init__(block_addr, target_expr_predicate, callback)[源代码]
class angr.analyses.decompiler.optimization_passes.expr_op_swapper.OpDescriptor(block_addr, stmt_idx, ins_addr, op)[源代码]

基类:object

Describes a specific operator.

参数:
__init__(block_addr, stmt_idx, ins_addr, op)[源代码]
参数:
class angr.analyses.decompiler.optimization_passes.expr_op_swapper.ExprOpSwapper(func, binop_operators=None, **kwargs)[源代码]

基类:SequenceOptimizationPass

Swap operands (and the operator accordingly) in a BinOp expression.

参数:

binop_operators (dict[OpDescriptor, str] | None)

ARCHES = ['X86', 'AMD64', 'ARMEL', 'ARMHF', 'ARMCortexM', 'MIPS32', 'MIPS64']
PLATFORMS = ['windows', 'linux', 'cgc']
STAGE: OptimizationPassStage = 8
NAME = 'Swap operands of expressions as requested'
DESCRIPTION = 'Swap operands (and the operator accordingly) in a BinOp expression.'
__init__(func, binop_operators=None, **kwargs)[源代码]
参数:

binop_operators (dict[OpDescriptor, str] | None)

class angr.analyses.decompiler.optimization_passes.register_save_area_simplifier.RegisterSaveAreaSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Optimizes away register spilling effects, including callee-saved registers.

This optimization runs between SSA-level0 and SSA-level1, which means registers are converted to vvars but stack accesses stay unchanged.

ARCHES = None
PLATFORMS = None
STAGE: OptimizationPassStage = 2
NAME = 'Simplify register save areas'
DESCRIPTION = 'Optimizes away register spilling effects, including callee-saved registers.\n\n    This optimization runs between SSA-level0 and SSA-level1, which means registers are converted to vvars but stack\n    accesses stay unchanged.'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.ret_addr_save_simplifier.RetAddrSaveSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Removes code in function prologues and epilogues for saving and restoring return address registers (ra, lr, etc.), generally seen in non-leaf functions.

ARCHES = ['MIPS32', 'MIPS64']
PLATFORMS = ['linux']
STAGE: OptimizationPassStage = 4
NAME = 'Simplify return address storage'
DESCRIPTION = 'Removes code in function prologues and epilogues for saving and restoring return address registers (ra, lr, etc.),\n    generally seen in non-leaf functions.'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.optimization_passes.x86_gcc_getpc_simplifier.X86GccGetPcSimplifier(func, **kwargs)[源代码]

基类:OptimizationPass

Simplifies __x86.get_pc_thunk calls.

ARCHES = ['X86']
PLATFORMS = ['linux']
STAGE: OptimizationPassStage = 1
NAME = 'Simplify getpc()'
DESCRIPTION = 'Simplifies __x86.get_pc_thunk calls.'
__init__(func, **kwargs)[源代码]
entry_node_addr: tuple[int, int | None]
out_graph: networkx.DiGraph | None
class angr.analyses.decompiler.peephole_optimizations.base.PeepholeOptimizationStmtBase(project, kb, func_addr=None)[源代码]

基类:object

The base class for all peephole optimizations that are applied on AIL statements.

参数:
NAME = 'Peephole Optimization - Statement'
DESCRIPTION = 'Peephole Optimization - Statement'
stmt_classes = None
__init__(project, kb, func_addr=None)[源代码]
参数:
project: Project | None
kb: KnowledgeBase | None
func_addr: int | None
optimize(stmt, stmt_idx=None, block=None, **kwargs)[源代码]
参数:

stmt_idx (int | None)

class angr.analyses.decompiler.peephole_optimizations.base.PeepholeOptimizationMultiStmtBase(project, kb, func_addr=None)[源代码]

基类:object

The base class for all peephole optimizations that are applied on multiple AIL statements at once.

参数:
NAME = 'Peephole Optimization - Multi-statement'
DESCRIPTION = 'Peephole Optimization - Multi-statement'
stmt_classes = None
__init__(project, kb, func_addr=None)[源代码]
参数:
project: Project | None
kb: KnowledgeBase | None
func_addr: int | None
optimize(stmts, stmt_idx=None, block=None, **kwargs)[源代码]
参数:
class angr.analyses.decompiler.peephole_optimizations.base.PeepholeOptimizationExprBase(project, kb, func_addr=None)[源代码]

基类:object

The base class for all peephole optimizations that are applied on AIL expressions.

参数:
NAME = 'Peephole Optimization - Expression'
DESCRIPTION = 'Peephole Optimization - Expression'
expr_classes = None
__init__(project, kb, func_addr=None)[源代码]
参数:
project: Project | None
kb: KnowledgeBase | None
func_addr: int | None
optimize(expr, **kwargs)[源代码]
static find_definition(ail_expr, stmt_idx, block)[源代码]
返回类型:

None

参数:
static is_bool_expr(ail_expr)[源代码]
class angr.analyses.decompiler.region_identifier.RegionIdentifier(func, cond_proc=None, graph=None, update_graph=True, largest_successor_tree_outside_loop=True, force_loop_single_exit=True, complete_successors=False, entry_node_addr=None)[源代码]

基类:Analysis

Identifies regions within a function graph and creates a recursive GraphRegion object. Note, that the analysis may modify the graph in-place. If you want to keep the original graph, set the update_graph parameter to False.

参数:

entry_node_addr (tuple[int, int | None] | None)

__init__(func, cond_proc=None, graph=None, update_graph=True, largest_successor_tree_outside_loop=True, force_loop_single_exit=True, complete_successors=False, entry_node_addr=None)[源代码]
参数:

entry_node_addr (tuple[int, int | None] | None)

static slice_graph(graph, node, frontier, include_frontier=False)[源代码]

Generate a slice of the graph from the head node to the given frontier.

参数:
  • graph (networkx.DiGraph) -- The graph to work on.

  • node -- The starting node in the graph.

  • frontier -- A list of frontier nodes.

  • include_frontier (bool) -- Whether the frontier nodes are included in the slice or not.

返回:

A subgraph.

返回类型:

networkx.DiGraph

class angr.analyses.decompiler.region_simplifiers.RegionSimplifier(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]

基类:Analysis

Simplifies a given region.

参数:
  • simplify_switches (bool)

  • simplify_ifelse (bool)

__init__(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]
参数:
  • simplify_switches (bool)

  • simplify_ifelse (bool)

class angr.analyses.decompiler.region_simplifiers.cascading_cond_transformer.CascadingConditionTransformer(node)[源代码]

基类:SequenceWalker

Identifies and transforms if { ... } else { if { ... } else { ... } } to if { ... } else if { ... } else if { ... }.

__init__(node)[源代码]
class angr.analyses.decompiler.region_simplifiers.cascading_ifs.CascadingIfsRemover(node)[源代码]

基类:SequenceWalker

Coalesce cascading If constructs. Transforming the following construct:

if (cond_a) {
    if (cond_b) {
        true_body
    } else { }
} else { }

into:

if (cond_a and cond_b) {
    true_body
} else { }
__init__(node)[源代码]
class angr.analyses.decompiler.region_simplifiers.expr_folding.LocationBase[源代码]

基类:object

class angr.analyses.decompiler.region_simplifiers.expr_folding.StatementLocation(block_addr, block_idx, stmt_idx)[源代码]

基类:LocationBase

__init__(block_addr, block_idx, stmt_idx)[源代码]
block_addr
block_idx
stmt_idx
copy()[源代码]
class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionLocation(block_addr, block_idx, stmt_idx, expr_idx)[源代码]

基类:LocationBase

__init__(block_addr, block_idx, stmt_idx, expr_idx)[源代码]
block_addr
block_idx
stmt_idx
expr_idx
statement_location()[源代码]
返回类型:

StatementLocation

class angr.analyses.decompiler.region_simplifiers.expr_folding.ConditionLocation(cond_node_addr, case_idx=None)[源代码]

基类:LocationBase

参数:

case_idx (int | None)

__init__(cond_node_addr, case_idx=None)[源代码]
参数:

case_idx (int | None)

node_addr
case_idx
class angr.analyses.decompiler.region_simplifiers.expr_folding.ConditionalBreakLocation(node_addr)[源代码]

基类:LocationBase

__init__(node_addr)[源代码]
node_addr
class angr.analyses.decompiler.region_simplifiers.expr_folding.MultiStatementExpressionAssignmentFinder(stmt_handler)[源代码]

基类:AILBlockWalker

Process statements in MultiStatementExpression objects and find assignments.

__init__(stmt_handler)[源代码]
class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionUseFinder[源代码]

基类:AILBlockWalker

Find where each variable is used.

Additionally, determine if the expression being walked has load expressions inside. Such expressions can only be safely folded if there are no Store statements between the expression defining location and its use sites. For example, we can only safely fold variable assignments that use Load() when there are no Store()s between the assignment and its use site. Otherwise, the loaded expression may get updated later by a Store() statement.

Here is a real AIL block:

v16 = ((int)v23->field_5) + 1 & 255;
v23->field_5 = ((char)(((int)v23->field_5) + 1 & 255));
v13 = printf("Recieved packet %d for connection with %d\n", v16, a0 & 255);

In this case, folding v16 into the last printf() expression would be incorrect, since v23->field_5 is updated by the second statement.

__init__()[源代码]
uses: defaultdict[SimVariable, set[tuple[Expression, ExpressionLocation | None]]]
has_load
class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionCounter(node, variable_manager)[源代码]

基类:SequenceWalker

Find all expressions that are assigned once and only used once.

__init__(node, variable_manager)[源代码]
class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionReplacer(assignments, uses, variable_manager)[源代码]

基类:AILBlockWalker

参数:
__init__(assignments, uses, variable_manager)[源代码]
参数:
class angr.analyses.decompiler.region_simplifiers.expr_folding.ExpressionFolder(assignments, uses, node, variable_manager)[源代码]

基类:SequenceWalker

参数:
__init__(assignments, uses, node, variable_manager)[源代码]
参数:
class angr.analyses.decompiler.region_simplifiers.expr_folding.StoreStatementFinder(node, intervals)[源代码]

基类:SequenceWalker

Determine if there are any Store statements between two given statements.

This class overrides _handle_Sequence() and _handle_MultiNode() to ensure they traverse nodes from top to bottom.

参数:

intervals (Iterable[tuple[StatementLocation, LocationBase]])

__init__(node, intervals)[源代码]
参数:

intervals (Iterable[tuple[StatementLocation, LocationBase]])

has_store(start, end)[源代码]
返回类型:

bool

参数:
class angr.analyses.decompiler.region_simplifiers.goto.GotoSimplifier(node, function=None, kb=None)[源代码]

基类:SequenceWalker

Remove unnecessary Jump statements. This simplifier also has the side effect of detecting Gotos that can't be reduced in the structuring and eventual decompilation output. Because of this, when this analysis is run, gotos in decompilation will be detected and stored in the kb.gotos. See the _handle_irreducible_goto function below.

TODO: Move the recording of Gotos outside this function

__init__(node, function=None, kb=None)[源代码]
class angr.analyses.decompiler.region_simplifiers.if_.IfSimplifier(node)[源代码]

基类:SequenceWalker

Remove unnecessary jump or conditional jump statements if they jump to the successor right afterwards.

__init__(node)[源代码]
class angr.analyses.decompiler.region_simplifiers.ifelse.IfElseFlattener(node, functions)[源代码]

基类:SequenceWalker

Remove unnecessary else branches and make the else node a direct successor of the previous If node if the If node always returns.

__init__(node, functions)[源代码]
class angr.analyses.decompiler.region_simplifiers.loop.LoopSimplifier(node, functions)[源代码]

基类:SequenceWalker

Simplifies loops.

__init__(node, functions)[源代码]
class angr.analyses.decompiler.region_simplifiers.node_address_finder.NodeAddressFinder(node)[源代码]

基类:SequenceWalker

Walk the entire node and collect all addresses of nodes.

__init__(node)[源代码]
class angr.analyses.decompiler.region_simplifiers.region_simplifier.RegionSimplifier(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]

基类:Analysis

Simplifies a given region.

参数:
  • simplify_switches (bool)

  • simplify_ifelse (bool)

__init__(func, region, variable_kb=None, simplify_switches=True, simplify_ifelse=True)[源代码]
参数:
  • simplify_switches (bool)

  • simplify_ifelse (bool)

class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.CmpOp(value)[源代码]

基类:Enum

All supported comparison operators.

LT = 0
GT = 1
EQ = 2
NE = 3
class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.ConditionalRegion(variable, op, value, node, parent=None)[源代码]

基类:object

Describes a conditional region.

参数:
__init__(variable, op, value, node, parent=None)[源代码]
参数:
variable
op
value
node
parent
class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.SwitchCaseRegion(variable, node, parent=None)[源代码]

基类:object

Describes an already-recovered switch region.

参数:

node (SwitchCaseNode)

__init__(variable, node, parent=None)[源代码]
参数:

node (SwitchCaseNode)

variable
node
parent
class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.SwitchClusterFinder(node)[源代码]

基类:SequenceWalker

Find comparisons and switches in order to identify switch clusters.

__init__(node)[源代码]
class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.SwitchClusterReplacer(region, to_replace, replace_with)[源代码]

基类:SequenceWalker

Replace an identified switch cluster with a newly created SwitchCase node.

__init__(region, to_replace, replace_with)[源代码]
angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.is_simple_jump_node(node, case_addrs, targets=None)[源代码]
返回类型:

bool

参数:

targets (set[int] | None)

angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.filter_cond_regions(cond_regions, case_addrs)[源代码]

Remove all conditional regions that cannot be merged into switch(es).

返回类型:

list[ConditionalRegion]

参数:
angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.update_switch_case_list(cases, old_case_id, new_case_id)[源代码]

Update cases in-place. Make new_case_id directly jump to old_case_id.

返回类型:

None

参数:
angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.simplify_switch_clusters(region, var2condnodes, var2switches)[源代码]

Identify switch clusters and simplify each of them.

参数:
  • region -- The region to simplify.

  • var2condnodes (dict[Any, list[ConditionalRegion]]) -- A dict that stores the mapping from (potential) switch variables to conditional regions.

  • var2switches (dict[Any, list[SwitchCaseRegion]]) -- A dict that stores the mapping from switch variables to switch-case regions.

返回:

None

angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.simplify_lowered_switches(region, var2condnodes, functions)[源代码]

Identify a lowered switch and simplify it into a switch-case if possible.

参数:
返回:

None

angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.simplify_lowered_switches_core(region, var, condnodes, functions)[源代码]
返回类型:

bool

参数:

region (SequenceNode)

class angr.analyses.decompiler.region_simplifiers.switch_cluster_simplifier.FindFirstNodeInSet(node_set)[源代码]

基类:SequenceWalker

Find the first node out of a set of node appearing in a SequenceNode (and its tree).

参数:

node_set (set[BaseNode])

__init__(node_set)[源代码]
参数:

node_set (set[BaseNode])

class angr.analyses.decompiler.region_simplifiers.switch_expr_simplifier.SwitchExpressionSimplifier(node)[源代码]

基类:SequenceWalker

Identifies switch expressions that adds or minuses a constant, removes the constant from the switch expression, and adjust all case expressions accordingly.

__init__(node)[源代码]
class angr.analyses.decompiler.region_walker.RegionWalker[源代码]

基类:object

A simple traverser class that walks GraphRegion instances.

__init__()[源代码]
walk(region)[源代码]
参数:

region (GraphRegion)

walk_node(region, node)[源代码]
class angr.analyses.decompiler.redundant_label_remover.RedundantLabelRemover(node, jump_targets)[源代码]

基类:object

Remove redundant labels.

This optimization pass contains two separate passes. The first pass (self._walker0) finds all redundant labels (e.g., two or more labels for the same location) and records the replacement label for redundant labels in self._new_jump_target. The second pass (self._walker1) removes all redundant labels that (a) are not referenced anywhere (determined by jump_targets), or (b) are deemed replaceable by the first pass.

参数:

jump_targets (set[tuple[int, int | None]])

__init__(node, jump_targets)[源代码]
参数:

jump_targets (set[tuple[int, int | None]])

class angr.analyses.decompiler.sequence_walker.SequenceWalker(handlers=None, exception_on_unsupported=False, update_seqnode_in_place=True, force_forward_scan=False)[源代码]

基类:object

Walks a SequenceNode and all its nodes, recursively.

参数:

force_forward_scan (bool)

__init__(handlers=None, exception_on_unsupported=False, update_seqnode_in_place=True, force_forward_scan=False)[源代码]
参数:

force_forward_scan (bool)

walk(sequence)[源代码]
class angr.analyses.decompiler.structured_codegen.BaseStructuredCodeGenerator(flavor=None)[源代码]

基类:object

__init__(flavor=None)[源代码]
reapply_options(options)[源代码]
regenerate_text()[源代码]
返回类型:

None

reload_variable_types()[源代码]
返回类型:

None

class angr.analyses.decompiler.structured_codegen.CStructuredCodeGenerator(func, sequence, indent=0, cfg=None, variable_kb=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False)[源代码]

基类:BaseStructuredCodeGenerator, Analysis

参数:
__init__(func, sequence, indent=0, cfg=None, variable_kb=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False)[源代码]
参数:
reapply_options(options)[源代码]
cleanup()[源代码]

Remove existing rendering results.

regenerate_text()[源代码]

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

返回类型:

None

RENDER_TYPE

tuple[str, PositionMapping, PositionMapping, InstructionMapping, dict[Any, set[Any]]] 的别名

render_text(cfunc)[源代码]
返回类型:

RENDER_TYPE

参数:

cfunc (CFunction)

reload_variable_types()[源代码]
返回类型:

None

default_simtype_from_bits(n, signed=True)[源代码]
返回类型:

SimType

参数:
class angr.analyses.decompiler.structured_codegen.CStructuredCodeWalker[源代码]

基类:object

handle(obj)[源代码]
handle_default(obj)[源代码]
handle_CFunction(obj)[源代码]
handle_CStatements(obj)[源代码]
handle_CWhileLoop(obj)[源代码]
handle_CDoWhileLoop(obj)[源代码]
handle_CForLoop(obj)[源代码]
handle_CIfElse(obj)[源代码]
handle_CIfBreak(obj)[源代码]
handle_CSwitchCase(obj)[源代码]
handle_CAssignment(obj)[源代码]
handle_CFunctionCall(obj)[源代码]
handle_CReturn(obj)[源代码]
handle_CGoto(obj)[源代码]
handle_CIndexedVariable(obj)[源代码]
handle_CVariableField(obj)[源代码]
handle_CUnaryOp(obj)[源代码]
handle_CBinaryOp(obj)[源代码]
handle_CTypeCast(obj)[源代码]
handle_CITE(obj)[源代码]
class angr.analyses.decompiler.structured_codegen.DummyStructuredCodeGenerator(flavor, expr_comments=None, stmt_comments=None, configuration=None, const_formats=None)[源代码]

基类:BaseStructuredCodeGenerator

A dummy structured code generator that only stores user-specified information.

参数:

flavor (str)

__init__(flavor, expr_comments=None, stmt_comments=None, configuration=None, const_formats=None)[源代码]
参数:

flavor (str)

class angr.analyses.decompiler.structured_codegen.ImportSourceCode(function, flavor='source', source_root=None, encoding='utf-8')[源代码]

基类:BaseStructuredCodeGenerator, Analysis

__init__(function, flavor='source', source_root=None, encoding='utf-8')[源代码]
regenerate_text()[源代码]
class angr.analyses.decompiler.structured_codegen.InstructionMapping[源代码]

基类:object

__init__()[源代码]
items()[源代码]
add_mapping(ins_addr, posmap_pos)[源代码]
get_nearest_pos(ins_addr)[源代码]
返回类型:

int | None

参数:

ins_addr (int)

class angr.analyses.decompiler.structured_codegen.InstructionMappingElement(ins_addr, posmap_pos)[源代码]

基类:object

__init__(ins_addr, posmap_pos)[源代码]
ins_addr: int
posmap_pos: int
class angr.analyses.decompiler.structured_codegen.PositionMapping[源代码]

基类:object

DUPLICATION_CHECK = True
__init__()[源代码]
items()[源代码]
add_mapping(start_pos, length, obj)[源代码]
get_node(pos)[源代码]
参数:

pos (int)

get_element(pos)[源代码]
返回类型:

PositionMappingElement | None

参数:

pos (int)

class angr.analyses.decompiler.structured_codegen.PositionMappingElement(start, length, obj)[源代码]

基类:object

__init__(start, length, obj)[源代码]
start: int
length: int
obj
class angr.analyses.decompiler.structured_codegen.base.PositionMappingElement(start, length, obj)[源代码]

基类:object

参数:
__init__(start, length, obj)[源代码]
start: int
length: int
obj
class angr.analyses.decompiler.structured_codegen.base.PositionMapping[源代码]

基类:object

DUPLICATION_CHECK = True
__init__()[源代码]
items()[源代码]
add_mapping(start_pos, length, obj)[源代码]
get_node(pos)[源代码]
参数:

pos (int)

get_element(pos)[源代码]
返回类型:

PositionMappingElement | None

参数:

pos (int)

class angr.analyses.decompiler.structured_codegen.base.InstructionMappingElement(ins_addr, posmap_pos)[源代码]

基类:object

参数:
  • ins_addr (int)

  • posmap_pos (int)

__init__(ins_addr, posmap_pos)[源代码]
ins_addr: int
posmap_pos: int
class angr.analyses.decompiler.structured_codegen.base.InstructionMapping[源代码]

基类:object

__init__()[源代码]
items()[源代码]
add_mapping(ins_addr, posmap_pos)[源代码]
get_nearest_pos(ins_addr)[源代码]
返回类型:

int | None

参数:

ins_addr (int)

class angr.analyses.decompiler.structured_codegen.base.BaseStructuredCodeGenerator(flavor=None)[源代码]

基类:object

__init__(flavor=None)[源代码]
reapply_options(options)[源代码]
regenerate_text()[源代码]
返回类型:

None

reload_variable_types()[源代码]
返回类型:

None

angr.analyses.decompiler.structured_codegen.c.unpack_typeref(ty)[源代码]
angr.analyses.decompiler.structured_codegen.c.unpack_pointer(ty)[源代码]
返回类型:

SimType | None

angr.analyses.decompiler.structured_codegen.c.unpack_array(ty)[源代码]
返回类型:

SimType | None

angr.analyses.decompiler.structured_codegen.c.squash_array_reference(ty)[源代码]
angr.analyses.decompiler.structured_codegen.c.qualifies_for_simple_cast(ty1, ty2)[源代码]
angr.analyses.decompiler.structured_codegen.c.qualifies_for_implicit_cast(ty1, ty2)[源代码]
angr.analyses.decompiler.structured_codegen.c.extract_terms(expr)[源代码]
返回类型:

tuple[int, list[tuple[int, CExpression]]]

参数:

expr (CExpression)

angr.analyses.decompiler.structured_codegen.c.is_machine_word_size_type(type_, arch)[源代码]
返回类型:

bool

参数:
angr.analyses.decompiler.structured_codegen.c.guess_value_type(value, project)[源代码]
返回类型:

SimType | None

参数:
angr.analyses.decompiler.structured_codegen.c.type_to_c_repr_chunks(ty, name=None, name_type=None, full=False, indent_str='')[源代码]

Helper generator function to turn a SimType into generated tuples of (C-string, AST node).

参数:

ty (SimType)

class angr.analyses.decompiler.structured_codegen.c.CConstruct(codegen)[源代码]

基类:object

Represents a program construct in C. Acts as the base class for all other representation constructions.

__init__(codegen)[源代码]
codegen: CStructuredCodeGenerator
c_repr(indent=0, pos_to_node=None, pos_to_addr=None, addr_to_pos=None)[源代码]

Creates the C representation of the code and displays it by constructing a large string. This function is called by each program function that needs to be decompiled. The map_pos_to_node and map_pos_to_addr act as position maps for the location of each variable and statement to be tracked for later GUI operations. The map_pos_to_addr also contains expressions that are nested inside of statements.

c_repr_chunks(indent=0, asexpr=False)[源代码]
static indent_str(indent=0)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CFunction(addr, name, functy, arg_list, statements, variables_in_use, variable_manager, demangled_name=None, show_demangled_name=True, omit_header=False, **kwargs)[源代码]

基类:CConstruct

Represents a function in C.

参数:
__init__(addr, name, functy, arg_list, statements, variables_in_use, variable_manager, demangled_name=None, show_demangled_name=True, omit_header=False, **kwargs)[源代码]
参数:
addr
name
functy
arg_list
statements
variables_in_use
variable_manager: VariableManagerInternal
demangled_name
unified_local_vars: dict[SimVariable, set[tuple[CVariable, SimType]]]
show_demangled_name
omit_header
get_unified_local_vars()[源代码]
返回类型:

dict[SimVariable, set[tuple[CVariable, SimType]]]

variable_list_repr_chunks(indent=0)[源代码]
c_repr_chunks(indent=0, asexpr=False)[源代码]
headerless_c_repr_chunks(indent=0)[源代码]
full_c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CStatement(codegen)[源代码]

基类:CConstruct

Represents a statement in C.

参数:

codegen (CStructuredCodeGenerator)

class angr.analyses.decompiler.structured_codegen.c.CExpression(collapsed=False, **kwargs)[源代码]

基类:CConstruct

Base class for C expressions.

__init__(collapsed=False, **kwargs)[源代码]
collapsed
property type
set_type(v)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CStatements(statements, addr=None, **kwargs)[源代码]

基类:CStatement

Represents a sequence of statements in C.

__init__(statements, addr=None, **kwargs)[源代码]
statements
addr
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CAILBlock(block, **kwargs)[源代码]

基类:CStatement

Represents a block of AIL statements.

__init__(block, **kwargs)[源代码]
block
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CLoop(codegen)[源代码]

基类:CStatement

Represents a loop in C.

参数:

codegen (CStructuredCodeGenerator)

class angr.analyses.decompiler.structured_codegen.c.CWhileLoop(condition, body, tags=None, **kwargs)[源代码]

基类:CLoop

Represents a while loop in C.

__init__(condition, body, tags=None, **kwargs)[源代码]
condition
body
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CDoWhileLoop(condition, body, tags=None, **kwargs)[源代码]

基类:CLoop

Represents a do-while loop in C.

__init__(condition, body, tags=None, **kwargs)[源代码]
condition
body
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CForLoop(initializer, condition, iterator, body, tags=None, **kwargs)[源代码]

基类:CStatement

Represents a for-loop in C.

__init__(initializer, condition, iterator, body, tags=None, **kwargs)[源代码]
initializer
condition
iterator
body
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CIfElse(condition_and_nodes, else_node=None, simplify_else_scope=False, cstyle_ifs=True, tags=None, **kwargs)[源代码]

基类:CStatement

Represents an if-else construct in C.

参数:

condition_and_nodes (list[tuple[CExpression, CStatement | None]])

__init__(condition_and_nodes, else_node=None, simplify_else_scope=False, cstyle_ifs=True, tags=None, **kwargs)[源代码]
参数:

condition_and_nodes (list[tuple[CExpression, CStatement | None]])

condition_and_nodes
else_node
simplify_else_scope
cstyle_ifs
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CIfBreak(condition, cstyle_ifs=True, tags=None, **kwargs)[源代码]

基类:CStatement

Represents an if-break statement in C.

__init__(condition, cstyle_ifs=True, tags=None, **kwargs)[源代码]
condition
cstyle_ifs
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CBreak(tags=None, **kwargs)[源代码]

基类:CStatement

Represents a break statement in C.

__init__(tags=None, **kwargs)[源代码]
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CContinue(tags=None, **kwargs)[源代码]

基类:CStatement

Represents a continue statement in C.

__init__(tags=None, **kwargs)[源代码]
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CSwitchCase(switch, cases, default, tags=None, **kwargs)[源代码]

基类:CStatement

Represents a switch-case statement in C.

__init__(switch, cases, default, tags=None, **kwargs)[源代码]
switch
cases: list[tuple[int | tuple[int], CStatements]]
default
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CIncompleteSwitchCase(head, cases, tags=None, **kwargs)[源代码]

基类:CStatement

Represents an incomplete switch-case construct; this only appear in the decompilation output when switch-case structuring fails (for whatever reason).

__init__(head, cases, tags=None, **kwargs)[源代码]
head
cases: list[tuple[int, CStatements]]
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CAssignment(lhs, rhs, tags=None, **kwargs)[源代码]

基类:CStatement

a = b

__init__(lhs, rhs, tags=None, **kwargs)[源代码]
lhs
rhs
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CFunctionCall(callee_target, callee_func, args, returning=True, ret_expr=None, tags=None, is_expr=False, show_demangled_name=True, show_disambiguated_name=True, **kwargs)[源代码]

基类:CStatement, CExpression

func(arg0, arg1)

变量:
  • callee_func (Function) -- The function getting called.

  • is_expr -- True if the return value of the function is written to ret_expr; Essentially, ret_expr = call().

参数:
  • is_expr (bool)

  • show_disambiguated_name (bool)

__init__(callee_target, callee_func, args, returning=True, ret_expr=None, tags=None, is_expr=False, show_demangled_name=True, show_disambiguated_name=True, **kwargs)[源代码]
参数:
  • is_expr (bool)

  • show_disambiguated_name (bool)

callee_target
callee_func: Function | None
args
returning
ret_expr
tags
is_expr
show_demangled_name
show_disambiguated_name
property prototype: SimTypeFunction | None
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
参数:
  • indent -- Number of whitespace indentation characters.

  • asexpr (bool) -- True if this call is used as an expression (which means we will skip the generation of semicolons and newlines at the end of the call).

class angr.analyses.decompiler.structured_codegen.c.CReturn(retval, tags=None, **kwargs)[源代码]

基类:CStatement

__init__(retval, tags=None, **kwargs)[源代码]
retval
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CGoto(target, target_idx, tags=None, **kwargs)[源代码]

基类:CStatement

__init__(target, target_idx, tags=None, **kwargs)[源代码]
target: int | CExpression
target_idx
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CUnsupportedStatement(stmt, **kwargs)[源代码]

基类:CStatement

A wrapper for unsupported AIL statement.

__init__(stmt, **kwargs)[源代码]
stmt
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CDirtyStatement(dirty, **kwargs)[源代码]

基类:CExpression

参数:

dirty (CDirtyExpression)

__init__(dirty, **kwargs)[源代码]
参数:

dirty (CDirtyExpression)

dirty
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CLabel(name, ins_addr, block_idx, tags=None, **kwargs)[源代码]

基类:CStatement

Represents a label in C code.

参数:
  • name (str)

  • ins_addr (int)

  • block_idx (int | None)

__init__(name, ins_addr, block_idx, tags=None, **kwargs)[源代码]
参数:
  • name (str)

  • ins_addr (int)

  • block_idx (int | None)

name
ins_addr
block_idx
tags
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CStructField(struct_type, offset, field, tags=None, **kwargs)[源代码]

基类:CExpression

参数:

struct_type (SimStruct)

__init__(struct_type, offset, field, tags=None, **kwargs)[源代码]
参数:

struct_type (SimStruct)

struct_type
offset
field
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CFakeVariable(name, ty, tags=None, **kwargs)[源代码]

基类:CExpression

An uninterpreted name to display in the decompilation output. Pretty much always represents an error?

参数:
__init__(name, ty, tags=None, **kwargs)[源代码]
参数:
name
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CVariable(variable, unified_variable=None, variable_type=None, tags=None, vvar_id=None, **kwargs)[源代码]

基类:CExpression

CVariable represents access to a variable with the specified type (variable_type).

variable must be a SimVariable.

参数:

variable (SimVariable)

__init__(variable, unified_variable=None, variable_type=None, tags=None, vvar_id=None, **kwargs)[源代码]
参数:

variable (SimVariable)

variable: SimVariable
unified_variable: SimVariable | None
variable_type: SimType
tags
vvar_id
property type
property name
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CIndexedVariable(variable, index, variable_type=None, tags=None, **kwargs)[源代码]

基类:CExpression

Represent a variable (an array) that is indexed.

参数:
__init__(variable, index, variable_type=None, tags=None, **kwargs)[源代码]
参数:
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
collapsed
class angr.analyses.decompiler.structured_codegen.c.CVariableField(variable, field, var_is_ptr=False, tags=None, **kwargs)[源代码]

基类:CExpression

Represent a field of a variable.

参数:
__init__(variable, field, var_is_ptr=False, tags=None, **kwargs)[源代码]
参数:
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
collapsed
class angr.analyses.decompiler.structured_codegen.c.CUnaryOp(op, operand, tags=None, **kwargs)[源代码]

基类:CExpression

Unary operations.

参数:

operand (CExpression)

__init__(op, operand, tags=None, **kwargs)[源代码]
参数:

operand (CExpression)

op
operand
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CBinaryOp(op, lhs, rhs, tags=None, **kwargs)[源代码]

基类:CExpression

Binary operations.

参数:

tags (dict | None)

__init__(op, lhs, rhs, tags=None, **kwargs)[源代码]
参数:

tags (dict | None)

op
lhs
rhs
tags
common_type
static compute_common_type(op, lhs_ty, rhs_ty)[源代码]
返回类型:

SimType

参数:
property type
property op_precedence
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CTypeCast(src_type, dst_type, expr, tags=None, **kwargs)[源代码]

基类:CExpression

参数:
__init__(src_type, dst_type, expr, tags=None, **kwargs)[源代码]
参数:
src_type
dst_type
expr
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CConstant(value, type_, reference_values=None, tags=None, **kwargs)[源代码]

基类:CExpression

参数:
__init__(value, type_, reference_values=None, tags=None, **kwargs)[源代码]
参数:
value
reference_values
tags
property fmt
property fmt_hex
property fmt_neg
property fmt_char
property fmt_float
property fmt_double
property type
static str_to_c_str(_str, prefix='')[源代码]
参数:

prefix (str)

c_repr_chunks(indent=0, asexpr=False)[源代码]
fmt_int(value)[源代码]

Format an integer using the format setup of the current node.

参数:

value (int) -- The integer value to format.

返回类型:

str

返回:

The formatted string.

class angr.analyses.decompiler.structured_codegen.c.CRegister(reg, tags=None, **kwargs)[源代码]

基类:CExpression

__init__(reg, tags=None, **kwargs)[源代码]
reg
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CITE(cond, iftrue, iffalse, tags=None, **kwargs)[源代码]

基类:CExpression

__init__(cond, iftrue, iffalse, tags=None, **kwargs)[源代码]
cond
iftrue
iffalse
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CMultiStatementExpression(stmts, expr, tags=None, **kwargs)[源代码]

基类:CExpression

(stmt0, stmt1, stmt2, expr)

参数:
__init__(stmts, expr, tags=None, **kwargs)[源代码]
参数:
stmts
expr
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CVEXCCallExpression(callee, operands, tags=None, **kwargs)[源代码]

基类:CExpression

ccall_name(arg0, arg1, ...)

参数:
__init__(callee, operands, tags=None, **kwargs)[源代码]
参数:
callee
operands
tags
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CDirtyExpression(dirty, **kwargs)[源代码]

基类:CExpression

Ideally all dirty expressions should be handled and converted to proper conversions during conversion from VEX to AIL. Eventually this class should not be used at all.

__init__(dirty, **kwargs)[源代码]
dirty
property type
c_repr_chunks(indent=0, asexpr=False)[源代码]
class angr.analyses.decompiler.structured_codegen.c.CClosingObject(opening_symbol)[源代码]

基类:object

A class to represent all objects that can be closed by it's correspodning character. Examples: (), {}, []

__init__(opening_symbol)[源代码]
opening_symbol
class angr.analyses.decompiler.structured_codegen.c.CArrayTypeLength(text)[源代码]

基类:object

A class to represent the type information of fixed-size array lengths. Examples: In "char foo[20]", this would be the "[20]".

__init__(text)[源代码]
text
class angr.analyses.decompiler.structured_codegen.c.CStructFieldNameDef(name)[源代码]

基类:object

A class to represent the name of a defined field in a struct. Needed because it's not a CVariable or a CStructField (because CStructField is the access of a CStructField). Example: In "struct foo { int bar; }, this would be "bar".

__init__(name)[源代码]
name
class angr.analyses.decompiler.structured_codegen.c.CStructuredCodeGenerator(func, sequence, indent=0, cfg=None, variable_kb=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False)[源代码]

基类:BaseStructuredCodeGenerator, Analysis

参数:
__init__(func, sequence, indent=0, cfg=None, variable_kb=None, func_args=None, binop_depth_cutoff=16, show_casts=True, braces_on_own_lines=True, use_compound_assignments=True, show_local_types=True, comment_gotos=False, cstyle_null_cmp=True, flavor=None, stmt_comments=None, expr_comments=None, show_externs=True, externs=None, const_formats=None, show_demangled_name=True, show_disambiguated_name=True, ail_graph=None, simplify_else_scope=True, cstyle_ifs=True, omit_func_header=False, display_block_addrs=False, display_vvar_ids=False)[源代码]
参数:
reapply_options(options)[源代码]
cleanup()[源代码]

Remove existing rendering results.

regenerate_text()[源代码]

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

返回类型:

None

RENDER_TYPE

tuple[str, PositionMapping, PositionMapping, InstructionMapping, dict[Any, set[Any]]] 的别名

render_text(cfunc)[源代码]
返回类型:

RENDER_TYPE

参数:

cfunc (CFunction)

reload_variable_types()[源代码]
返回类型:

None

default_simtype_from_bits(n, signed=True)[源代码]
返回类型:

SimType

参数:
class angr.analyses.decompiler.structured_codegen.c.CStructuredCodeWalker[源代码]

基类:object

handle(obj)[源代码]
handle_default(obj)[源代码]
handle_CFunction(obj)[源代码]
handle_CStatements(obj)[源代码]
handle_CWhileLoop(obj)[源代码]
handle_CDoWhileLoop(obj)[源代码]
handle_CForLoop(obj)[源代码]
handle_CIfElse(obj)[源代码]
handle_CIfBreak(obj)[源代码]
handle_CSwitchCase(obj)[源代码]
handle_CAssignment(obj)[源代码]
handle_CFunctionCall(obj)[源代码]
handle_CReturn(obj)[源代码]
handle_CGoto(obj)[源代码]
handle_CIndexedVariable(obj)[源代码]
handle_CVariableField(obj)[源代码]
handle_CUnaryOp(obj)[源代码]
handle_CBinaryOp(obj)[源代码]
handle_CTypeCast(obj)[源代码]
handle_CITE(obj)[源代码]
class angr.analyses.decompiler.structured_codegen.c.MakeTypecastsImplicit[源代码]

基类:CStructuredCodeWalker

classmethod collapse(dst_ty, child)[源代码]
返回类型:

CExpression

参数:
handle_CAssignment(obj)[源代码]
handle_CFunctionCall(obj)[源代码]
参数:

obj (CFunctionCall)

handle_CReturn(obj)[源代码]
参数:

obj (CReturn)

handle_CBinaryOp(obj)[源代码]
参数:

obj (CBinaryOp)

handle_CTypeCast(obj)[源代码]
参数:

obj (CTypeCast)

class angr.analyses.decompiler.structured_codegen.c.FieldReferenceCleanup[源代码]

基类:CStructuredCodeWalker

handle_CTypeCast(obj)[源代码]
class angr.analyses.decompiler.structured_codegen.c.PointerArithmeticFixer[源代码]

基类:CStructuredCodeWalker

Before calling this fixer class, pointer arithmetics are purely integer-based and ignoring the pointer type.

For example, in the following case:

struct A* a_ptr; // assume struct A is 24 bytes in size a_ptr = a_ptr + 24;

It means adding 24 to the address of a_ptr, without considering the size of struct A. This fixer class will make pointer arithmetics aware of the pointer type. In this case, the fixer class will convert the code to a_ptr = a_ptr + 1.

handle_CBinaryOp(obj)[源代码]
angr.analyses.decompiler.structured_codegen.c.StructuredCodeGenerator

CStructuredCodeGenerator 的别名

class angr.analyses.decompiler.structured_codegen.dwarf_import.ImportedLine(addr)[源代码]

基类:object

__init__(addr)[源代码]
class angr.analyses.decompiler.structured_codegen.dwarf_import.ImportSourceCode(function, flavor='source', source_root=None, encoding='utf-8')[源代码]

基类:BaseStructuredCodeGenerator, Analysis

__init__(function, flavor='source', source_root=None, encoding='utf-8')[源代码]
regenerate_text()[源代码]
class angr.analyses.decompiler.structured_codegen.dummy.DummyStructuredCodeGenerator(flavor, expr_comments=None, stmt_comments=None, configuration=None, const_formats=None)[源代码]

基类:BaseStructuredCodeGenerator

A dummy structured code generator that only stores user-specified information.

参数:

flavor (str)

__init__(flavor, expr_comments=None, stmt_comments=None, configuration=None, const_formats=None)[源代码]
参数:

flavor (str)

angr.analyses.decompiler.utils.remove_last_statement(node)[源代码]
angr.analyses.decompiler.utils.remove_last_statements(node)[源代码]
返回类型:

bool

angr.analyses.decompiler.utils.append_statement(node, stmt)[源代码]
angr.analyses.decompiler.utils.replace_last_statement(node, old_stmt, new_stmt)[源代码]
angr.analyses.decompiler.utils.extract_jump_targets(stmt)[源代码]

Extract concrete goto targets from a Jump or a ConditionalJump statement.

参数:

stmt -- The statement to analyze.

返回:

A list of known concrete jump targets.

返回类型:

list

angr.analyses.decompiler.utils.switch_extract_cmp_bounds(last_stmt)[源代码]

Check the last statement of the switch-case header node, and extract lower+upper bounds for the comparison.

参数:

last_stmt (ConditionalJump) -- The last statement of the switch-case header node.

返回类型:

tuple[Any, int, int] | None

返回:

A tuple of (comparison expression, lower bound, upper bound), or None

angr.analyses.decompiler.utils.get_ast_subexprs(claripy_ast)[源代码]
angr.analyses.decompiler.utils.insert_node(parent, insert_location, node, node_idx, label=None)[源代码]
参数:
angr.analyses.decompiler.utils.to_ail_supergraph(transition_graph, allow_fake=False)[源代码]

Takes an AIL graph and converts it into a AIL graph that treats calls and redundant jumps as parts of a bigger block instead of transitions. Calls to returning functions do not terminate basic blocks.

Based on region_identifier super_graph

返回类型:

DiGraph

返回:

A converted super transition graph

参数:

transition_graph (DiGraph)

angr.analyses.decompiler.utils.is_empty_node(node)[源代码]
返回类型:

bool

angr.analyses.decompiler.utils.is_empty_or_label_only_node(node)[源代码]
返回类型:

bool

angr.analyses.decompiler.utils.has_nonlabel_statements(block)[源代码]
返回类型:

bool

参数:

block (Block)

angr.analyses.decompiler.utils.has_nonlabel_nonphi_statements(block)[源代码]
返回类型:

bool

参数:

block (Block)

angr.analyses.decompiler.utils.first_nonlabel_statement(block)[源代码]
返回类型:

Statement | None

参数:

block (Block | MultiNode)

angr.analyses.decompiler.utils.first_nonlabel_statement_id(block)[源代码]
返回类型:

int | None

参数:

block (Block)

angr.analyses.decompiler.utils.first_nonlabel_nonphi_statement(block)[源代码]
返回类型:

Statement | None

参数:

block (Block | MultiNode)

angr.analyses.decompiler.utils.last_nonlabel_statement(block)[源代码]
返回类型:

Statement | None

参数:

block (Block)

angr.analyses.decompiler.utils.first_nonlabel_node(seq)[源代码]
返回类型:

BaseNode | Block | None

参数:

seq (SequenceNode)

angr.analyses.decompiler.utils.first_nonlabel_nonphi_node(seq)[源代码]
返回类型:

BaseNode | Block | None

参数:

seq (SequenceNode)

angr.analyses.decompiler.utils.remove_labels(graph)[源代码]
参数:

graph (DiGraph)

angr.analyses.decompiler.utils.add_labels(graph)[源代码]
参数:

graph (DiGraph)

angr.analyses.decompiler.utils.update_labels(graph)[源代码]

A utility function to recreate the labels for every node in an AIL graph. This useful when you are working with a graph where only _some_ of the nodes have labels.

参数:

graph (DiGraph)

angr.analyses.decompiler.utils.structured_node_is_simple_return(node, graph, use_packed_successors=False)[源代码]
返回类型:

bool

参数:

Will check if a "simple return" is contained within the node a simple returns looks like this: if (cond) {

// simple return ... return 0;

}

Returns true on any block ending in linear statements and a return.

angr.analyses.decompiler.utils.is_statement_terminating(stmt, functions)[源代码]
返回类型:

bool

参数:

stmt (Statement)

angr.analyses.decompiler.utils.peephole_optimize_exprs(block, expr_opts)[源代码]
angr.analyses.decompiler.utils.peephole_optimize_expr(expr, expr_opts)[源代码]
angr.analyses.decompiler.utils.copy_graph(graph)[源代码]

Copy AIL Graph.

返回:

A copy of the AIl graph.

参数:

graph (DiGraph)

angr.analyses.decompiler.utils.peephole_optimize_stmts(block, stmt_opts)[源代码]
angr.analyses.decompiler.utils.match_stmt_classes(all_stmts, idx, stmt_class_seq)[源代码]
返回类型:

bool

参数:
angr.analyses.decompiler.utils.peephole_optimize_multistmts(block, stmt_opts)[源代码]
angr.analyses.decompiler.utils.decompile_functions(path, functions=None, structurer=None, catch_errors=False, show_casts=True, base_address=None, preset=None)[源代码]

Decompile a binary into a set of functions.

参数:
  • path -- The path to the binary to decompile.

  • functions (Optional[list[int | str]]) -- The functions to decompile. If None, all functions will be decompiled.

  • structurer (Optional[str]) -- The structuring algorithms to use.

  • catch_errors (bool) -- The structuring algorithms to use.

  • show_casts (bool) -- Whether to show casts in the decompiled output.

  • base_address (Optional[int]) -- The base address of the binary.

  • preset (Optional[str]) -- The configuration preset to use during decompilation.

返回类型:

str | None

返回:

The decompilation of all functions appended in order.

angr.analyses.decompiler.utils.calls_in_graph(graph)[源代码]

Counts the number of calls in an graph full of AIL Blocks

返回类型:

int

参数:

graph (DiGraph)

angr.analyses.decompiler.utils.find_block_by_addr(graph, addr, insn_addr=False)[源代码]
参数:

graph (DiGraph)

angr.analyses.decompiler.utils.sequence_to_blocks(seq)[源代码]

Converts a sequence node (BaseNode) to a list of ailment blocks contained in it and all its children.

返回类型:

list[Block]

参数:

seq (BaseNode)

angr.analyses.decompiler.utils.sequence_to_statements(seq, exclude=(<class 'ailment.statement.Jump'>, <class 'ailment.statement.Jump'>))[源代码]

Converts a sequence node (BaseNode) to a list of ailment Statements contained in it and all its children. May exclude certain types of statements.

返回类型:

list[Statement]

参数:

seq (BaseNode)

class angr.analyses.ddg.AST(op, *operands)[源代码]

基类:object

A mini implementation for AST

__init__(op, *operands)[源代码]
class angr.analyses.ddg.ProgramVariable(variable, location, initial=False, arch=None)[源代码]

基类:object

Describes a variable in the program at a specific location.

变量:
__init__(variable, location, initial=False, arch=None)[源代码]
property short_repr
class angr.analyses.ddg.DDGJob(cfg_node, call_depth)[源代码]

基类:object

__init__(cfg_node, call_depth)[源代码]
class angr.analyses.ddg.LiveDefinitions[源代码]

基类:object

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

__init__()[源代码]

Constructor.

branch()[源代码]

Create a branch of the current live definition collection.

返回:

A new LiveDefinition instance.

返回类型:

angr.analyses.ddg.LiveDefinitions

copy()[源代码]

Make a hard copy of self.

返回:

A new LiveDefinition instance.

返回类型:

angr.analyses.ddg.LiveDefinitions

add_def(variable, location, size_threshold=32)[源代码]

Add a new definition of variable.

参数:
  • variable (SimVariable) -- The variable being defined.

  • location (CodeLocation) -- Location of the variable being defined.

  • size_threshold (int) -- The maximum bytes to consider for the variable.

返回:

True if the definition was new, False otherwise

返回类型:

bool

add_defs(variable, locations, size_threshold=32)[源代码]

Add a collection of new definitions of a variable.

参数:
  • variable (SimVariable) -- The variable being defined.

  • locations (iterable) -- A collection of locations where the variable was defined.

  • size_threshold (int) -- The maximum bytes to consider for the variable.

返回:

True if any of the definition was new, False otherwise

返回类型:

bool

kill_def(variable, location, size_threshold=32)[源代码]

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

参数:
  • variable (SimVariable) -- The variable to kill.

  • location (CodeLocation) -- The location where this variable is defined.

  • size_threshold (int) -- The maximum bytes to consider for the variable.

返回:

None

lookup_defs(variable, size_threshold=32)[源代码]

Find all definitions of the variable.

参数:
  • variable (SimVariable) -- The variable to lookup for.

  • size_threshold (int) -- The maximum bytes to consider for the variable. For example, if the variable is 100 byte long, only the first size_threshold bytes are considered.

返回:

A set of code locations where the variable is defined.

返回类型:

set

items()[源代码]

An iterator that returns all live definitions.

返回:

The iterator.

返回类型:

iter

itervariables()[源代码]

An iterator that returns all live variables.

返回:

The iterator.

返回类型:

iter

class angr.analyses.ddg.DDGViewItem(ddg, variable, simplified=False)[源代码]

基类:object

__init__(ddg, variable, simplified=False)[源代码]
property depends_on
property dependents
class angr.analyses.ddg.DDGViewInstruction(cfg, ddg, insn_addr, simplified=False)[源代码]

基类:object

__init__(cfg, ddg, insn_addr, simplified=False)[源代码]
property definitions: list[DDGViewItem]

Get all definitions located at the current instruction address.

返回:

A list of ProgramVariable instances.

class angr.analyses.ddg.DDGView(cfg, ddg, simplified=False)[源代码]

基类:object

A view of the data dependence graph.

__init__(cfg, ddg, simplified=False)[源代码]
class angr.analyses.ddg.DDG(cfg, start=None, call_depth=None, block_addrs=None)[源代码]

基类:Analysis

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

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

The DDG is based on a CFG, which should ideally be a CFGEmulated generated with the following options:

  • keep_state=True to keep all input states

  • state_add_options=angr.options.refs to store memory, register, and temporary value accesses

You may want to consider a high value for context_sensitivity_level as well when generating the CFG.

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

__init__(cfg, start=None, call_depth=None, block_addrs=None)[源代码]
参数:
  • cfg -- Control flow graph. Please make sure each node has an associated state with it, e.g. by passing the keep_state=True and state_add_options=angr.options.refs arguments to CFGEmulated.

  • start -- An address, Specifies where we start the generation of this data dependence graph.

  • call_depth -- None or integers. A non-negative integer specifies how deep we would like to track in the call tree. None disables call_depth limit.

  • block_addrs (iterable or None) -- A collection of block addresses that the DDG analysis should be performed on.

property graph

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

Type:

returns

property data_graph

Get the data dependence graph.

返回:

A networkx DiGraph instance representing data dependence.

返回类型:

networkx.DiGraph

property simplified_data_graph

return:

property ast_graph
pp()[源代码]

Pretty printing.

dbg_repr()[源代码]

Representation for debugging.

get_predecessors(code_location)[源代码]

Returns all predecessors of the code location.

参数:

code_location -- A CodeLocation instance.

返回:

A list of all predecessors.

function_dependency_graph(func)[源代码]

Get a dependency graph for the function func.

参数:

func -- The Function object in CFG.function_manager.

返回:

A networkx.DiGraph instance.

data_sub_graph(pv, simplified=True, killing_edges=False, excluding_types=None)[源代码]

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

参数:
  • pv (ProgramVariable) -- The starting point of the subgraph.

  • simplified (bool) -- When True, the simplified data graph is used, otherwise the data graph is used.

  • killing_edges (bool) -- Are killing edges included or not.

  • excluding_types (iterable) -- Excluding edges whose types are among those excluded types.

返回:

A subgraph.

返回类型:

networkx.MultiDiGraph

find_definitions(variable, location=None, simplified_graph=True)[源代码]

Find all definitions of the given variable.

参数:
  • variable (SimVariable)

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

返回:

A collection of all variable definitions to the specific variable.

返回类型:

list

find_consumers(var_def, simplified_graph=True)[源代码]

Find all consumers to the specified variable definition.

参数:
  • var_def (ProgramVariable) -- The variable definition.

  • simplified_graph (bool) -- True if we want to search in the simplified graph, False otherwise.

返回:

A collection of all consumers to the specified variable definition.

返回类型:

list

find_killers(var_def, simplified_graph=True)[源代码]

Find all killers to the specified variable definition.

参数:
  • var_def (ProgramVariable) -- The variable definition.

  • simplified_graph (bool) -- True if we want to search in the simplified graph, False otherwise.

返回:

A collection of all killers to the specified variable definition.

返回类型:

list

find_sources(var_def, simplified_graph=True)[源代码]

Find all sources to the specified variable definition.

参数:
  • var_def (ProgramVariable) -- The variable definition.

  • simplified_graph (bool) -- True if we want to search in the simplified graph, False otherwise.

返回:

A collection of all sources to the specified variable definition.

返回类型:

list

class angr.analyses.flirt.FlirtAnalysis(sig=None)[源代码]

基类:Analysis

FlirtAnalysis accomplishes two purposes:

  • If a FLIRT signature file is specified, it will match the given signature file against the current binary and rename recognized functions accordingly.

  • If no FLIRT signature file is specified, it will use strings to determine possible libraries embedded in the current binary, and then match all possible signatures for the architecture.

参数:

sig (FlirtSignature | str | None)

__init__(sig=None)[源代码]
参数:

sig (FlirtSignature | str | None)

class angr.engines.light.data.ArithmeticExpression(op, operands)[源代码]

基类:object

Add = 0
Sub = 1
Or = 2
And = 4
RShift = 8
LShift = 16
Mul = 32
Xor = 64
CONST_TYPES = (<class 'int'>, <class 'ailment.expression.Const'>)
__init__(op, operands)[源代码]
op
operands
static try_unpack_const(expr)[源代码]
class angr.engines.light.data.RegisterOffset(bits, reg, offset)[源代码]

基类:object

__init__(bits, reg, offset)[源代码]
reg
offset
property bits
property symbolic
class angr.engines.light.data.SpOffset(bits, offset, is_base=False)[源代码]

基类:RegisterOffset

__init__(bits, offset, is_base=False)[源代码]
is_base
class angr.engines.light.ArithmeticExpression(op, operands)[源代码]

基类:object

Add = 0
Sub = 1
Or = 2
And = 4
RShift = 8
LShift = 16
Mul = 32
Xor = 64
CONST_TYPES = (<class 'int'>, <class 'ailment.expression.Const'>)
__init__(op, operands)[源代码]
op
operands
static try_unpack_const(expr)[源代码]
class angr.engines.light.RegisterOffset(bits, reg, offset)[源代码]

基类:object

__init__(bits, reg, offset)[源代码]
reg
offset
property bits
property symbolic
class angr.engines.light.SimEngineLight(project, logger=None)[源代码]

基类:Generic[StateType, DataType_co, BlockType, ResultType], SimEngine[StateType, ResultType]

A full-featured engine base class, suitable for static analysis

参数:

project (Project)

block: TypeVar(BlockType, bound= BlockProtocol)
state: TypeVar(StateType)
stmt_idx: int
ins_addr: int
tmps: dict[int, TypeVar(DataType_co, covariant=True)]
__init__(project, logger=None)[源代码]
参数:

project (Project)

process(state, *, block=None, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:
  • state (TypeVar(StateType)) -- The state to proceed from

  • block (BlockType | None)

返回类型:

TypeVar(ResultType)

返回:

The result. Whatever you want ;)

lift(state)[源代码]
返回类型:

TypeVar(BlockType, bound= BlockProtocol)

参数:

state (StateType)

static sp_offset(bits, offset)[源代码]
返回类型:

BV

参数:
static extract_offset_to_sp(spoffset_expr)[源代码]

Extract the offset to the original stack pointer.

参数:

spoffset_expr (Base) -- The claripy AST to parse.

返回类型:

int | None

返回:

The offset to the original stack pointer, or None if spoffset_expr is not a supported type of SpOffset expression.

class angr.engines.light.SimEngineLightAIL(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, StmtDataType, ResultType], SimEngineLight[StateType, DataType_co, Block, ResultType]

A mixin for doing static analysis on AIL

__init__(*args, **kwargs)[源代码]
class angr.engines.light.SimEngineLightVEX(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, ResultType, StmtDataType], SimEngineLight[StateType, DataType_co, Block, ResultType]

A mixin for doing static analysis on VEX

tyenv: IRTypeEnv
static unop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Unop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Unop], DataType_co])

static binop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Binop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Binop], DataType_co])

static binopv_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), int, int, Binop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, int, int, Binop], DataType_co])

static triop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Triop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Triop], DataType_co])

static qop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Qop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Qop], DataType_co])

static ccall_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), CCall], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, CCall], DataType_co])

static dirty_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Dirty], TypeVar(StmtDataType)]

参数:

f (Callable[[T, Dirty], StmtDataType])

__init__(*args, **kwargs)[源代码]
class angr.engines.light.SimEngineNoexprAIL(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, StmtDataType, ResultType], SimEngineLightAIL[StateType, DataType_co | None, StmtDataType, ResultType]

A base class of SimEngineLightAIL that has default handlers for expressions if they just need to return None, so you don't have to implement every single expression handler as return None.

class angr.engines.light.SimEngineNostmtAIL(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, StmtDataType, ResultType], SimEngineLightAIL[StateType, DataType_co, StmtDataType | None, ResultType]

A base class of SimEngineLightAIL that has default handlers for statements if they just need to return None, so you don't have to implement every single statement handler as return None.

class angr.engines.light.SimEngineNostmtVEX(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, ResultType], SimEngineLightVEX[StateType, DataType_co, ResultType, None]

A base class of SimEngineLightVEX that has default handlers for statements if they just need to return None, so you don't have to implement every single statement handler as return None.

class angr.engines.light.SpOffset(bits, offset, is_base=False)[源代码]

基类:RegisterOffset

__init__(bits, offset, is_base=False)[源代码]
is_base
class angr.engines.light.engine.BlockProtocol(*args, **kwargs)[源代码]

基类:Protocol

The minimum protocol that a block an engine can process should adhere to. Requires just an addr attribute.

addr: int
__init__(*args, **kwargs)
class angr.engines.light.engine.IRTop(ty)[源代码]

基类:IRExpr

A dummy IRExpr used for intra-engine communication and code-reuse.

参数:

ty (str)

__init__(ty)[源代码]
参数:

ty (str)

result_type(tyenv)[源代码]
class angr.engines.light.engine.SimEngineLight(project, logger=None)[源代码]

基类:Generic[StateType, DataType_co, BlockType, ResultType], SimEngine[StateType, ResultType]

A full-featured engine base class, suitable for static analysis

参数:

project (Project)

block: TypeVar(BlockType, bound= BlockProtocol)
state: TypeVar(StateType)
stmt_idx: int
ins_addr: int
tmps: dict[int, TypeVar(DataType_co, covariant=True)]
__init__(project, logger=None)[源代码]
参数:

project (Project)

process(state, *, block=None, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:
  • state (TypeVar(StateType)) -- The state to proceed from

  • block (BlockType | None)

返回类型:

TypeVar(ResultType)

返回:

The result. Whatever you want ;)

lift(state)[源代码]
返回类型:

TypeVar(BlockType, bound= BlockProtocol)

参数:

state (StateType)

static sp_offset(bits, offset)[源代码]
返回类型:

BV

参数:
static extract_offset_to_sp(spoffset_expr)[源代码]

Extract the offset to the original stack pointer.

参数:

spoffset_expr (Base) -- The claripy AST to parse.

返回类型:

int | None

返回:

The offset to the original stack pointer, or None if spoffset_expr is not a supported type of SpOffset expression.

angr.engines.light.engine.longest_prefix_lookup(haystack, mapping)[源代码]
返回类型:

Optional[TypeVar(T)]

参数:
class angr.engines.light.engine.SimEngineLightVEX(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, ResultType, StmtDataType], SimEngineLight[StateType, DataType_co, Block, ResultType]

A mixin for doing static analysis on VEX

tyenv: IRTypeEnv
static unop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Unop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Unop], DataType_co])

static binop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Binop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Binop], DataType_co])

static binopv_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), int, int, Binop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, int, int, Binop], DataType_co])

static triop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Triop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Triop], DataType_co])

static qop_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Qop], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, Qop], DataType_co])

static ccall_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), CCall], TypeVar(DataType_co, covariant=True)]

参数:

f (Callable[[T, CCall], DataType_co])

static dirty_handler(f)[源代码]
返回类型:

Callable[[TypeVar(T), Dirty], TypeVar(StmtDataType)]

参数:

f (Callable[[T, Dirty], StmtDataType])

__init__(*args, **kwargs)[源代码]
block: TypeVar(BlockType, bound= BlockProtocol)
state: TypeVar(StateType)
stmt_idx: int
ins_addr: int
tmps: dict[int, TypeVar(DataType_co, covariant=True)]
class angr.engines.light.engine.SimEngineNostmtVEX(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, ResultType], SimEngineLightVEX[StateType, DataType_co, ResultType, None]

A base class of SimEngineLightVEX that has default handlers for statements if they just need to return None, so you don't have to implement every single statement handler as return None.

class angr.engines.light.engine.SimEngineLightAIL(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, StmtDataType, ResultType], SimEngineLight[StateType, DataType_co, Block, ResultType]

A mixin for doing static analysis on AIL

__init__(*args, **kwargs)[源代码]
class angr.engines.light.engine.SimEngineNostmtAIL(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, StmtDataType, ResultType], SimEngineLightAIL[StateType, DataType_co, StmtDataType | None, ResultType]

A base class of SimEngineLightAIL that has default handlers for statements if they just need to return None, so you don't have to implement every single statement handler as return None.

class angr.engines.light.engine.SimEngineNoexprAIL(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, StmtDataType, ResultType], SimEngineLightAIL[StateType, DataType_co | None, StmtDataType, ResultType]

A base class of SimEngineLightAIL that has default handlers for expressions if they just need to return None, so you don't have to implement every single expression handler as return None.

class angr.analyses.propagator.PropagatorAnalysis(func=None, block=None, func_graph=None, base_state=None, max_iterations=30, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False, func_addr=None, gp=None, cache_results=False, key_prefix=None, profiling=False)[源代码]

基类:ForwardAnalysis, Analysis

PropagatorAnalysis implements copy propagation. It propagates values (either constant values or variables) and expressions inside a block or across a function.

PropagatorAnalysis only supports VEX. For AIL, please use SPropagator.

PropagatorAnalysis performs certain arithmetic operations between constants, including but are not limited to:

  • addition

  • subtraction

  • multiplication

  • division

  • xor

It also performs the following memory operations:

  • Loading values from a known address

  • Writing values to a stack variable

参数:
  • func_addr (int | None)

  • gp (int | None)

  • cache_results (bool)

  • key_prefix (str | None)

  • profiling (bool)

__init__(func=None, block=None, func_graph=None, base_state=None, max_iterations=30, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False, func_addr=None, gp=None, cache_results=False, key_prefix=None, profiling=False)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

  • func_addr (int | None)

  • gp (int | None)

  • cache_results (bool)

  • key_prefix (str | None)

  • profiling (bool)

返回:

None

property prop_key: tuple[str | None, str, int, bool, bool, bool]

Gets a key that represents the function and the "flavor" of the propagation result.

property replacements
class angr.analyses.propagator.values.Top(size)[源代码]

基类:object

__init__(size)[源代码]
size
property bits
class angr.analyses.propagator.values.Bottom[源代码]

基类:object

class angr.analyses.propagator.vex_vars.VEXVariable[源代码]

基类:object

class angr.analyses.propagator.vex_vars.VEXMemVar(addr, size)[源代码]

基类:object

参数:
__init__(addr, size)[源代码]
参数:
addr
size
class angr.analyses.propagator.vex_vars.VEXReg(offset, size)[源代码]

基类:VEXVariable

__init__(offset, size)[源代码]
offset
size
class angr.analyses.propagator.vex_vars.VEXTmp(tmp)[源代码]

基类:VEXVariable

__init__(tmp)[源代码]
tmp
class angr.analyses.propagator.engine_base.SimEnginePropagatorBaseMixin(project, stack_pointer_tracker=None, propagate_tmps=True, reaching_definitions=None, bp_as_gpr=False)[源代码]

基类:Generic[StateType, DataType_co, BlockType], SimEngineLight[StateType, DataType_co, BlockType, StateType]

The base class for the propagator VEX engine.

参数:
__init__(project, stack_pointer_tracker=None, propagate_tmps=True, reaching_definitions=None, bp_as_gpr=False)[源代码]
参数:
process(state, *, block=None, base_state=None, load_callback=None, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:
  • state (TypeVar(StateType)) -- The state to proceed from

  • block (BlockType | None)

返回类型:

TypeVar(StateType)

返回:

The result. Whatever you want ;)

class angr.analyses.propagator.engine_vex.SimEnginePropagatorVEX(project, stack_pointer_tracker=None, propagate_tmps=True, reaching_definitions=None, bp_as_gpr=False)[源代码]

基类:ClaripyDataVEXEngineMixin[PropagatorVEXState, BV, PropagatorVEXState, None], SimEnginePropagatorBaseMixin[PropagatorVEXState, BV, Block], SimEngineNostmtVEX[PropagatorVEXState, BV, PropagatorVEXState]

参数:
class angr.analyses.propagator.propagator.PropagatorAnalysis(func=None, block=None, func_graph=None, base_state=None, max_iterations=30, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False, func_addr=None, gp=None, cache_results=False, key_prefix=None, profiling=False)[源代码]

基类:ForwardAnalysis, Analysis

PropagatorAnalysis implements copy propagation. It propagates values (either constant values or variables) and expressions inside a block or across a function.

PropagatorAnalysis only supports VEX. For AIL, please use SPropagator.

PropagatorAnalysis performs certain arithmetic operations between constants, including but are not limited to:

  • addition

  • subtraction

  • multiplication

  • division

  • xor

It also performs the following memory operations:

  • Loading values from a known address

  • Writing values to a stack variable

参数:
  • func_addr (int | None)

  • gp (int | None)

  • cache_results (bool)

  • key_prefix (str | None)

  • profiling (bool)

__init__(func=None, block=None, func_graph=None, base_state=None, max_iterations=30, load_callback=None, stack_pointer_tracker=None, only_consts=False, completed_funcs=None, do_binops=True, store_tops=True, vex_cross_insn_opt=False, func_addr=None, gp=None, cache_results=False, key_prefix=None, profiling=False)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

  • func_addr (int | None)

  • gp (int | None)

  • cache_results (bool)

  • key_prefix (str | None)

  • profiling (bool)

返回:

None

property prop_key: tuple[str | None, str, int, bool, bool, bool]

Gets a key that represents the function and the "flavor" of the propagation result.

property replacements
class angr.analyses.propagator.top_checker_mixin.ClaripyDataEngineMixin(project, logger=None)[源代码]

基类:Generic[StateType, DataType_co, BlockType, ResultType], SimEngineLight[StateType, DataType_co | BV, BlockType, ResultType]

参数:

project (Project)

class angr.analyses.propagator.top_checker_mixin.ClaripyDataVEXEngineMixin(*args, **kwargs)[源代码]

基类:Generic[StateType, DataType_co, ResultType, StmtDataType], ClaripyDataEngineMixin[StateType, DataType_co, Block, ResultType], SimEngineLightVEX[StateType, DataType_co | BV, ResultType, StmtDataType]

class angr.analyses.reaching_definitions.Atom(size)[源代码]

基类:object

This class represents a data storage location manipulated by IR instructions.

It could either be a Tmp (temporary variable), a Register, a MemoryLocation.

__init__(size)[源代码]
参数:

size -- The size of the atom in bytes

size
property bits: int
static from_ail_expr(expr, arch, full_reg=False)[源代码]
返回类型:

Register

参数:
static from_argument(argument, arch, full_reg=False, sp=None)[源代码]

Instantiate an Atom from a given argument.

参数:
  • argument (SimFunctionArgument) -- The argument to create a new atom from.

  • arch (Arch) -- The argument representing archinfo architecture for argument.

  • full_reg -- Whether to return an atom indicating the entire register if the argument only specifies a slice of the register.

  • sp (Optional[int]) -- The current stack offset. Optional. Only used when argument is a SimStackArg.

返回类型:

Register | MemoryLocation

static reg(thing, size=None, arch=None)[源代码]

Create a Register atom.

参数:
  • thing (str | RegisterOffset) -- The register offset (e.g., project.arch.registers["rax"][0]) or the register name (e.g., "rax").

  • size (Optional[int]) -- Size of the register atom. Must be provided when creating the atom using a register offset.

  • arch (Optional[Arch]) -- The architecture. Must be provided when creating the atom using a register name.

返回类型:

Register

返回:

The Register Atom object.

static register(thing, size=None, arch=None)

Create a Register atom.

参数:
  • thing (str | RegisterOffset) -- The register offset (e.g., project.arch.registers["rax"][0]) or the register name (e.g., "rax").

  • size (Optional[int]) -- Size of the register atom. Must be provided when creating the atom using a register offset.

  • arch (Optional[Arch]) -- The architecture. Must be provided when creating the atom using a register name.

返回类型:

Register

返回:

The Register Atom object.

static mem(addr, size, endness=None)[源代码]

Create a MemoryLocation atom,

参数:
  • addr (SpOffset | HeapAddress | int) -- The memory location. Can be an SpOffset for stack variables, an int for global memory variables, or a HeapAddress for items on the heap.

  • size (int) -- Size of the atom.

  • endness (Optional[str]) -- Optional, either "Iend_LE" or "Iend_BE".

返回类型:

MemoryLocation

返回:

The MemoryLocation Atom object.

static memory(addr, size, endness=None)

Create a MemoryLocation atom,

参数:
  • addr (SpOffset | HeapAddress | int) -- The memory location. Can be an SpOffset for stack variables, an int for global memory variables, or a HeapAddress for items on the heap.

  • size (int) -- Size of the atom.

  • endness (Optional[str]) -- Optional, either "Iend_LE" or "Iend_BE".

返回类型:

MemoryLocation

返回:

The MemoryLocation Atom object.

class angr.analyses.reaching_definitions.AtomKind(value)[源代码]

基类:Enum

An enum indicating the class of an atom

REGISTER = 1
MEMORY = 2
TMP = 3
GUARD = 4
CONSTANT = 5
class angr.analyses.reaching_definitions.ConstantSrc(value, size)[源代码]

基类:Atom

Represents a constant.

参数:
__init__(value, size)[源代码]
参数:
  • size (int) -- The size of the atom in bytes

  • value (int)

value: int
class angr.analyses.reaching_definitions.Definition(atom, codeloc, dummy=False, tags=None)[源代码]

基类:Generic[A]

An atom definition.

变量:
  • atom -- The atom being defined.

  • codeloc -- Where this definition is created in the original binary code.

  • dummy -- Tell whether the definition should be considered dummy or not. During simplification by AILment, definitions marked as dummy will not be removed.

  • tags -- A set of tags containing information about the definition gathered during analyses.

参数:
__init__(atom, codeloc, dummy=False, tags=None)[源代码]
参数:
atom: TypeVar(A, bound= Atom)
codeloc: CodeLocation
dummy: bool
tags
property offset: int
property size: int
matches(**kwargs)[源代码]

Return whether this definition has certain characteristics.

返回类型:

bool

class angr.analyses.reaching_definitions.FunctionCallData(callsite_codeloc, function_codeloc, address_multi, address=None, symbol=None, function=None, name=None, cc=None, prototype=None, args_atoms=None, args_values=None, ret_atoms=None, redefine_locals=True, visited_blocks=None, effects=<factory>, ret_values=None, ret_values_deps=None, caller_will_handle_single_ret=False, guessed_cc=False, guessed_prototype=False, retaddr_popped=False)[源代码]

基类:object

A bundle of intermediate data used when computing the sum effect of a function during ReachingDefinitionsAnalysis.

RDA engine contract:

  • Construct one of these before calling FunctionHandler.handle_function. Fill it with as many fields as you can realistically provide without duplicating effort.

  • Provide callsite_codeloc as either the call statement (AIL) or the default exit of the default statement of the calling block (VEX)

  • Provide function_codeloc as the callee address with stmt_idx=0`.

Function handler contract:

  • If redefine_locals is unset, do not adjust any artifacts of the function call abstraction, such as the stack pointer, the caller saved registers, etc.

  • If caller_will_handle_single_ret is set, and there is a single entry in ret_atoms, do not apply to the state effects modifying this atom. Instead, set ret_values and ret_values_deps to the values and deps which are used constructing these values.

参数:
callsite_codeloc: CodeLocation
function_codeloc: CodeLocation
address_multi: Optional[MultiValues[BV | FP]]
address: int | None = None
symbol: Symbol | None = None
function: Function | None = None
name: str | None = None
cc: SimCC | None = None
prototype: SimTypeFunction | None = None
args_atoms: list[set[Atom]] | None = None
args_values: list[MultiValues[BV | FP]] | None = None
ret_atoms: set[Atom] | None = None
redefine_locals: bool = True
visited_blocks: set[int] | None = None
effects: list[FunctionEffect]
ret_values: Optional[MultiValues[BV | FP]] = None
ret_values_deps: set[Definition] | None = None
caller_will_handle_single_ret: bool = False
guessed_cc: bool = False
guessed_prototype: bool = False
retaddr_popped: bool = False
has_clobbered(dest)[源代码]

Determines whether the given atom already has effects applied

返回类型:

bool

参数:

dest (Atom)

depends(dest, *sources, value=None, apply_at_callsite=False, tags=None)[源代码]

Mark a single effect of the current function, including the atom being modified, the input atoms on which that output atom depends, the precise (or imprecise!) value to store, and whether the effect should be applied during the function or afterwards, at the callsite.

The tags are used to annotate the Definition of the Atom that will be created, when the function effects are applied to the state.

The atom being modified may be None to mark uses of the source atoms which do not have any explicit sinks.

参数:
reset_prototype(prototype, state, soft_reset=False)[源代码]
返回类型:

set[Atom]

参数:
__init__(callsite_codeloc, function_codeloc, address_multi, address=None, symbol=None, function=None, name=None, cc=None, prototype=None, args_atoms=None, args_values=None, ret_atoms=None, redefine_locals=True, visited_blocks=None, effects=<factory>, ret_values=None, ret_values_deps=None, caller_will_handle_single_ret=False, guessed_cc=False, guessed_prototype=False, retaddr_popped=False)
参数:
返回类型:

None

class angr.analyses.reaching_definitions.FunctionHandler(interfunction_level=0, extra_impls=None)[源代码]

基类:object

A mechanism for summarizing a function call's effect on a program for ReachingDefinitionsAnalysis.

参数:
__init__(interfunction_level=0, extra_impls=None)[源代码]
参数:
hook(analysis)[源代码]

Attach this instance of the function handler to an instance of RDA.

返回类型:

FunctionHandler

参数:

analysis (ReachingDefinitionsAnalysis)

make_function_codeloc(target, callsite, callsite_func_addr)[源代码]

The RDA engine will call this function to transform a callsite CodeLocation into a callee CodeLocation.

参数:
handle_function(state, data)[源代码]

The main entry point for the function handler. Called with a RDA state and a FunctionCallData, it is expected to update the state and the data as per the contracts described on FunctionCallData.

You can override this method to take full control over how data is processed, or override any of the following to use the higher-level interface (data.depends()):

  • handle_impl_<function name> - used for <function name>.

  • handle_local_function - used for any function (excluding plt stubs) whose address is inside the main binary.

  • handle_external_function - used for any function or plt stub whose address is outside the main binary.

  • handle_indirect_function - used for any function whose target cannot be resolved.

  • handle_generic_function - used as a default if none of the above are overridden.

Each of them take the same signature as handle_function.

参数:
handle_generic_function(state, data)[源代码]
参数:
handle_indirect_function(state, data)[源代码]
返回类型:

None

参数:
handle_local_function(state, data)[源代码]
返回类型:

None

参数:
handle_external_function(state, data)[源代码]
返回类型:

None

参数:
recurse_analysis(state, data)[源代码]

Precondition: data.function MUST NOT BE NONE in order to call this method.

返回类型:

None

参数:
static c_args_as_atoms(state, cc, prototype)[源代码]
返回类型:

list[set[Atom]]

参数:
static c_return_as_atoms(state, cc, prototype)[源代码]
返回类型:

set[Atom]

参数:
static caller_saved_regs_as_atoms(state, cc)[源代码]
返回类型:

set[Register]

参数:
static stack_pointer_as_atom(state)[源代码]
返回类型:

Register

class angr.analyses.reaching_definitions.GuardUse(target)[源代码]

基类:Atom

Implements a guard use.

__init__(target)[源代码]
参数:

size -- The size of the atom in bytes

target
class angr.analyses.reaching_definitions.LiveDefinitions(arch, track_tmps=False, canonical_size=8, registers=None, stack=None, memory=None, heap=None, tmps=None, others=None, register_uses=None, stack_uses=None, heap_uses=None, memory_uses=None, tmp_uses=None, other_uses=None, element_limit=5, merge_into_tops=True)[源代码]

基类:object

A LiveDefinitions instance contains definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.

参数:
INITIAL_SP_32BIT = 2147418112
INITIAL_SP_64BIT = 140737488289792
__init__(arch, track_tmps=False, canonical_size=8, registers=None, stack=None, memory=None, heap=None, tmps=None, others=None, register_uses=None, stack_uses=None, heap_uses=None, memory_uses=None, tmp_uses=None, other_uses=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
project: Project | None
arch
track_tmps
registers: MultiValuedMemory
stack: MultiValuedMemory
memory: MultiValuedMemory
heap: MultiValuedMemory
tmps: dict[int, set[Definition]]
others: dict[Atom, MultiValues]
register_uses
stack_uses
heap_uses
memory_uses
tmp_uses: dict[int, set[CodeLocation]]
other_uses
uses_by_codeloc: dict[CodeLocation, set[Definition]]
property register_definitions
property stack_definitions
property memory_definitions
property heap_definitions
copy(discard_tmpdefs=False)[源代码]
返回类型:

LiveDefinitions

reset_uses()[源代码]
static top(bits)[源代码]

Get a TOP value.

参数:

bits (int) -- Width of the TOP value (in bits).

返回:

The TOP value.

static is_top(expr)[源代码]

Check if the given expression is a TOP value.

参数:

expr -- The given expression.

返回类型:

bool

返回:

True if the expression is TOP, False otherwise.

stack_address(offset)[源代码]
返回类型:

BV

参数:

offset (int)

static is_stack_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_stack_offset(addr, had_stack_base=False)[源代码]
返回类型:

int | None

参数:

addr (Base)

static annotate_with_def(symvar, definition)[源代码]
参数:
返回类型:

TypeVar(MVType, bound= BV | FP)

返回:

static extract_defs(symvar)[源代码]
返回类型:

Generator[Definition]

参数:

symvar (Base)

static extract_defs_from_annotations(annos)[源代码]
返回类型:

set[Definition]

参数:

annos (Iterable[Annotation])

static extract_defs_from_mv(mv)[源代码]
返回类型:

Generator[Definition]

参数:

mv (MultiValues)

get_sp()[源代码]

Return the concrete value contained by the stack pointer.

返回类型:

int

get_sp_offset()[源代码]

Return the offset of the stack pointer.

返回类型:

int | None

get_stack_address(offset)[源代码]
返回类型:

int | None

参数:

offset (Base)

stack_offset_to_stack_addr(offset)[源代码]
返回类型:

int

merge(*others)[源代码]
返回类型:

tuple[LiveDefinitions, bool]

参数:

others (LiveDefinitions)

compare(other)[源代码]
返回类型:

bool

参数:

other (LiveDefinitions)

kill_definitions(atom)[源代码]

Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification.

参数:

atom (Atom)

返回类型:

None

返回:

None

kill_and_add_definition(atom, code_loc, data, dummy=False, tags=None, endness=None, annotated=False)[源代码]
返回类型:

MultiValues | None

参数:
add_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_use_by_def(definition, code_loc, expr=None)[源代码]
返回类型:

None

参数:
get_definitions(thing)[源代码]
返回类型:

set[Definition[Atom]]

参数:

thing (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]] | MultiValues)

get_tmp_definitions(tmp_idx)[源代码]
返回类型:

set[Definition]

参数:

tmp_idx (int)

get_register_definitions(reg_offset, size)[源代码]
返回类型:

set[Definition]

参数:
get_stack_values(stack_offset, size, endness)[源代码]
返回类型:

MultiValues | None

参数:
  • stack_offset (int)

  • size (int)

  • endness (str)

get_stack_definitions(stack_offset, size)[源代码]
返回类型:

set[Definition]

参数:
  • stack_offset (int)

  • size (int)

get_heap_definitions(heap_addr, size)[源代码]
返回类型:

set[Definition]

参数:
get_memory_definitions(addr, size)[源代码]
返回类型:

set[Definition]

参数:
get_definitions_from_atoms(**kwargs)
get_value_from_definition(**kwargs)
get_one_value_from_definition(**kwargs)
get_concrete_value_from_definition(**kwargs)
get_value_from_atom(**kwargs)
get_one_value_from_atom(**kwargs)
get_concrete_value_from_atom(**kwargs)
get_values(spec)[源代码]
返回类型:

MultiValues | None

参数:

spec (A | Definition[A] | Iterable[A] | Iterable[Definition[A]])

get_one_value(spec, strip_annotations=False)[源代码]
返回类型:

BV | None

参数:
get_concrete_value(spec, cast_to=<class 'int'>)[源代码]
返回类型:

int | bytes | None

参数:
add_register_use(reg_offset, size, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_register_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_heap_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_heap_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_memory_use(atom, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_memory_use_by_def(def_, code_loc, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use(atom, code_loc)[源代码]
返回类型:

None

参数:
add_tmp_use_by_def(def_, code_loc)[源代码]
返回类型:

None

参数:
deref(pointer, size, endness=Endness.BE)[源代码]
static is_heap_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_heap_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

heap_address(offset)[源代码]
返回类型:

BV

参数:

offset (int | HeapAddress)

class angr.analyses.reaching_definitions.MemoryLocation(addr, size, endness=None)[源代码]

基类:Atom

Represents a memory slice.

It is characterized by its address and its size.

参数:
__init__(addr, size, endness=None)[源代码]
参数:
  • addr (int) -- The address of the beginning memory location slice.

  • size (int) -- The size of the represented memory location, in bytes.

  • endness (str | None)

addr: SpOffset | int | BV
endness
property is_on_stack: bool

True if this memory location is located on the stack.

property symbolic: bool
class angr.analyses.reaching_definitions.ObservationPointType(value)[源代码]

基类:IntEnum

Enum to replace the previously generic constants This makes it possible to annotate where they are expected by typing something as ObservationPointType instead of Literal[0,1]

OP_BEFORE = 0
OP_AFTER = 1
class angr.analyses.reaching_definitions.ReachingDefinitionsAnalysis(subject=None, func_graph=None, max_iterations=30, track_tmps=False, track_consts=True, observation_points=None, init_state=None, init_context=None, state_initializer=None, cc=None, function_handler=None, observe_all=False, visited_blocks=None, dep_graph=True, observe_callback=None, canonical_size=8, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, interfunction_level=0, track_liveness=True, func_addr=None, element_limit=5, merge_into_tops=True)[源代码]

基类:ForwardAnalysis[ReachingDefinitionsState, NodeType, object, object], Analysis

ReachingDefinitionsAnalysis is a text-book implementation of a static data-flow analysis that works on either a function or a block. It supports both VEX and AIL. By registering observers to observation points, users may use this analysis to generate use-def chains, def-use chains, and reaching definitions, and perform other traditional data-flow analyses such as liveness analysis.

  • I've always wanted to find a better name for this analysis. Now I gave up and decided to live with this name for the foreseeable future (until a better name is proposed by someone else).

  • Aliasing is definitely a problem, and I forgot how aliasing is resolved in this implementation. I'll leave this as a post-graduation TODO.

  • Some more documentation and examples would be nice.

参数:
__init__(subject=None, func_graph=None, max_iterations=30, track_tmps=False, track_consts=True, observation_points=None, init_state=None, init_context=None, state_initializer=None, cc=None, function_handler=None, observe_all=False, visited_blocks=None, dep_graph=True, observe_callback=None, canonical_size=8, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, interfunction_level=0, track_liveness=True, func_addr=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
  • subject (Union[Subject, Block, Block, Function, str, None]) -- The subject of the analysis: a function, or a single basic block

  • func_graph -- Alternative graph for function.graph.

  • max_iterations -- The maximum number of iterations before the analysis is terminated.

  • track_tmps -- Whether or not temporary variables should be taken into consideration during the analysis.

  • observation_points (iterable) -- A collection of tuples of ("node"|"insn", ins_addr, OP_TYPE) defining where reaching definitions should be copied and stored. OP_TYPE can be OP_BEFORE or OP_AFTER.

  • init_state (Optional[ReachingDefinitionsState]) -- An optional initialization state. The analysis creates and works on a copy. Default to None: the analysis then initialize its own abstract state, based on the given <Subject>.

  • init_context -- If init_state is not given, this is used to initialize the context field of the initial state's CodeLocation. The only default-supported type which may go here is a tuple of integers, i.e. a callstack. Anything else requires a custom FunctionHandler.

  • cc -- Calling convention of the function.

  • function_handler (Optional[FunctionHandler]) -- The function handler to update the analysis state and results on function calls.

  • observe_all -- Observe every statement, both before and after.

  • visited_blocks -- A set of previously visited blocks.

  • dep_graph (DepGraph | bool | None) -- An initial dependency graph to add the result of the analysis to. Set it to None to skip dependency graph generation.

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

  • dep_graph -- Set this to True to generate a dependency graph for the subject. It will be available as result.dep_graph.

  • interfunction_level (int) -- The number of functions we should recurse into. This parameter is only used if function_handler is not provided.

  • track_liveness (bool) -- Whether to track liveness information. This can consume sizeable amounts of RAM on large functions. (e.g. ~15GB for a function with 4k nodes)

  • merge_into_tops (bool) -- Merge known values into TOP if TOP is present. If True: {TOP} V {0xabc} = {TOP} If False: {TOP} V {0xabc} = {TOP, 0xabc}

  • state_initializer (RDAStateInitializer | None)

  • func_addr (int | None)

  • element_limit (int)

property observed_results: dict[tuple[str, int, int], LiveDefinitions]
property all_definitions
property all_uses
property one_result
property dep_graph: DepGraph
property visited_blocks
get_reaching_definitions(**kwargs)
get_reaching_definitions_by_insn(ins_addr, op_type)[源代码]
get_reaching_definitions_by_node(node_addr, op_type)[源代码]
node_observe(node_addr, state, op_type, node_idx=None)[源代码]
参数:
  • node_addr (int) -- Address of the node.

  • state (ReachingDefinitionsState) -- The analysis state.

  • op_type (ObservationPointType) -- Type of the observation point. Must be one of the following: OP_BEFORE, OP_AFTER.

  • node_idx (Optional[int]) -- ID of the node. Used in AIL to differentiate blocks with the same address.

返回类型:

None

insn_observe(insn_addr, stmt, block, state, op_type)[源代码]
参数:
返回类型:

None

stmt_observe(stmt_idx, stmt, block, state, op_type)[源代码]
参数:
返回类型:

None

返回:

exit_observe(node_addr, exit_stmt_idx, block, state, node_idx=None)[源代码]
参数:
property subject
callsites_to(target)[源代码]
返回类型:

Iterable[FunctionCallRelationships]

参数:

target (int | str | Function)

class angr.analyses.reaching_definitions.ReachingDefinitionsModel(func_addr=None, track_liveness=True)[源代码]

基类:object

Models the definitions, uses, and memory of a ReachingDefinitionState object

参数:
  • func_addr (int | None)

  • track_liveness (bool)

__init__(func_addr=None, track_liveness=True)[源代码]
参数:
  • func_addr (int | None)

  • track_liveness (bool)

add_def(d)[源代码]
返回类型:

None

参数:

d (Definition)

kill_def(d)[源代码]
返回类型:

None

参数:

d (Definition)

at_new_stmt(codeloc)[源代码]
返回类型:

None

参数:

codeloc (CodeLocation)

at_new_block(code_loc, pred_codelocs)[源代码]
返回类型:

None

参数:
make_liveness_snapshot()[源代码]
返回类型:

None

find_defs_at(code_loc, op=ObservationPointType.OP_BEFORE)[源代码]
返回类型:

set[Definition]

参数:
get_defs(atom, code_loc, op)[源代码]
返回类型:

set[Definition]

参数:
copy()[源代码]
返回类型:

ReachingDefinitionsModel

merge(model)[源代码]
参数:

model (ReachingDefinitionsModel)

get_observation_by_insn(ins_addr, kind)[源代码]
返回类型:

LiveDefinitions | None

参数:
get_observation_by_node(node_addr, kind, node_idx=None)[源代码]
返回类型:

LiveDefinitions | None

参数:
get_observation_by_stmt(arg1, arg2, arg3=None, *, block_idx=None)[源代码]
get_observation_by_exit(node_addr, stmt_idx, src_node_idx=None)[源代码]
返回类型:

LiveDefinitions | None

参数:
  • node_addr (int)

  • stmt_idx (int)

  • src_node_idx (int | None)

class angr.analyses.reaching_definitions.ReachingDefinitionsState(codeloc, arch, subject, analysis, track_tmps=False, track_consts=False, rtoc_value=None, live_definitions=None, canonical_size=8, heap_allocator=None, environment=None, sp_adjusted=False, all_definitions=None, initializer=None, element_limit=5, merge_into_tops=True)[源代码]

基类:object

Represents the internal state of the ReachingDefinitionsAnalysis.

It contains a data class LiveDefinitions, which stores both definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.

参数:
  • subject (Subject) -- The subject being analyzed.

  • track_tmps (bool) -- Only tells whether or not temporary variables should be taken into consideration when representing the state of the analysis. Should be set to true when the analysis has counted uses and definitions for temporary variables, false otherwise.

  • analysis (ReachingDefinitionsAnalysis) -- The analysis that generated the state represented by this object.

  • rtoc_value -- When the targeted architecture is ppc64, the initial function needs to know the rtoc_value.

  • live_definitions (Optional[LiveDefinitions])

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

  • heap_allocator (Optional[HeapAllocator]) -- Mechanism to model the management of heap memory.

  • environment (Optional[Environment]) -- Representation of the environment of the analyzed program.

  • codeloc (CodeLocation)

  • arch (archinfo.Arch)

  • track_consts (bool)

  • sp_adjusted (bool)

  • all_definitions (set[Definition[A]] | None)

  • initializer (RDAStateInitializer | None)

  • element_limit (int)

  • merge_into_tops (bool)

变量:

arch -- The architecture targeted by the program.

__init__(codeloc, arch, subject, analysis, track_tmps=False, track_consts=False, rtoc_value=None, live_definitions=None, canonical_size=8, heap_allocator=None, environment=None, sp_adjusted=False, all_definitions=None, initializer=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
codeloc
arch: Arch
analysis
all_definitions: set[Definition[Any]]
heap_allocator
codeloc_uses: set[Definition[Any]]
exit_observed: bool
live_definitions
top(bits)[源代码]
参数:

bits (int)

is_top(*args)[源代码]
heap_address(offset)[源代码]
返回类型:

BV

参数:

offset (int | HeapAddress)

static is_heap_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_heap_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

stack_address(offset)[源代码]
返回类型:

BV

参数:

offset (int)

is_stack_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

get_stack_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

annotate_with_def(symvar, definition)[源代码]
参数:
返回类型:

TypeVar(MVType, bound= BV | FP)

返回:

annotate_mv_with_def(mv, definition)[源代码]
返回类型:

MultiValues[TypeVar(MVType, bound= BV | FP)]

参数:
extract_defs(symvar)[源代码]
返回类型:

Iterator[Definition[Any]]

参数:

symvar (Base)

property tmps
property tmp_uses
property register_uses
property registers: MultiValuedMemory
property stack: MultiValuedMemory
property stack_uses
property heap: MultiValuedMemory
property heap_uses
property memory_uses
property memory: MultiValuedMemory
property uses_by_codeloc
get_sp()[源代码]
返回类型:

int

get_stack_address(offset)[源代码]
返回类型:

int | None

参数:

offset (Base)

property environment
property dep_graph
copy(discard_tmpdefs=False)[源代码]
返回类型:

Self

merge(*others)[源代码]
返回类型:

tuple[Self, bool]

参数:

others (Self)

compare(other)[源代码]
返回类型:

bool

参数:

other (ReachingDefinitionsState)

move_codelocs(new_codeloc)[源代码]
返回类型:

None

参数:

new_codeloc (CodeLocation)

kill_definitions(atom)[源代码]

Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification.

返回类型:

None

参数:

atom (Atom)

kill_and_add_definition(atom, data, dummy=False, tags=None, endness=None, annotated=False, uses=None, override_codeloc=None)[源代码]
返回类型:

tuple[MultiValues | None, set[Definition[TypeVar(A, bound= Atom)]]]

参数:
add_use(atom, expr=None)[源代码]
返回类型:

None

参数:
add_use_by_def(definition, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use(tmp, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use_by_defs(defs, expr=None)[源代码]
返回类型:

None

参数:
add_register_use(reg_offset, size, expr=None)[源代码]
返回类型:

None

参数:
  • reg_offset (int)

  • size (int)

  • expr (Any | None)

add_register_use_by_defs(defs, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use(stack_offset, size, expr=None)[源代码]
返回类型:

None

参数:
  • stack_offset (int)

  • size (int)

  • expr (Any | None)

add_stack_use_by_defs(defs, expr=None)[源代码]
参数:
add_heap_use(heap_offset, size, expr=None)[源代码]
返回类型:

None

参数:
  • heap_offset (int)

  • size (int)

  • expr (Any | None)

add_heap_use_by_defs(defs, expr=None)[源代码]
参数:
add_memory_use_by_def(definition, expr=None)[源代码]
参数:
add_memory_use_by_defs(defs, expr=None)[源代码]
参数:
get_definitions(atom)[源代码]
返回类型:

set[Definition[Atom]]

参数:

atom (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]])

get_values(spec)[源代码]
返回类型:

MultiValues | None

参数:

spec (A | Definition[A] | Iterable[A])

get_one_value(spec, strip_annotations=False)[源代码]
返回类型:

BV | None

参数:
get_concrete_value(spec, cast_to=<class 'int'>)[源代码]
返回类型:

int | bytes | None

参数:
mark_guard(target)[源代码]
mark_const(value, size)[源代码]
参数:
downsize()[源代码]
pointer_to_atoms(**kwargs)
pointer_to_atom(**kwargs)
deref(pointer, size, endness=Endness.BE)[源代码]
参数:
class angr.analyses.reaching_definitions.Register(reg_offset, size, arch=None)[源代码]

基类:Atom

Represents a given CPU register.

As an IR abstracts the CPU design to target different architectures, registers are represented as a separated memory space. Thus a register is defined by its offset from the base of this memory and its size.

变量:
  • reg_offset (int) -- The offset from the base to define its place in the memory bloc.

  • size (int) -- The size, in number of bytes.

参数:
__init__(reg_offset, size, arch=None)[源代码]
参数:
reg_offset
arch
property name: str
class angr.analyses.reaching_definitions.Tmp(tmp_idx, size)[源代码]

基类:Atom

Represents a variable used by the IR to store intermediate values.

参数:
__init__(tmp_idx, size)[源代码]
参数:
  • size (int) -- The size of the atom in bytes

  • tmp_idx (int)

tmp_idx
angr.analyses.reaching_definitions.get_all_definitions(region)[源代码]
返回类型:

set[Definition]

参数:

region (MultiValuedMemory)

class angr.analyses.reaching_definitions.call_trace.CallSite(caller_func_addr, block_addr, callee_func_addr)[源代码]

基类:object

Describes a call site on a CFG.

参数:
  • caller_func_addr (int)

  • block_addr (int | None)

  • callee_func_addr (int)

__init__(caller_func_addr, block_addr, callee_func_addr)[源代码]
参数:
  • caller_func_addr (int)

  • block_addr (int | None)

  • callee_func_addr (int)

caller_func_addr
callee_func_addr
block_addr
class angr.analyses.reaching_definitions.call_trace.CallTrace(target)[源代码]

基类:object

Describes a series of functions calls to get from one function (current_function_address()) to another function or a basic block (self.target).

参数:

target (int)

__init__(target)[源代码]
参数:

target (int)

target
callsites: list[CallSite]
current_function_address()[源代码]
返回类型:

int

step_back(caller_func_addr, block_addr, callee_func_addr)[源代码]
返回类型:

CallTrace

参数:
  • caller_func_addr (int)

  • block_addr (int | None)

includes_function(func_addr)[源代码]
返回类型:

bool

参数:

func_addr (int)

copy()[源代码]
返回类型:

CallTrace

class angr.analyses.reaching_definitions.engine_vex.SimEngineRDVEX(project, function_handler, functions)[源代码]

基类:SimEngineNostmtVEX[ReachingDefinitionsState, MultiValues[BV | FP], ReachingDefinitionsState]

Implements the VEX execution engine for reaching definition analysis.

参数:
__init__(project, function_handler, functions)[源代码]
参数:
process(state, *, block=None, fail_fast=False, visited_blocks=None, dep_graph=None, whitelist=None, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:

state -- The state to proceed from

返回:

The result. Whatever you want ;)

class angr.analyses.reaching_definitions.reaching_definitions.ReachingDefinitionsAnalysis(subject=None, func_graph=None, max_iterations=30, track_tmps=False, track_consts=True, observation_points=None, init_state=None, init_context=None, state_initializer=None, cc=None, function_handler=None, observe_all=False, visited_blocks=None, dep_graph=True, observe_callback=None, canonical_size=8, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, interfunction_level=0, track_liveness=True, func_addr=None, element_limit=5, merge_into_tops=True)[源代码]

基类:ForwardAnalysis[ReachingDefinitionsState, NodeType, object, object], Analysis

ReachingDefinitionsAnalysis is a text-book implementation of a static data-flow analysis that works on either a function or a block. It supports both VEX and AIL. By registering observers to observation points, users may use this analysis to generate use-def chains, def-use chains, and reaching definitions, and perform other traditional data-flow analyses such as liveness analysis.

  • I've always wanted to find a better name for this analysis. Now I gave up and decided to live with this name for the foreseeable future (until a better name is proposed by someone else).

  • Aliasing is definitely a problem, and I forgot how aliasing is resolved in this implementation. I'll leave this as a post-graduation TODO.

  • Some more documentation and examples would be nice.

参数:
__init__(subject=None, func_graph=None, max_iterations=30, track_tmps=False, track_consts=True, observation_points=None, init_state=None, init_context=None, state_initializer=None, cc=None, function_handler=None, observe_all=False, visited_blocks=None, dep_graph=True, observe_callback=None, canonical_size=8, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, interfunction_level=0, track_liveness=True, func_addr=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
  • subject (Union[Subject, Block, Block, Function, str, None]) -- The subject of the analysis: a function, or a single basic block

  • func_graph -- Alternative graph for function.graph.

  • max_iterations -- The maximum number of iterations before the analysis is terminated.

  • track_tmps -- Whether or not temporary variables should be taken into consideration during the analysis.

  • observation_points (iterable) -- A collection of tuples of ("node"|"insn", ins_addr, OP_TYPE) defining where reaching definitions should be copied and stored. OP_TYPE can be OP_BEFORE or OP_AFTER.

  • init_state (Optional[ReachingDefinitionsState]) -- An optional initialization state. The analysis creates and works on a copy. Default to None: the analysis then initialize its own abstract state, based on the given <Subject>.

  • init_context -- If init_state is not given, this is used to initialize the context field of the initial state's CodeLocation. The only default-supported type which may go here is a tuple of integers, i.e. a callstack. Anything else requires a custom FunctionHandler.

  • cc -- Calling convention of the function.

  • function_handler (Optional[FunctionHandler]) -- The function handler to update the analysis state and results on function calls.

  • observe_all -- Observe every statement, both before and after.

  • visited_blocks -- A set of previously visited blocks.

  • dep_graph (DepGraph | bool | None) -- An initial dependency graph to add the result of the analysis to. Set it to None to skip dependency graph generation.

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

  • dep_graph -- Set this to True to generate a dependency graph for the subject. It will be available as result.dep_graph.

  • interfunction_level (int) -- The number of functions we should recurse into. This parameter is only used if function_handler is not provided.

  • track_liveness (bool) -- Whether to track liveness information. This can consume sizeable amounts of RAM on large functions. (e.g. ~15GB for a function with 4k nodes)

  • merge_into_tops (bool) -- Merge known values into TOP if TOP is present. If True: {TOP} V {0xabc} = {TOP} If False: {TOP} V {0xabc} = {TOP, 0xabc}

  • state_initializer (RDAStateInitializer | None)

  • func_addr (int | None)

  • element_limit (int)

property observed_results: dict[tuple[str, int, int], LiveDefinitions]
property all_definitions
property all_uses
property one_result
property dep_graph: DepGraph
property visited_blocks
get_reaching_definitions(**kwargs)
get_reaching_definitions_by_insn(ins_addr, op_type)[源代码]
get_reaching_definitions_by_node(node_addr, op_type)[源代码]
node_observe(node_addr, state, op_type, node_idx=None)[源代码]
参数:
  • node_addr (int) -- Address of the node.

  • state (ReachingDefinitionsState) -- The analysis state.

  • op_type (ObservationPointType) -- Type of the observation point. Must be one of the following: OP_BEFORE, OP_AFTER.

  • node_idx (Optional[int]) -- ID of the node. Used in AIL to differentiate blocks with the same address.

返回类型:

None

insn_observe(insn_addr, stmt, block, state, op_type)[源代码]
参数:
返回类型:

None

stmt_observe(stmt_idx, stmt, block, state, op_type)[源代码]
参数:
返回类型:

None

返回:

exit_observe(node_addr, exit_stmt_idx, block, state, node_idx=None)[源代码]
参数:
property subject
callsites_to(target)[源代码]
返回类型:

Iterable[FunctionCallRelationships]

参数:

target (int | str | Function)

class angr.analyses.reaching_definitions.dep_graph.FunctionCallRelationships(callsite, target, args_defns, other_input_defns, ret_defns, other_output_defns)[源代码]

基类:object

参数:
callsite: CodeLocation
target: int | None
args_defns: list[set[Definition]]
other_input_defns: set[Definition]
ret_defns: set[Definition]
other_output_defns: set[Definition]
__init__(callsite, target, args_defns, other_input_defns, ret_defns, other_output_defns)
参数:
返回类型:

None

class angr.analyses.reaching_definitions.dep_graph.DepGraph(graph=None)[源代码]

基类:object

The representation of a dependency graph: a directed graph, where nodes are definitions, and edges represent uses.

Mostly a wrapper around a <networkx.DiGraph>.

参数:

graph (networkx.DiGraph[Definition] | None)

__init__(graph=None)[源代码]
参数:

graph -- A graph where nodes are definitions, and edges represent uses.

property graph: networkx.DiGraph[Definition]
add_node(node)[源代码]
参数:

node (Definition) -- The definition to add to the definition-use graph.

返回类型:

None

add_edge(source, destination, **labels)[源代码]

The edge to add to the definition-use graph. Will create nodes that are not yet present.

参数:
  • source (Definition) -- The "source" definition, used by the "destination".

  • destination (Definition) -- The "destination" definition, using the variable defined by "source".

  • labels -- Optional keyword arguments to represent edge labels.

返回类型:

None

nodes()[源代码]
返回类型:

NodeView[Definition]

predecessors(node)[源代码]
参数:

node (Definition) -- The definition to get the predecessors of.

返回类型:

Iterator[Definition]

transitive_closure(definition)[源代码]

Compute the "transitive closure" of a given definition. Obtained by transitively aggregating the ancestors of this definition in the graph.

Note: Each definition is memoized to avoid any kind of recomputation across the lifetime of this object.

参数:

definition -- The Definition to get transitive closure for.

返回:

A graph of the transitive closure of the given definition.

返回类型:

networkx.DiGraph[Definition[Atom]]

contains_atom(atom)[源代码]
返回类型:

bool

参数:

atom (Atom)

add_dependencies_for_concrete_pointers_of(values, definition, cfg, loader)[源代码]

When a given definition holds concrete pointers, make sure the <MemoryLocation>s they point to are present in the dependency graph; Adds them if necessary.

参数:
  • values (Iterable[Base | int])

  • definition (Definition) -- The definition which has data that can contain concrete pointers.

  • cfg (CFGModel | None) -- The CFG, containing information about memory data.

  • loader (Loader)

find_definitions(**kwargs)[源代码]

Filter the definitions present in the graph based on various criteria. Parameters can be any valid keyword args to DefinitionMatchPredicate

返回类型:

list[Definition]

find_all_predecessors(starts, **kwargs)[源代码]

Filter the ancestors of the given start node or nodes that match various criteria. Parameters can be any valid keyword args to DefinitionMatchPredicate

find_all_successors(starts, **kwargs)[源代码]

Filter the descendents of the given start node or nodes that match various criteria. Parameters can be any valid keyword args to DefinitionMatchPredicate

返回类型:

list[Definition]

参数:

starts (Definition | Iterable[Definition])

find_path(starts, ends, **kwargs)[源代码]

Find a path between the given start node or nodes and the given end node or nodes. All the intermediate steps in the path must match the criteria given in kwargs. The kwargs can be any valid parameters to DefinitionMatchPredicate.

This algorithm has exponential time and space complexity. Use at your own risk. Want to do better? Do it yourself or use networkx and eat the cost of indirection and/or cloning.

返回类型:

tuple[Definition, ...] | None

参数:
find_paths(starts, ends, **kwargs)[源代码]

Find all non-overlapping simple paths between the given start node or nodes and the given end node or nodes. All the intermediate steps in the path must match the criteria given in kwargs. The kwargs can be any valid parameters to DefinitionMatchPredicate.

This algorithm has exponential time and space complexity. Use at your own risk. Want to do better? Do it yourself or use networkx and eat the cost of indirection and/or cloning.

返回类型:

Iterator[tuple[Definition, ...]]

参数:
class angr.analyses.reaching_definitions.heap_allocator.HeapAllocator(canonical_size)[源代码]

基类:object

A simple modelisation to help represent heap memory management during a <ReachingDefinitionsAnalysis>: - Act as if allocations were always done in consecutive memory segments; - Take care of the size not to screw potential pointer arithmetic (avoid overlapping segments).

The content of the heap itself is modeled using a <KeyedRegion> attribute in the <LiveDefinitions> state; This class serves to generate consistent heap addresses to be used by the aforementioned.

Note: This has NOT been made to help detect heap vulnerabilities.

参数:

canonical_size (int)

__init__(canonical_size)[源代码]
参数:

canonical_size (int) -- The concrete size an <UNKNOWN_SIZE> defaults to.

allocate(size)[源代码]

Gives an address for a new memory chunk of <size> bytes.

参数:

size (int | UnknownSize) -- The requested size for the chunk, in number of bytes.

返回类型:

HeapAddress

返回:

The address of the chunk.

free(address)[源代码]

Mark the chunk pointed by <address> as freed.

参数:

address (Undefined | HeapAddress) -- The address of the chunk to free.

property allocated_addresses

The list of addresses that are currently allocated on the heap.

Type:

return

angr.analyses.reaching_definitions.function_handler.get_exit_livedefinitions(func, rda_model)[源代码]

Get LiveDefinitions at all exits of a function, merge them, and return.

参数:
class angr.analyses.reaching_definitions.function_handler.FunctionEffect(dest, sources, value=None, sources_defns=None, apply_at_callsite=False, tags=None)[源代码]

基类:object

A single effect that a function summary may apply to the state. This is largely an implementation detail; use FunctionCallData.depends instead.

参数:
dest: Atom | None
sources: set[Atom]
value: MultiValues | None = None
sources_defns: set[Definition] | None = None
apply_at_callsite: bool = False
tags: set[Tag] | None = None
__init__(dest, sources, value=None, sources_defns=None, apply_at_callsite=False, tags=None)
参数:
返回类型:

None

class angr.analyses.reaching_definitions.function_handler.FunctionCallData(callsite_codeloc, function_codeloc, address_multi, address=None, symbol=None, function=None, name=None, cc=None, prototype=None, args_atoms=None, args_values=None, ret_atoms=None, redefine_locals=True, visited_blocks=None, effects=<factory>, ret_values=None, ret_values_deps=None, caller_will_handle_single_ret=False, guessed_cc=False, guessed_prototype=False, retaddr_popped=False)[源代码]

基类:object

A bundle of intermediate data used when computing the sum effect of a function during ReachingDefinitionsAnalysis.

RDA engine contract:

  • Construct one of these before calling FunctionHandler.handle_function. Fill it with as many fields as you can realistically provide without duplicating effort.

  • Provide callsite_codeloc as either the call statement (AIL) or the default exit of the default statement of the calling block (VEX)

  • Provide function_codeloc as the callee address with stmt_idx=0`.

Function handler contract:

  • If redefine_locals is unset, do not adjust any artifacts of the function call abstraction, such as the stack pointer, the caller saved registers, etc.

  • If caller_will_handle_single_ret is set, and there is a single entry in ret_atoms, do not apply to the state effects modifying this atom. Instead, set ret_values and ret_values_deps to the values and deps which are used constructing these values.

参数:
callsite_codeloc: CodeLocation
function_codeloc: CodeLocation
address_multi: Optional[MultiValues[BV | FP]]
address: int | None = None
symbol: Symbol | None = None
function: Function | None = None
name: str | None = None
cc: SimCC | None = None
prototype: SimTypeFunction | None = None
args_atoms: list[set[Atom]] | None = None
args_values: list[MultiValues[BV | FP]] | None = None
ret_atoms: set[Atom] | None = None
redefine_locals: bool = True
visited_blocks: set[int] | None = None
effects: list[FunctionEffect]
ret_values: Optional[MultiValues[BV | FP]] = None
ret_values_deps: set[Definition] | None = None
caller_will_handle_single_ret: bool = False
guessed_cc: bool = False
guessed_prototype: bool = False
retaddr_popped: bool = False
has_clobbered(dest)[源代码]

Determines whether the given atom already has effects applied

返回类型:

bool

参数:

dest (Atom)

depends(dest, *sources, value=None, apply_at_callsite=False, tags=None)[源代码]

Mark a single effect of the current function, including the atom being modified, the input atoms on which that output atom depends, the precise (or imprecise!) value to store, and whether the effect should be applied during the function or afterwards, at the callsite.

The tags are used to annotate the Definition of the Atom that will be created, when the function effects are applied to the state.

The atom being modified may be None to mark uses of the source atoms which do not have any explicit sinks.

参数:
reset_prototype(prototype, state, soft_reset=False)[源代码]
返回类型:

set[Atom]

参数:
__init__(callsite_codeloc, function_codeloc, address_multi, address=None, symbol=None, function=None, name=None, cc=None, prototype=None, args_atoms=None, args_values=None, ret_atoms=None, redefine_locals=True, visited_blocks=None, effects=<factory>, ret_values=None, ret_values_deps=None, caller_will_handle_single_ret=False, guessed_cc=False, guessed_prototype=False, retaddr_popped=False)
参数:
返回类型:

None

class angr.analyses.reaching_definitions.function_handler.FunctionCallDataUnwrapped(inner)[源代码]

基类:FunctionCallData

A subclass of FunctionCallData which asserts that many of its members are non-None at construction time. Typechecks be gone!

参数:

inner (FunctionCallData)

address_multi: MultiValues
__init__(inner)[源代码]
参数:

inner (FunctionCallData)

static decorate(wrapper, *, wrapped=<function FunctionCallDataUnwrapped.decorate>, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__', ))

Update a wrapper function to look like the wrapped function

wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes of the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES)

class angr.analyses.reaching_definitions.function_handler.FunctionHandler(interfunction_level=0, extra_impls=None)[源代码]

基类:object

A mechanism for summarizing a function call's effect on a program for ReachingDefinitionsAnalysis.

参数:
__init__(interfunction_level=0, extra_impls=None)[源代码]
参数:
hook(analysis)[源代码]

Attach this instance of the function handler to an instance of RDA.

返回类型:

FunctionHandler

参数:

analysis (ReachingDefinitionsAnalysis)

make_function_codeloc(target, callsite, callsite_func_addr)[源代码]

The RDA engine will call this function to transform a callsite CodeLocation into a callee CodeLocation.

参数:
handle_function(state, data)[源代码]

The main entry point for the function handler. Called with a RDA state and a FunctionCallData, it is expected to update the state and the data as per the contracts described on FunctionCallData.

You can override this method to take full control over how data is processed, or override any of the following to use the higher-level interface (data.depends()):

  • handle_impl_<function name> - used for <function name>.

  • handle_local_function - used for any function (excluding plt stubs) whose address is inside the main binary.

  • handle_external_function - used for any function or plt stub whose address is outside the main binary.

  • handle_indirect_function - used for any function whose target cannot be resolved.

  • handle_generic_function - used as a default if none of the above are overridden.

Each of them take the same signature as handle_function.

参数:
handle_generic_function(state, data)[源代码]
参数:
handle_indirect_function(state, data)[源代码]
返回类型:

None

参数:
handle_local_function(state, data)[源代码]
返回类型:

None

参数:
handle_external_function(state, data)[源代码]
返回类型:

None

参数:
recurse_analysis(state, data)[源代码]

Precondition: data.function MUST NOT BE NONE in order to call this method.

返回类型:

None

参数:
static c_args_as_atoms(state, cc, prototype)[源代码]
返回类型:

list[set[Atom]]

参数:
static c_return_as_atoms(state, cc, prototype)[源代码]
返回类型:

set[Atom]

参数:
static caller_saved_regs_as_atoms(state, cc)[源代码]
返回类型:

set[Register]

参数:
static stack_pointer_as_atom(state)[源代码]
返回类型:

Register

class angr.analyses.reaching_definitions.rd_state.ReachingDefinitionsState(codeloc, arch, subject, analysis, track_tmps=False, track_consts=False, rtoc_value=None, live_definitions=None, canonical_size=8, heap_allocator=None, environment=None, sp_adjusted=False, all_definitions=None, initializer=None, element_limit=5, merge_into_tops=True)[源代码]

基类:object

Represents the internal state of the ReachingDefinitionsAnalysis.

It contains a data class LiveDefinitions, which stores both definitions and uses for register, stack, memory, and temporary variables, uncovered during the analysis.

参数:
  • subject (Subject) -- The subject being analyzed.

  • track_tmps (bool) -- Only tells whether or not temporary variables should be taken into consideration when representing the state of the analysis. Should be set to true when the analysis has counted uses and definitions for temporary variables, false otherwise.

  • analysis (ReachingDefinitionsAnalysis) -- The analysis that generated the state represented by this object.

  • rtoc_value -- When the targeted architecture is ppc64, the initial function needs to know the rtoc_value.

  • live_definitions (Optional[LiveDefinitions])

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

  • heap_allocator (Optional[HeapAllocator]) -- Mechanism to model the management of heap memory.

  • environment (Optional[Environment]) -- Representation of the environment of the analyzed program.

  • codeloc (CodeLocation)

  • arch (Arch)

  • track_consts (bool)

  • sp_adjusted (bool)

  • all_definitions (set[Definition[Any]])

  • initializer (RDAStateInitializer | None)

  • element_limit (int)

  • merge_into_tops (bool)

变量:

arch -- The architecture targeted by the program.

__init__(codeloc, arch, subject, analysis, track_tmps=False, track_consts=False, rtoc_value=None, live_definitions=None, canonical_size=8, heap_allocator=None, environment=None, sp_adjusted=False, all_definitions=None, initializer=None, element_limit=5, merge_into_tops=True)[源代码]
参数:
codeloc
arch: Arch
analysis
all_definitions: set[Definition[Any]]
heap_allocator
codeloc_uses: set[Definition[Any]]
exit_observed: bool
live_definitions
top(bits)[源代码]
参数:

bits (int)

is_top(*args)[源代码]
heap_address(offset)[源代码]
返回类型:

BV

参数:

offset (int | HeapAddress)

static is_heap_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

static get_heap_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

stack_address(offset)[源代码]
返回类型:

BV

参数:

offset (int)

is_stack_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

get_stack_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Base)

annotate_with_def(symvar, definition)[源代码]
参数:
返回类型:

TypeVar(MVType, bound= BV | FP)

返回:

annotate_mv_with_def(mv, definition)[源代码]
返回类型:

MultiValues[TypeVar(MVType, bound= BV | FP)]

参数:
extract_defs(symvar)[源代码]
返回类型:

Iterator[Definition[Any]]

参数:

symvar (Base)

property tmps
property tmp_uses
property register_uses
property registers: MultiValuedMemory
property stack: MultiValuedMemory
property stack_uses
property heap: MultiValuedMemory
property heap_uses
property memory_uses
property memory: MultiValuedMemory
property uses_by_codeloc
get_sp()[源代码]
返回类型:

int

get_stack_address(offset)[源代码]
返回类型:

int | None

参数:

offset (Base)

property environment
property dep_graph
copy(discard_tmpdefs=False)[源代码]
返回类型:

Self

merge(*others)[源代码]
返回类型:

tuple[Self, bool]

参数:

others (Self)

compare(other)[源代码]
返回类型:

bool

参数:

other (ReachingDefinitionsState)

move_codelocs(new_codeloc)[源代码]
返回类型:

None

参数:

new_codeloc (CodeLocation)

kill_definitions(atom)[源代码]

Overwrite existing definitions w.r.t 'atom' with a dummy definition instance. A dummy definition will not be removed during simplification.

返回类型:

None

参数:

atom (Atom)

kill_and_add_definition(atom, data, dummy=False, tags=None, endness=None, annotated=False, uses=None, override_codeloc=None)[源代码]
返回类型:

tuple[MultiValues | None, set[Definition[TypeVar(A, bound= Atom)]]]

参数:
add_use(atom, expr=None)[源代码]
返回类型:

None

参数:
add_use_by_def(definition, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use(tmp, expr=None)[源代码]
返回类型:

None

参数:
add_tmp_use_by_defs(defs, expr=None)[源代码]
返回类型:

None

参数:
add_register_use(reg_offset, size, expr=None)[源代码]
返回类型:

None

参数:
  • reg_offset (int)

  • size (int)

  • expr (Any | None)

add_register_use_by_defs(defs, expr=None)[源代码]
返回类型:

None

参数:
add_stack_use(stack_offset, size, expr=None)[源代码]
返回类型:

None

参数:
  • stack_offset (int)

  • size (int)

  • expr (Any | None)

add_stack_use_by_defs(defs, expr=None)[源代码]
参数:
add_heap_use(heap_offset, size, expr=None)[源代码]
返回类型:

None

参数:
  • heap_offset (int)

  • size (int)

  • expr (Any | None)

add_heap_use_by_defs(defs, expr=None)[源代码]
参数:
add_memory_use_by_def(definition, expr=None)[源代码]
参数:
add_memory_use_by_defs(defs, expr=None)[源代码]
参数:
get_definitions(atom)[源代码]
返回类型:

set[Definition[Atom]]

参数:

atom (Atom | Definition[Atom] | Iterable[Atom] | Iterable[Definition[Atom]])

get_values(spec)[源代码]
返回类型:

MultiValues | None

参数:

spec (A | Definition[A] | Iterable[A])

get_one_value(spec, strip_annotations=False)[源代码]
返回类型:

BV | None

参数:
get_concrete_value(spec, cast_to=<class 'int'>)[源代码]
返回类型:

int | bytes | None

参数:
mark_guard(target)[源代码]
mark_const(value, size)[源代码]
参数:
downsize()[源代码]
pointer_to_atoms(**kwargs)
pointer_to_atom(**kwargs)
deref(pointer, size, endness=Endness.BE)[源代码]
参数:
class angr.analyses.reaching_definitions.subject.SubjectType(value)[源代码]

基类:Enum

An enumeration.

Function = 1
Block = 2
CallTrace = 3
class angr.analyses.reaching_definitions.subject.Subject(content, func_graph=None, cc=None)[源代码]

基类:object

__init__(content, func_graph=None, cc=None)[源代码]

The thing being analysed, and the way (visitor) to analyse it.

参数:
  • content (Union[ailment.Block, angr.Block, Function]) -- Thing to be analysed.

  • func_graph (networkx.DiGraph) -- Alternative graph for function.graph.

  • cc (SimCC) -- Calling convention of the function.

property cc
property content
property func_graph
property type
property visitor: FunctionGraphVisitor | SingleNodeGraphVisitor
class angr.analyses.reaching_definitions.engine_ail.SimEngineRDAIL(project, function_handler, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, bp_as_gpr=False)[源代码]

基类:SimEngineNostmtAIL[ReachingDefinitionsState, MultiValues[BV | FP], None, ReachingDefinitionsState]

参数:
__init__(project, function_handler, stack_pointer_tracker=None, use_callee_saved_regs_at_return=True, bp_as_gpr=False)[源代码]
参数:
process(state, *, dep_graph=None, visited_blocks=None, block=None, fail_fast=False, whitelist=None, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:

state -- The state to proceed from

返回:

The result. Whatever you want ;)

class angr.analyses.cfg_slice_to_sink.CFGSliceToSink(target, transitions=None)[源代码]

基类:object

The representation of a slice of a CFG.

__init__(target, transitions=None)[源代码]
参数:
  • target (angr.knowledge_plugins.functions.function.Function) -- The targeted sink, to which every path in the slice leads.

  • transitions (Dict[int,List[int]]) -- A mapping representing transitions in the graph. Indexes are source addresses and values a list of destination addresses, for which there exists a transition in the slice from source to destination.

property transitions

The transitions in the slice.

Type:

return Dict[int,List[int]]

property transitions_as_tuples

The list of transitions as pairs of (source, destination).

Type:

return List[Tuple[int,int]]

property target

return angr.knowledge_plugins.functions.function.Function: The targeted sink function, from which the slice is constructed.

property nodes: list[int]

The complete list of addresses present in the slice.

Type:

return

property entrypoints

Entrypoints are all source addresses that are not the destination address of any transition.

Return List[int]:

The list of entrypoints addresses.

add_transitions(transitions)[源代码]

Add the given transitions to the current slice.

参数:

transitions (Dict[int,List[int]]) -- The list of transitions to be added to self.transitions.

Return Dict[int,List[int]]:

Return the updated list of transitions.

is_empty()[源代码]

Test if a given slice does not contain any transition.

Return bool:

True if the <CFGSliceToSink> instance does not contain any transitions. False otherwise.

path_between(source, destination, visited=None)[源代码]

Check the existence of a path in the slice between two given node addresses.

参数:
  • source (int) -- The source address.

  • destination (int) -- The destination address.

  • visited (Optional[set[Any]]) -- Used to avoid infinite recursion if loops are present in the slice.

返回类型:

bool

返回:

True if there is a path between the source and the destination in the CFG, False if not, or if we have been unable to decide (because of loops).

angr.analyses.cfg_slice_to_sink.slice_callgraph(callgraph, cfg_slice_to_sink)[源代码]

Slice a callgraph, keeping only the nodes present in the <CFGSliceToSink> representation, and th transitions for which a path exists.

Note that this function mutates the graph passed as an argument.

参数:
  • callgraph (networkx.MultiDiGraph) -- The callgraph to update.

  • cfg_slice_to_sink (CFGSliceToSink) -- The representation of the slice, containing the data to update the callgraph from.

angr.analyses.cfg_slice_to_sink.slice_cfg_graph(graph, cfg_slice_to_sink)[源代码]

Slice a CFG graph, keeping only the transitions and nodes present in the <CFGSliceToSink> representation.

Note that this function mutates the graph passed as an argument.

参数:
  • graph (networkx.DiGraph) -- The graph to slice.

  • cfg_slice_to_sink (CFGSliceToSink) -- The representation of the slice, containing the data to update the CFG from.

Return networkx.DiGraph:

The sliced graph.

angr.analyses.cfg_slice_to_sink.slice_function_graph(function_graph, cfg_slice_to_sink)[源代码]

Slice a function graph, keeping only the nodes present in the <CFGSliceToSink> representation.

Because the <CFGSliceToSink> is build from the CFG, and the function graph is NOT a subgraph of the CFG, edges of the function graph will no be present in the <CFGSliceToSink> transitions. However, we use the fact that if there is an edge between two nodes in the function graph, then there must exist a path between these two nodes in the slice; Proof idea: - The <CFGSliceToSink> is backward and recursively constructed; - If a node is in the slice, then all its predecessors will be (transitively); - If there is an edge between two nodes in the function graph, there is a path between them in the CFG; - So: The origin node is a transitive predecessor of the destination one, hence if destination is in the slice, then origin will be too.

In consequence, in the end, removing the only nodes not present in the slice, and their related transitions gives us the expected result: a function graph representing (a higher view of) the flow in the slice.

Note that this function mutates the graph passed as an argument.

参数:
  • graph (networkx.DiGraph) -- The graph to slice.

  • cfg_slice_to_sink (CFGSliceToSink) -- The representation of the slice, containing the data to update the CFG from.

Return networkx.DiGraph:

The sliced graph.

class angr.analyses.cfg_slice_to_sink.cfg_slice_to_sink.CFGSliceToSink(target, transitions=None)[源代码]

基类:object

The representation of a slice of a CFG.

__init__(target, transitions=None)[源代码]
参数:
  • target (angr.knowledge_plugins.functions.function.Function) -- The targeted sink, to which every path in the slice leads.

  • transitions (Dict[int,List[int]]) -- A mapping representing transitions in the graph. Indexes are source addresses and values a list of destination addresses, for which there exists a transition in the slice from source to destination.

property transitions

The transitions in the slice.

Type:

return Dict[int,List[int]]

property transitions_as_tuples

The list of transitions as pairs of (source, destination).

Type:

return List[Tuple[int,int]]

property target

return angr.knowledge_plugins.functions.function.Function: The targeted sink function, from which the slice is constructed.

property nodes: list[int]

The complete list of addresses present in the slice.

Type:

return

property entrypoints

Entrypoints are all source addresses that are not the destination address of any transition.

Return List[int]:

The list of entrypoints addresses.

add_transitions(transitions)[源代码]

Add the given transitions to the current slice.

参数:

transitions (Dict[int,List[int]]) -- The list of transitions to be added to self.transitions.

Return Dict[int,List[int]]:

Return the updated list of transitions.

is_empty()[源代码]

Test if a given slice does not contain any transition.

Return bool:

True if the <CFGSliceToSink> instance does not contain any transitions. False otherwise.

path_between(source, destination, visited=None)[源代码]

Check the existence of a path in the slice between two given node addresses.

参数:
  • source (int) -- The source address.

  • destination (int) -- The destination address.

  • visited (Optional[set[Any]]) -- Used to avoid infinite recursion if loops are present in the slice.

返回类型:

bool

返回:

True if there is a path between the source and the destination in the CFG, False if not, or if we have been unable to decide (because of loops).

angr.analyses.cfg_slice_to_sink.graph.slice_callgraph(callgraph, cfg_slice_to_sink)[源代码]

Slice a callgraph, keeping only the nodes present in the <CFGSliceToSink> representation, and th transitions for which a path exists.

Note that this function mutates the graph passed as an argument.

参数:
  • callgraph (networkx.MultiDiGraph) -- The callgraph to update.

  • cfg_slice_to_sink (CFGSliceToSink) -- The representation of the slice, containing the data to update the callgraph from.

angr.analyses.cfg_slice_to_sink.graph.slice_cfg_graph(graph, cfg_slice_to_sink)[源代码]

Slice a CFG graph, keeping only the transitions and nodes present in the <CFGSliceToSink> representation.

Note that this function mutates the graph passed as an argument.

参数:
  • graph (networkx.DiGraph) -- The graph to slice.

  • cfg_slice_to_sink (CFGSliceToSink) -- The representation of the slice, containing the data to update the CFG from.

Return networkx.DiGraph:

The sliced graph.

angr.analyses.cfg_slice_to_sink.graph.slice_function_graph(function_graph, cfg_slice_to_sink)[源代码]

Slice a function graph, keeping only the nodes present in the <CFGSliceToSink> representation.

Because the <CFGSliceToSink> is build from the CFG, and the function graph is NOT a subgraph of the CFG, edges of the function graph will no be present in the <CFGSliceToSink> transitions. However, we use the fact that if there is an edge between two nodes in the function graph, then there must exist a path between these two nodes in the slice; Proof idea: - The <CFGSliceToSink> is backward and recursively constructed; - If a node is in the slice, then all its predecessors will be (transitively); - If there is an edge between two nodes in the function graph, there is a path between them in the CFG; - So: The origin node is a transitive predecessor of the destination one, hence if destination is in the slice, then origin will be too.

In consequence, in the end, removing the only nodes not present in the slice, and their related transitions gives us the expected result: a function graph representing (a higher view of) the flow in the slice.

Note that this function mutates the graph passed as an argument.

参数:
  • graph (networkx.DiGraph) -- The graph to slice.

  • cfg_slice_to_sink (CFGSliceToSink) -- The representation of the slice, containing the data to update the CFG from.

Return networkx.DiGraph:

The sliced graph.

Some utilitary functions to manage our representation of transitions:

A dictionary, indexed by int (source addresses), which values are list of ints (target addresses).

angr.analyses.cfg_slice_to_sink.transitions.merge_transitions(transitions, existing_transitions)[源代码]

Merge two dictionaries of transitions together.

参数:
  • transitions (Dict[int,List[int]]) -- Some transitions.

  • existing_transitions (Dict[int,List[int]]) -- Other transitions.

Return Dict[int,List[int]]:

The merge of the two parameters.

class angr.analyses.stack_pointer_tracker.BottomType[源代码]

基类:object

The bottom value for register values.

class angr.analyses.stack_pointer_tracker.Constant(val)[源代码]

基类:object

Represents a constant value.

__init__(val)[源代码]
val
class angr.analyses.stack_pointer_tracker.Register(offset, bitlen)[源代码]

基类:object

Represent a register.

__init__(offset, bitlen)[源代码]
offset
bitlen
class angr.analyses.stack_pointer_tracker.OffsetVal(reg, offset)[源代码]

基类:object

Represent a value with an offset added.

__init__(reg, offset)[源代码]
property reg
property offset
class angr.analyses.stack_pointer_tracker.Eq(val0, val1)[源代码]

基类:object

Represent an equivalence condition.

__init__(val0, val1)[源代码]
val0
val1
class angr.analyses.stack_pointer_tracker.FrozenStackPointerTrackerState(regs, memory, is_tracking_memory, resilient)[源代码]

基类:object

Abstract state for StackPointerTracker analysis with registers and memory values being in frozensets.

__init__(regs, memory, is_tracking_memory, resilient)[源代码]
regs
memory
is_tracking_memory
resilient
unfreeze()[源代码]
merge(other, addr, reg_merge_cache, mem_merge_cache)[源代码]
参数:
class angr.analyses.stack_pointer_tracker.StackPointerTrackerState(regs, memory, is_tracking_memory, resilient)[源代码]

基类:object

Abstract state for StackPointerTracker analysis.

参数:

resilient (bool)

__init__(regs, memory, is_tracking_memory, resilient)[源代码]
参数:

resilient (bool)

regs
memory
is_tracking_memory
resilient
give_up_on_memory_tracking()[源代码]
store(addr, val)[源代码]
load(addr)[源代码]
get(reg)[源代码]
put(reg, val, force=False)[源代码]
参数:

force (bool)

copy()[源代码]
freeze()[源代码]
merge(other, addr, reg_merge_cache, mem_merge_cache)[源代码]
参数:
exception angr.analyses.stack_pointer_tracker.CouldNotResolveException[源代码]

基类:Exception

An exception used in StackPointerTracker analysis to represent internal resolving failures.

class angr.analyses.stack_pointer_tracker.StackPointerTracker(func, reg_offsets, block=None, track_memory=True, cross_insn_opt=True, initial_reg_values=None, resilient=True)[源代码]

基类:Analysis, ForwardAnalysis

Track the offset of stack pointer at the end of each basic block of a function.

参数:
__init__(func, reg_offsets, block=None, track_memory=True, cross_insn_opt=True, initial_reg_values=None, resilient=True)[源代码]
参数:
offset_after(addr, reg)[源代码]
offset_before(addr, reg)[源代码]
offset_after_block(block_addr, reg)[源代码]
offset_before_block(block_addr, reg)[源代码]
constant_after(addr, reg)[源代码]
constant_before(addr, reg)[源代码]
constant_after_block(block_addr, reg)[源代码]
constant_before_block(block_addr, reg)[源代码]
property inconsistent
inconsistent_for(reg)[源代码]
offsets_for(reg)[源代码]
class angr.analyses.variable_recovery.annotations.StackLocationAnnotation(offset)[源代码]

基类:Annotation

__init__(offset)[源代码]
property eliminatable

Returns whether this annotation can be eliminated in a simplification.

返回:

True if eliminatable, False otherwise

property relocatable

Returns whether this annotation can be relocated in a simplification.

返回:

True if it can be relocated, false otherwise.

class angr.analyses.variable_recovery.annotations.VariableSourceAnnotation(block_addr, stmt_idx, ins_addr)[源代码]

基类:Annotation

__init__(block_addr, stmt_idx, ins_addr)[源代码]
property eliminatable

Returns whether this annotation can be eliminated in a simplification.

返回:

True if eliminatable, False otherwise

property relocatable

Returns whether this annotation can be relocated in a simplification.

返回:

True if it can be relocated, false otherwise.

static from_state(state)[源代码]
angr.analyses.variable_recovery.variable_recovery_base.parse_stack_pointer(sp)[源代码]

Convert multiple supported forms of stack pointer representations into stack offsets.

参数:

sp -- A stack pointer representation.

返回:

A stack pointer offset.

返回类型:

int

class angr.analyses.variable_recovery.variable_recovery_base.VariableAnnotation(addr_and_variables)[源代码]

基类:Annotation

参数:

addr_and_variables (list[tuple[int, SimVariable]])

__init__(addr_and_variables)[源代码]
参数:

addr_and_variables (list[tuple[int, SimVariable]])

addr_and_variables
property relocatable

Returns whether this annotation can be relocated in a simplification.

返回:

True if it can be relocated, false otherwise.

property eliminatable

Returns whether this annotation can be eliminated in a simplification.

返回:

True if eliminatable, False otherwise

class angr.analyses.variable_recovery.variable_recovery_base.VariableRecoveryBase(func, max_iterations, store_live_variables, vvar_to_vvar=None)[源代码]

基类:Analysis

The base class for VariableRecovery and VariableRecoveryFast.

参数:
__init__(func, max_iterations, store_live_variables, vvar_to_vvar=None)[源代码]
参数:
get_variable_definitions(block_addr)[源代码]

Get variables that are defined at the specified block.

参数:

block_addr (int) -- Address of the block.

返回:

A set of variables.

initialize_dominance_frontiers()[源代码]
class angr.analyses.variable_recovery.variable_recovery_base.VariableRecoveryStateBase(block_addr, analysis, arch, func, project, stack_region=None, register_region=None, global_region=None, typevars=None, type_constraints=None, func_typevar=None, delayed_type_constraints=None, stack_offset_typevars=None)[源代码]

基类:object

The base abstract state for variable recovery analysis.

参数:
__init__(block_addr, analysis, arch, func, project, stack_region=None, register_region=None, global_region=None, typevars=None, type_constraints=None, func_typevar=None, delayed_type_constraints=None, stack_offset_typevars=None)[源代码]
参数:
static top(bits)[源代码]
返回类型:

BV

static is_top(thing)[源代码]
返回类型:

bool

static extract_variables(expr)[源代码]
返回类型:

Generator[tuple[int, SimVariable]]

参数:

expr (Base)

static annotate_with_variables(expr, addr_and_variables)[源代码]
返回类型:

TypeVar(AnyClaripy, bound= Base)

参数:
stack_address(offset)[源代码]
返回类型:

BV

参数:

offset (int)

static is_stack_address(addr)[源代码]
返回类型:

bool

参数:

addr (Base)

is_global_variable_address(addr)[源代码]
返回类型:

bool

参数:

addr (Bits)

get_stack_offset(addr)[源代码]
返回类型:

int | None

参数:

addr (Bits)

stack_addr_from_offset(offset)[源代码]
返回类型:

int

参数:

offset (int)

property func_addr
property dominance_frontiers
property variable_manager
property variables
get_variable_definitions(block_addr)[源代码]

Get variables that are defined at the specified block.

参数:

block_addr (int) -- Address of the block.

返回:

A set of variables.

add_type_constraint(constraint)[源代码]

Add a new type constraint.

参数:

constraint

返回:

add_type_constraint_for_function(func_typevar, constraint)[源代码]

Add a new type constraint for a specified function.

参数:
  • func_typevar

  • constraint

返回:

downsize()[源代码]

Remove unnecessary members.

返回类型:

None

返回:

None

static downsize_region(region)[源代码]

Get rid of unnecessary references in region so that it won't avoid garbage collection on those referenced objects.

参数:

region (MultiValuedMemory) -- A MultiValuedMemory region.

返回类型:

MultiValuedMemory

返回:

None

class angr.analyses.variable_recovery.variable_recovery_fast.VariableRecoveryFastState(block_addr, analysis, arch, func, stack_region=None, register_region=None, global_region=None, typevars=None, type_constraints=None, func_typevar=None, delayed_type_constraints=None, stack_offset_typevars=None, project=None, ret_val_size=None)[源代码]

基类:VariableRecoveryStateBase

The abstract state of variable recovery analysis.

变量:
__init__(block_addr, analysis, arch, func, stack_region=None, register_region=None, global_region=None, typevars=None, type_constraints=None, func_typevar=None, delayed_type_constraints=None, stack_offset_typevars=None, project=None, ret_val_size=None)[源代码]
copy()[源代码]
merge(others, successor=None)[源代码]

Merge two abstract states.

For any node A whose dominance frontier that the current node (at the current program location) belongs to, we create a phi variable V' for each variable V that is defined in A, and then replace all existence of V with V' in the merged abstract state.

参数:

others (tuple[VariableRecoveryFastState]) -- Other abstract states to merge.

返回类型:

tuple[VariableRecoveryFastState, bool]

返回:

The merged abstract state.

downsize()[源代码]

Remove unnecessary members.

返回类型:

None

返回:

None

class angr.analyses.variable_recovery.variable_recovery_fast.VariableRecoveryFast(func, func_graph=None, max_iterations=2, low_priority=False, track_sp=True, func_args=None, store_live_variables=False, unify_variables=True, func_arg_vvars=None, vvar_to_vvar=None)[源代码]

基类:ForwardAnalysis, VariableRecoveryBase

Recover "variables" from a function by keeping track of stack pointer offsets and pattern matching VEX statements.

If calling conventions are recovered prior to running VariableRecoveryFast, variables can be recognized more accurately. However, it is not a requirement. In this case, the function graph you pass must contain information indicating the call-out sites inside the analyzed function. These graph edges must be annotated with either "type": "call" or "outside": True.

参数:
__init__(func, func_graph=None, max_iterations=2, low_priority=False, track_sp=True, func_args=None, store_live_variables=False, unify_variables=True, func_arg_vvars=None, vvar_to_vvar=None)[源代码]

Constructor

参数:
返回:

None

class angr.analyses.variable_recovery.variable_recovery.VariableRecoveryState(project, block_addr, analysis, arch, func, concrete_states, stack_region=None, register_region=None)[源代码]

基类:VariableRecoveryStateBase

The abstract state of variable recovery analysis.

变量:

variable_manager (angr.knowledge.variable_manager.VariableManager) -- The variable manager.

参数:
__init__(project, block_addr, analysis, arch, func, concrete_states, stack_region=None, register_region=None)[源代码]
参数:
property concrete_states
get_concrete_state(addr)[源代码]
参数:

addr

返回:

copy()[源代码]
register_callbacks(concrete_states)[源代码]
参数:

concrete_states

返回:

merge(others, successor=None)[源代码]

Merge two abstract states.

参数:

others (tuple[VariableRecoveryState, ...]) -- Other abstract states to merge.

返回:

The merged abstract state.

返回类型:

VariableRecoveryState, and a boolean that indicates if any merge has happened.

class angr.analyses.variable_recovery.variable_recovery.VariableRecovery(func, max_iterations=20, store_live_variables=False)[源代码]

基类:ForwardAnalysis, VariableRecoveryBase

Recover "variables" from a function using forced execution.

While variables play a very important role in programming, it does not really exist after compiling. However, we can still identify and recovery their counterparts in binaries. It is worth noting that not every variable in source code can be identified in binaries, and not every recognized variable in binaries have a corresponding variable in the original source code. In short, there is no guarantee that the variables we identified/recognized in a binary are the same variables in its source code.

This analysis uses heuristics to identify and recovers the following types of variables: - Register variables. - Stack variables. - Heap variables. (not implemented yet) - Global variables. (not implemented yet)

This analysis takes a function as input, and performs a data-flow analysis on nodes. It runs concrete execution on every statement and hooks all register/memory accesses to discover all places that are accessing variables. It is slow, but has a more accurate analysis result. For a fast but inaccurate variable recovery, you may consider using VariableRecoveryFast.

This analysis follows SSA, which means every write creates a new variable in registers or memory (statck, heap, etc.). Things may get tricky when overlapping variable (in memory, as you cannot really have overlapping accesses to registers) accesses exist, and in such cases, a new variable will be created, and this new variable will overlap with one or more existing variables. A decision procedure (which is pretty much TODO) is required at the end of this analysis to resolve the conflicts between overlapping variables.

__init__(func, max_iterations=20, store_live_variables=False)[源代码]
参数:

func (knowledge.Function) -- The function to analyze.

class angr.analyses.variable_recovery.engine_ail.SimEngineVRAIL(*args, call_info=None, vvar_to_vvar, **kwargs)[源代码]

基类:SimEngineNostmtAIL[VariableRecoveryFastState, RichR[BV | FP], None, None], SimEngineVRBase[VariableRecoveryFastState, Block]

The engine for variable recovery on AIL.

参数:

vvar_to_vvar (dict[int, int] | None)

__init__(*args, call_info=None, vvar_to_vvar, **kwargs)[源代码]
参数:

vvar_to_vvar (dict[int, int] | None)

class angr.analyses.variable_recovery.engine_vex.SimEngineVRVEX(*args, call_info=None, **kwargs)[源代码]

基类:SimEngineNostmtVEX[VariableRecoveryFastState, RichR[BV | FP], None], SimEngineVRBase[VariableRecoveryFastState, Block]

Implements the VEX engine for variable recovery analysis.

reg_read_stmts_to_ignore: set[int]
stmts_to_lower: set[int]
__init__(*args, call_info=None, **kwargs)[源代码]
class angr.analyses.variable_recovery.engine_base.RichR(data, variable=None, typevar=None, type_constraints=None)[源代码]

基类:Generic[RichRT_co]

A rich representation of calculation results. The variable recovery data domain.

参数:
__init__(data, variable=None, typevar=None, type_constraints=None)[源代码]
参数:
data
variable
typevar
type_constraints
property bits: int
class angr.analyses.variable_recovery.engine_base.SimEngineVRBase(project, kb)[源代码]

基类:Generic[VRStateType, BlockType], SimEngineLight[VRStateType, RichR[BV | FP], BlockType, None]

The base class for variable recovery analyses. Contains methods for basic interactions with the state, like loading and storing data.

variable_manager: VariableManager
__init__(project, kb)[源代码]
property func_addr
process(state, *args, **kwargs)[源代码]

The main entry point for an engine. Should take a state and return a result.

参数:

state -- The state to proceed from

返回:

The result. Whatever you want ;)

class angr.analyses.variable_recovery.irsb_scanner.VEXIRSBScanner(*args, **kwargs)[源代码]

基类:SimEngineLightVEX[None, None, None, None]

Scan the VEX IRSB to determine if any argument-passing registers should be narrowed by detecting cases of loading the whole register and immediately narrowing the register before writing to the tmp.

__init__(*args, **kwargs)[源代码]
class angr.analyses.variable_recovery.VariableRecovery(func, max_iterations=20, store_live_variables=False)[源代码]

基类:ForwardAnalysis, VariableRecoveryBase

Recover "variables" from a function using forced execution.

While variables play a very important role in programming, it does not really exist after compiling. However, we can still identify and recovery their counterparts in binaries. It is worth noting that not every variable in source code can be identified in binaries, and not every recognized variable in binaries have a corresponding variable in the original source code. In short, there is no guarantee that the variables we identified/recognized in a binary are the same variables in its source code.

This analysis uses heuristics to identify and recovers the following types of variables: - Register variables. - Stack variables. - Heap variables. (not implemented yet) - Global variables. (not implemented yet)

This analysis takes a function as input, and performs a data-flow analysis on nodes. It runs concrete execution on every statement and hooks all register/memory accesses to discover all places that are accessing variables. It is slow, but has a more accurate analysis result. For a fast but inaccurate variable recovery, you may consider using VariableRecoveryFast.

This analysis follows SSA, which means every write creates a new variable in registers or memory (statck, heap, etc.). Things may get tricky when overlapping variable (in memory, as you cannot really have overlapping accesses to registers) accesses exist, and in such cases, a new variable will be created, and this new variable will overlap with one or more existing variables. A decision procedure (which is pretty much TODO) is required at the end of this analysis to resolve the conflicts between overlapping variables.

__init__(func, max_iterations=20, store_live_variables=False)[源代码]
参数:

func (knowledge.Function) -- The function to analyze.

class angr.analyses.variable_recovery.VariableRecoveryFast(func, func_graph=None, max_iterations=2, low_priority=False, track_sp=True, func_args=None, store_live_variables=False, unify_variables=True, func_arg_vvars=None, vvar_to_vvar=None)[源代码]

基类:ForwardAnalysis, VariableRecoveryBase

Recover "variables" from a function by keeping track of stack pointer offsets and pattern matching VEX statements.

If calling conventions are recovered prior to running VariableRecoveryFast, variables can be recognized more accurately. However, it is not a requirement. In this case, the function graph you pass must contain information indicating the call-out sites inside the analyzed function. These graph edges must be annotated with either "type": "call" or "outside": True.

参数:
__init__(func, func_graph=None, max_iterations=2, low_priority=False, track_sp=True, func_args=None, store_live_variables=False, unify_variables=True, func_arg_vvars=None, vvar_to_vvar=None)[源代码]

Constructor

参数:
返回:

None

class angr.analyses.typehoon.lifter.TypeLifter(bits)[源代码]

基类:object

Lift SimTypes to type constants.

参数:

bits (int)

__init__(bits)[源代码]
参数:

bits (int)

bits
memo
lift(ty)[源代码]
参数:

ty (SimType)

class angr.analyses.typehoon.simple_solver.SketchNodeBase[源代码]

基类:object

The base class for nodes in a sketch.

class angr.analyses.typehoon.simple_solver.SketchNode(typevar)[源代码]

基类:SketchNodeBase

Represents a node in a sketch graph.

参数:

typevar (TypeVariable | DerivedTypeVariable)

__init__(typevar)[源代码]
参数:

typevar (TypeVariable | DerivedTypeVariable)

typevar: TypeVariable | DerivedTypeVariable
upper_bound: TypeConstant
lower_bound: TypeConstant
class angr.analyses.typehoon.simple_solver.RecursiveRefNode(target)[源代码]

基类:SketchNodeBase

Represents a cycle in a sketch graph.

This is equivalent to sketches.LabelNode in the reference implementation of retypd.

参数:

target (DerivedTypeVariable)

__init__(target)[源代码]
参数:

target (DerivedTypeVariable)

class angr.analyses.typehoon.simple_solver.Sketch(solver, root)[源代码]

基类:object

Describes the sketch of a type variable.

参数:
__init__(solver, root)[源代码]
参数:
root: SketchNode
graph
node_mapping: dict[TypeVariable | DerivedTypeVariable, SketchNodeBase]
solver
lookup(typevar)[源代码]
返回类型:

SketchNodeBase | None

参数:

typevar (TypeVariable | DerivedTypeVariable)

add_edge(src, dst, label)[源代码]
返回类型:

None

参数:
add_constraint(constraint)[源代码]
返回类型:

None

参数:

constraint (TypeConstraint)

static flatten_typevar(derived_typevar)[源代码]
返回类型:

DerivedTypeVariable | TypeVariable | TypeConstant

参数:

derived_typevar (TypeVariable | TypeConstant | DerivedTypeVariable)

class angr.analyses.typehoon.simple_solver.ConstraintGraphTag(value)[源代码]

基类:Enum

An enumeration.

LEFT = 0
RIGHT = 1
UNKNOWN = 2
class angr.analyses.typehoon.simple_solver.FORGOTTEN(value)[源代码]

基类:Enum

An enumeration.

PRE_FORGOTTEN = 0
POST_FORGOTTEN = 1
class angr.analyses.typehoon.simple_solver.ConstraintGraphNode(typevar, variance, tag, forgotten)[源代码]

基类:object

参数:
__init__(typevar, variance, tag, forgotten)[源代码]
参数:
typevar
variance
tag
forgotten
forget_last_label()[源代码]
返回类型:

tuple[ConstraintGraphNode, BaseLabel] | None

recall(label)[源代码]
返回类型:

ConstraintGraphNode

参数:

label (BaseLabel)

inverse()[源代码]
返回类型:

ConstraintGraphNode

inverse_wo_tag()[源代码]

Invert the variance only.

返回类型:

ConstraintGraphNode

class angr.analyses.typehoon.simple_solver.SimpleSolver(bits, constraints, typevars)[源代码]

基类:object

SimpleSolver is, by its name, a simple solver. Most of this solver is based on the (complex) simplification logic that the retypd paper describes and the retypd re-implementation (https://github.com/GrammaTech/retypd) implements. Additionally, we add some improvements to allow type propagation of known struct names, among a few other improvements.

参数:

bits (int)

__init__(bits, constraints, typevars)[源代码]
参数:

bits (int)

solve()[源代码]

Steps:

For each type variable, - Infer the shape in its sketch - Build the constraint graph - Collect all constraints - Apply constraints to derive the lower and upper bounds

infer_shapes(typevars, constraints)[源代码]

Computing sketches from constraint sets. Implements Algorithm E.1 in the retypd paper.

返回类型:

tuple[dict, dict[TypeVariable, Sketch]]

参数:
compute_quotient_graph(constraints)[源代码]

Compute the quotient graph (the constraint graph modulo ~ in Algorithm E.1 in the retypd paper) with respect to a given set of type constraints.

参数:

constraints (set[TypeConstraint])

join(t1, t2)[源代码]
返回类型:

TypeConstant

参数:
meet(t1, t2)[源代码]
返回类型:

TypeConstant

参数:
static abstract(t)[源代码]
返回类型:

TypeConstant | TypeVariable

参数:

t (TypeConstant | TypeVariable)

determine(equivalent_classes, sketches, solution, nodes=None)[源代码]

Determine C-like types from sketches.

参数:
  • equivalent_classes (dict[TypeVariable, TypeVariable]) -- A dictionary mapping each type variable from its representative in the equivalence class over ~.

  • sketches -- A dictionary storing sketches for each type variable.

  • solution (dict) -- The dictionary storing C-like types for each type variable. Output.

  • nodes (Optional[set[SketchNode]]) -- Optional. Nodes that should be considered in the sketch.

返回类型:

None

返回:

None

class angr.analyses.typehoon.translator.SimTypeTempRef(typevar)[源代码]

基类:SimType

Represents a temporary reference to another type. TypeVariableReference is translated to SimTypeTempRef.

__init__(typevar)[源代码]
参数:

label -- the type label.

c_repr(**kwargs)[源代码]
class angr.analyses.typehoon.translator.TypeTranslator(arch=None)[源代码]

基类:object

Translate type variables to SimType equivalence.

__init__(arch=None)[源代码]
struct_name()[源代码]
tc2simtype(tc)[源代码]
simtype2tc(simtype)[源代码]
返回类型:

TypeConstant

参数:

simtype (SimType)

backpatch(st, translated)[源代码]
参数:
返回:

class angr.analyses.typehoon.typevars.TypeConstraint[源代码]

基类:object

pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

class angr.analyses.typehoon.typevars.Equivalence(type_a, type_b)[源代码]

基类:TypeConstraint

__init__(type_a, type_b)[源代码]
type_a
type_b
pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

class angr.analyses.typehoon.typevars.Existence(type_)[源代码]

基类:TypeConstraint

__init__(type_)[源代码]
type_
pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

replace(replacements)[源代码]
class angr.analyses.typehoon.typevars.Subtype(sub_type, super_type)[源代码]

基类:TypeConstraint

参数:
  • sub_type (TypeType)

  • super_type (TypeType)

__init__(sub_type, super_type)[源代码]
参数:
super_type
sub_type
pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

replace(replacements)[源代码]
class angr.analyses.typehoon.typevars.Add(type_0, type_1, type_r)[源代码]

基类:TypeConstraint

Describes the constraint that type_r == type0 + type1

__init__(type_0, type_1, type_r)[源代码]
type_0
type_1
type_r
pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

replace(replacements)[源代码]
class angr.analyses.typehoon.typevars.Sub(type_0, type_1, type_r)[源代码]

基类:TypeConstraint

Describes the constraint that type_r == type0 - type1

__init__(type_0, type_1, type_r)[源代码]
type_0
type_1
type_r
pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

replace(replacements)[源代码]
class angr.analyses.typehoon.typevars.TypeVariable(idx=None, name=None)[源代码]

基类:object

参数:
  • idx (int | None)

  • name (str | None)

__init__(idx=None, name=None)[源代码]
参数:
  • idx (int | None)

  • name (str | None)

idx: int
name
pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

class angr.analyses.typehoon.typevars.DerivedTypeVariable(type_var, label, labels=None, idx=None)[源代码]

基类:TypeVariable

参数:
__init__(type_var, label, labels=None, idx=None)[源代码]
参数:
type_var
labels: tuple[BaseLabel, ...]
one_label()[源代码]
返回类型:

BaseLabel | None

path()[源代码]
返回类型:

tuple[BaseLabel, ...]

longest_prefix()[源代码]
返回类型:

Union[TypeConstant, TypeVariable, DerivedTypeVariable, None]

pp_str(mapping)[源代码]
返回类型:

str

参数:

mapping (dict[TypeVariable, Any])

replace(replacements)[源代码]
class angr.analyses.typehoon.typevars.TypeVariables[源代码]

基类:object

__init__()[源代码]
copy()[源代码]
add_type_variable(var, codeloc, typevar)[源代码]
参数:
get_type_variable(var, codeloc)[源代码]
has_type_variable_for(var, codeloc)[源代码]
参数:

var (SimVariable)

class angr.analyses.typehoon.typevars.BaseLabel[源代码]

基类:object

__init__()[源代码]
property variance: Variance
class angr.analyses.typehoon.typevars.FuncIn(loc)[源代码]

基类:BaseLabel

__init__(loc)[源代码]
loc
class angr.analyses.typehoon.typevars.FuncOut(loc)[源代码]

基类:BaseLabel

__init__(loc)[源代码]
loc
class angr.analyses.typehoon.typevars.Load[源代码]

基类:BaseLabel

class angr.analyses.typehoon.typevars.Store[源代码]

基类:BaseLabel

property variance: Variance
class angr.analyses.typehoon.typevars.AddN(n)[源代码]

基类:BaseLabel

__init__(n)[源代码]
n
class angr.analyses.typehoon.typevars.SubN(n)[源代码]

基类:BaseLabel

__init__(n)[源代码]
n
class angr.analyses.typehoon.typevars.ConvertTo(to_bits)[源代码]

基类:BaseLabel

__init__(to_bits)[源代码]
to_bits
class angr.analyses.typehoon.typevars.ReinterpretAs(to_type, to_bits)[源代码]

基类:BaseLabel

__init__(to_type, to_bits)[源代码]
to_type
to_bits
class angr.analyses.typehoon.typevars.HasField(bits, offset)[源代码]

基类:BaseLabel

__init__(bits, offset)[源代码]
bits
offset
class angr.analyses.typehoon.typevars.IsArray[源代码]

基类:BaseLabel

class angr.analyses.typehoon.typehoon.Typehoon(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]

基类:Analysis

A spiritual tribute to the long-standing typehoon project that @jmg (John Grosen) worked on during his days in the angr team. Now I feel really bad of asking the poor guy to work directly on VEX IR without any fancy static analysis support as we have right now...

Typehoon analysis implements a pushdown system that simplifies and solves type constraints. Our type constraints are largely an implementation of the paper Polymorphic Type Inference for Machine Code by Noonan, Loginov, and Cok from GrammaTech (with missing functionality support and bugs, of course). Type constraints are collected by running VariableRecoveryFast (maybe VariableRecovery later as well) on a function, and then solved using this analysis.

User may specify ground truth, which will override all types at certain program points during constraint solving.

参数:
__init__(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]
参数:
update_variable_types(func_addr, var_to_typevars)[源代码]
参数:

func_addr (int | str)

pp_constraints()[源代码]

Pretty-print constraints between variables using the variable mapping.

返回类型:

None

pp_solution()[源代码]

Pretty-print solutions using the variable mapping.

返回类型:

None

All type constants used in type inference. They can be mapped, translated, or rewritten to C-style types.

angr.analyses.typehoon.typeconsts.memoize(f)[源代码]
class angr.analyses.typehoon.typeconsts.TypeConstant[源代码]

基类:object

SIZE = None
pp_str(mapping)[源代码]
返回类型:

str

property size: int
class angr.analyses.typehoon.typeconsts.TopType[源代码]

基类:TypeConstant

class angr.analyses.typehoon.typeconsts.BottomType[源代码]

基类:TypeConstant

class angr.analyses.typehoon.typeconsts.Int[源代码]

基类:TypeConstant

class angr.analyses.typehoon.typeconsts.Int1[源代码]

基类:Int

SIZE = 1
class angr.analyses.typehoon.typeconsts.Int8[源代码]

基类:Int

SIZE = 1
class angr.analyses.typehoon.typeconsts.Int16[源代码]

基类:Int

SIZE = 2
class angr.analyses.typehoon.typeconsts.Int32[源代码]

基类:Int

SIZE = 4
class angr.analyses.typehoon.typeconsts.Int64[源代码]

基类:Int

SIZE = 8
class angr.analyses.typehoon.typeconsts.Int128[源代码]

基类:Int

SIZE = 16
class angr.analyses.typehoon.typeconsts.Int256[源代码]

基类:Int

SIZE = 32
class angr.analyses.typehoon.typeconsts.Int512[源代码]

基类:Int

SIZE = 32
class angr.analyses.typehoon.typeconsts.FloatBase[源代码]

基类:TypeConstant

class angr.analyses.typehoon.typeconsts.Float[源代码]

基类:FloatBase

SIZE = 4
class angr.analyses.typehoon.typeconsts.Double[源代码]

基类:FloatBase

SIZE = 8
class angr.analyses.typehoon.typeconsts.Pointer(basetype)[源代码]

基类:TypeConstant

参数:

basetype (TypeConstant | None)

__init__(basetype)[源代码]
参数:

basetype (TypeConstant | None)

new(basetype)[源代码]
class angr.analyses.typehoon.typeconsts.Pointer32(basetype=None)[源代码]

基类:Pointer, Int32

32-bit pointers.

__init__(basetype=None)[源代码]
class angr.analyses.typehoon.typeconsts.Pointer64(basetype=None)[源代码]

基类:Pointer, Int64

64-bit pointers.

__init__(basetype=None)[源代码]
class angr.analyses.typehoon.typeconsts.Array(element=None, count=None)[源代码]

基类:TypeConstant

__init__(element=None, count=None)[源代码]
class angr.analyses.typehoon.typeconsts.Struct(fields=None, name=None, field_names=None)[源代码]

基类:TypeConstant

__init__(fields=None, name=None, field_names=None)[源代码]
class angr.analyses.typehoon.typeconsts.Function(params, outputs)[源代码]

基类:TypeConstant

参数:
__init__(params, outputs)[源代码]
参数:
class angr.analyses.typehoon.typeconsts.TypeVariableReference(typevar)[源代码]

基类:TypeConstant

__init__(typevar)[源代码]
angr.analyses.typehoon.typeconsts.int_type(bits)[源代码]
返回类型:

Int

参数:

bits (int)

angr.analyses.typehoon.typeconsts.float_type(bits)[源代码]
返回类型:

FloatBase | None

参数:

bits (int)

class angr.analyses.typehoon.Typehoon(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]

基类:Analysis

A spiritual tribute to the long-standing typehoon project that @jmg (John Grosen) worked on during his days in the angr team. Now I feel really bad of asking the poor guy to work directly on VEX IR without any fancy static analysis support as we have right now...

Typehoon analysis implements a pushdown system that simplifies and solves type constraints. Our type constraints are largely an implementation of the paper Polymorphic Type Inference for Machine Code by Noonan, Loginov, and Cok from GrammaTech (with missing functionality support and bugs, of course). Type constraints are collected by running VariableRecoveryFast (maybe VariableRecovery later as well) on a function, and then solved using this analysis.

User may specify ground truth, which will override all types at certain program points during constraint solving.

参数:
__init__(constraints, func_var, ground_truth=None, var_mapping=None, must_struct=None)[源代码]
参数:
update_variable_types(func_addr, var_to_typevars)[源代码]
参数:

func_addr (int | str)

pp_constraints()[源代码]

Pretty-print constraints between variables using the variable mapping.

返回类型:

None

pp_solution()[源代码]

Pretty-print solutions using the variable mapping.

返回类型:

None

class angr.analyses.identifier.identify.FuncInfo[源代码]

基类:object

__init__()[源代码]
class angr.analyses.identifier.identify.Identifier(cfg=None, require_predecessors=True, only_find=None)[源代码]

基类:Analysis

__init__(cfg=None, require_predecessors=True, only_find=None)[源代码]
run(only_find=None)[源代码]
can_call_same_name(addr, name)[源代码]
get_func_info(func)[源代码]
static constrain_all_zero(before_state, state, regs)[源代码]
identify_func(function)[源代码]
check_tests(cfg_func, match_func)[源代码]
map_callsites()[源代码]
do_trace(addr_trace, reverse_accesses, func_info)[源代码]
get_call_args(func, callsite)[源代码]
static get_reg_name(arch, reg_offset)[源代码]
参数:
  • arch -- the architecture

  • reg_offset -- Tries to find the name of a register given the offset in the registers.

返回:

The register name

find_stack_vars_x86(func)[源代码]
static make_initial_state(project, stack_length)[源代码]
返回:

an initial state with a symbolic stack and good options for rop

static make_symbolic_state(project, reg_list, stack_length=80)[源代码]

converts an input state into a state with symbolic registers :return: the symbolic state

class angr.analyses.loopfinder.Loop(entry, entry_edges, break_edges, continue_edges, body_nodes, graph, subloops)[源代码]

基类:object

__init__(entry, entry_edges, break_edges, continue_edges, body_nodes, graph, subloops)[源代码]
class angr.analyses.loopfinder.LoopFinder(functions=None, normalize=True)[源代码]

基类:Analysis

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

__init__(functions=None, normalize=True)[源代码]
class angr.analyses.loop_analysis.VariableTypes[源代码]

基类:object

Iterator = 'Iterator'
HasNext = 'HasNext'
Next = 'Next'
class angr.analyses.loop_analysis.AnnotatedVariable(variable, type_)[源代码]

基类:object

__init__(variable, type_)[源代码]
variable
type
class angr.analyses.loop_analysis.Condition(op, val0, val1)[源代码]

基类:object

Equal = '=='
NotEqual = '!='
__init__(op, val0, val1)[源代码]
classmethod from_opstr(opstr)[源代码]
class angr.analyses.loop_analysis.SootBlockProcessor(state, block, loop, defuse)[源代码]

基类:object

__init__(state, block, loop, defuse)[源代码]
process()[源代码]
class angr.analyses.loop_analysis.LoopAnalysisState(block)[源代码]

基类:object

__init__(block)[源代码]
copy()[源代码]
merge(state)[源代码]
add_loop_exit_stmt(stmt_idx, condition=None)[源代码]
class angr.analyses.loop_analysis.LoopAnalysis(loop, defuse)[源代码]

基类:ForwardAnalysis, Analysis

Analyze a loop and recover important information about the loop (e.g., invariants, induction variables) in a static manner.

__init__(loop, defuse)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

返回:

None

exception angr.analyses.veritesting.VeritestingError[源代码]

基类:Exception

class angr.analyses.veritesting.CallTracingFilter(project, depth, blacklist=None)[源代码]

基类:object

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

whitelist = {<class 'angr.procedures.cgc.receive.receive'>, <class 'angr.procedures.cgc.transmit.transmit'>, <class 'angr.procedures.glibc.__ctype_b_loc.__ctype_b_loc'>, <class 'angr.procedures.libc.atoi.atoi'>, <class 'angr.procedures.libc.fgetc.fgetc'>, <class 'angr.procedures.libc.strcmp.strcmp'>, <class 'angr.procedures.libc.strlen.strlen'>, <class 'angr.procedures.posix.read.read'>}
cfg_cache = {}
__init__(project, depth, blacklist=None)[源代码]
filter(call_target_state, jumpkind)[源代码]

The call will be skipped if it returns True.

参数:
  • call_target_state -- The new state of the call target.

  • jumpkind -- The Jumpkind of this call.

返回:

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

class angr.analyses.veritesting.Veritesting(input_state, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None)[源代码]

基类:Analysis

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

cfg_cache = {}
all_stashes = ('successful', 'errored', 'deadended', 'deviated', 'unconstrained')
__init__(input_state, boundaries=None, loop_unrolling_limit=10, enable_function_inlining=False, terminator=None, deviation_filter=None)[源代码]

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

参数:
  • input_state -- The initial state to begin the execution with.

  • boundaries -- Addresses where execution should stop.

  • loop_unrolling_limit -- The maximum times that Veritesting should unroll a loop for.

  • enable_function_inlining -- Whether we should enable function inlining and syscall inlining.

  • terminator -- A callback function that takes a state as parameter. Veritesting will terminate if this function returns True.

  • deviation_filter -- A callback function that takes a state as parameter. Veritesting will put the state into "deviated" stash if this function returns True.

is_not_in_cfg(s)[源代码]

Returns if s.addr is not a proper node in our CFG.

参数:

s (SimState) -- The SimState instance to test.

Returns bool:

False if our CFG contains p.addr, True otherwise.

is_overbound(state)[源代码]

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

param SimState state: SimState instance to check returns bool: True if outside of mem/loop_ctr boundary

project: Project
kb: KnowledgeBase
class angr.analyses.vfg.VFGJob(*args, **kwargs)[源代码]

基类:CFGJobBase

A job descriptor that contains local variables used during VFG analysis.

__init__(*args, **kwargs)[源代码]
返回类型:

None

property block_id: BlockID | None
callstack_repr(kb)[源代码]
参数:

kb (KnowledgeBase)

class angr.analyses.vfg.PendingJob(block_id, state, call_stack, src_block_id, src_stmt_idx, src_ins_addr)[源代码]

基类:object

Describes a pending job during VFG analysis.

参数:
__init__(block_id, state, call_stack, src_block_id, src_stmt_idx, src_ins_addr)[源代码]
参数:
返回类型:

None

block_id
state
call_stack
src_block_id
src_stmt_idx
src_ins_addr
class angr.analyses.vfg.AnalysisTask[源代码]

基类:object

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

__init__()[源代码]
返回类型:

None

property done
class angr.analyses.vfg.FunctionAnalysis(function_address, return_address)[源代码]

基类:AnalysisTask

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

参数:
  • function_address (int)

  • return_address (int | None)

__init__(function_address, return_address)[源代码]
参数:
  • function_address (int)

  • return_address (int | None)

返回类型:

None

property done: bool
class angr.analyses.vfg.CallAnalysis(address, return_address, function_analysis_tasks=None, mergeable_plugins=None)[源代码]

基类:AnalysisTask

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

参数:
  • address (int)

  • return_address (None)

  • function_analysis_tasks (list[Any] | None)

  • mergeable_plugins (tuple[str, str] | None)

__init__(address, return_address, function_analysis_tasks=None, mergeable_plugins=None)[源代码]
参数:
  • address (int)

  • return_address (None)

  • function_analysis_tasks (list[Any] | None)

  • mergeable_plugins (tuple[str, str] | None)

返回类型:

None

property done: bool
register_function_analysis(task)[源代码]
返回类型:

None

参数:

task (FunctionAnalysis)

add_final_job(job)[源代码]
返回类型:

None

参数:

job (VFGJob)

merge_jobs()[源代码]
返回类型:

VFGJob

class angr.analyses.vfg.VFGNode(addr, key, state=None)[源代码]

基类:object

A descriptor of nodes in a Value-Flow Graph

参数:
__init__(addr, key, state=None)[源代码]

Constructor.

参数:
返回类型:

None

append_state(s, is_widened_state=False)[源代码]

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

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

基类:ForwardAnalysis[SimState, VFGNode, VFGJob, BlockID], Analysis

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

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

Steps:

  • Generate a CFG first if CFG is not provided.

  • Identify all merge points (denote the set of merge points as Pw) in the CFG.

  • Cut those loop back edges (can be derived from Pw) so that we gain an acyclic CFG.

  • Identify all variables that are 1) from memory loading 2) from initial values, or 3) phi functions. Denote

    the set of those variables as S_{var}.

  • Start real AI analysis and try to compute a fix point of each merge point. Perform widening/narrowing only on

    variables in S_{var}.

参数:
__init__(cfg=None, context_sensitivity_level=2, start=None, function_start=None, interfunction_level=0, initial_state=None, avoid_runs=None, remove_options=None, timeout=None, max_iterations_before_widening=8, max_iterations=40, widening_interval=3, final_state_callback=None, status_callback=None, record_function_final_states=False)[源代码]
参数:
  • cfg (Optional[CFGEmulated]) -- The control-flow graph to base this analysis on. If none is provided, we will construct a CFGEmulated.

  • context_sensitivity_level (int) -- The level of context-sensitivity of this VFG. It ranges from 0 to infinity. Default 2.

  • function_start (Optional[int]) -- The address of the function to analyze.

  • interfunction_level (int) -- The level of interfunction-ness to be

  • initial_state (Optional[SimState]) -- A state to use as the initial one

  • avoid_runs (Optional[list[int]]) -- A list of runs to avoid

  • remove_options (Optional[set[str]]) -- State options to remove from the initial state. It only works when initial_state is None

  • timeout (int)

  • final_state_callback (Optional[Callable[[SimState, CallStack], Any]]) -- callback function when countering final state

  • status_callback (Optional[Callable[[VFG], Any]]) -- callback function used in _analysis_core_baremetal

  • start (int | None)

  • max_iterations_before_widening (int)

  • max_iterations (int)

  • widening_interval (int)

  • record_function_final_states (bool)

返回类型:

None

property function_initial_states
property function_final_states
get_any_node(addr)[源代码]

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

返回类型:

VFGNode | None

参数:

addr (int)

get_all_nodes(addr)[源代码]
返回类型:

Generator[VFGNode]

irsb_from_node(node)[源代码]
copy()[源代码]
class angr.analyses.vsa_ddg.DefUseChain(def_loc, use_loc, variable)[源代码]

基类:object

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

__init__(def_loc, use_loc, variable)[源代码]

Constructor.

参数:
  • def_loc

  • use_loc

  • variable

返回:

class angr.analyses.vsa_ddg.VSA_DDG(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)[源代码]

基类:Analysis

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

__init__(vfg=None, start_addr=None, interfunction_level=0, context_sensitivity_level=2, keep_data=False)[源代码]

Constructor.

参数:
  • vfg -- An already constructed VFG. If not specified, a new VFG will be created with other specified parameters. vfg and start_addr cannot both be unspecified.

  • start_addr -- The address where to start the analysis (typically, a function's entry point).

  • interfunction_level -- See VFG analysis.

  • context_sensitivity_level -- See VFG analysis.

  • keep_data -- Whether we keep set of addresses as edges in the graph, or just the cardinality of the sets, which can be used as a "weight".

get_predecessors(code_location)[源代码]

Returns all predecessors of code_location.

参数:

code_location -- A CodeLocation instance.

返回:

A list of all predecessors.

get_all_nodes(simrun_addr, stmt_idx)[源代码]

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

class angr.analyses.vtable.Vtable(vaddr, size, func_addrs=None)[源代码]

基类:object

This contains the addr, size and function addresses of a Vtable

__init__(vaddr, size, func_addrs=None)[源代码]
class angr.analyses.vtable.VtableFinder[源代码]

基类:Analysis

This analysis locates Vtables in a binary based on heuristics taken from - "Reconstruction of Class Hierarchies for Decompilation of C++ Programs"

__init__()[源代码]
is_cross_referenced(addr)[源代码]
is_function(addr)[源代码]
analyze()[源代码]
create_extract_vtable(start_addr, sec_size)[源代码]
class angr.analyses.find_objects_static.PossibleObject(size, addr, class_name=None)[源代码]

基类:object

This holds the address and class name of possible class instances. The address that it holds in mapped outside the binary so it is only valid in this analysis. TO DO: map the address to its uses in the registers/memory locations in the instructions

__init__(size, addr, class_name=None)[源代码]
class angr.analyses.find_objects_static.NewFunctionHandler(max_addr=None, new_func_addr=None, project=None)[源代码]

基类:FunctionHandler

This handles calls to the function new(), by recording the size parameter passed to it and also assigns a new

address outside the mapped binary to the newly created space(possible object).

It also tracks if the function called right after new() is passed the same 'this' pointer and is a constructor, if so we mark it as an instance of the class the constructor belongs to.(only for non stripped binaries)

__init__(max_addr=None, new_func_addr=None, project=None)[源代码]
hook(analysis)[源代码]

Attach this instance of the function handler to an instance of RDA.

handle_local_function(state, data)[源代码]
参数:
class angr.analyses.find_objects_static.StaticObjectFinder[源代码]

基类:Analysis

This analysis tries to find objects on the heap based on calls to new(), and subsequent calls to constructors with

the 'this' pointer

__init__()[源代码]
class angr.analyses.class_identifier.ClassIdentifier[源代码]

基类:Analysis

This is a class identifier for non stripped or partially stripped binaries, it identifies classes based on the demangled function names, and also assigns functions to their respective classes based on their names. It also uses the results from the VtableFinder analysis to assign the corresponding vtable to the classes.

self.classes contains a mapping between class names and SimCppClass objects

e.g. A::tool() and A::qux() belong to the class A

__init__()[源代码]
class angr.analyses.disassembly.DisassemblyPiece[源代码]

基类:object

addr = None
ident = nan
render(formatting=None)[源代码]
getpiece(formatting, column)[源代码]
width(formatting)[源代码]
height(formatting)[源代码]
static color(string, coloring, formatting)[源代码]
highlight(string, formatting=None)[源代码]
class angr.analyses.disassembly.FunctionStart(func)[源代码]

基类:DisassemblyPiece

__init__(func)[源代码]

Constructor.

参数:

func (angr.knowledge.Function) -- The function instance.

height(formatting)[源代码]
class angr.analyses.disassembly.Label(addr, name)[源代码]

基类:DisassemblyPiece

__init__(addr, name)[源代码]
class angr.analyses.disassembly.IROp(addr, seq, obj, irsb)[源代码]

基类:DisassemblyPiece

参数:
__init__(addr, seq, obj, irsb)[源代码]
参数:
addr: int
seq: int
obj: Union[IRStmt, PcodeOp]
irsb: Union[IRSB, IRSB]
class angr.analyses.disassembly.BlockStart(block, parentfunc, project)[源代码]

基类:DisassemblyPiece

__init__(block, parentfunc, project)[源代码]
class angr.analyses.disassembly.Hook(block)[源代码]

基类:DisassemblyPiece

__init__(block)[源代码]
class angr.analyses.disassembly.Instruction(insn, parentblock, project=None)[源代码]

基类:DisassemblyPiece

__init__(insn, parentblock, project=None)[源代码]
property mnemonic
reload_format()[源代码]
dissect_instruction()[源代码]
dissect_instruction_for_arm()[源代码]
static split_arm_op_string(op_str)[源代码]
参数:

op_str (str)

dissect_instruction_by_default()[源代码]
static split_op_string(insn_str)[源代码]
class angr.analyses.disassembly.SootExpression(expr)[源代码]

基类:DisassemblyPiece

__init__(expr)[源代码]
class angr.analyses.disassembly.SootExpressionTarget(target_stmt_idx)[源代码]

基类:SootExpression

__init__(target_stmt_idx)[源代码]
class angr.analyses.disassembly.SootExpressionStaticFieldRef(field)[源代码]

基类:SootExpression

__init__(field)[源代码]
class angr.analyses.disassembly.SootExpressionInvoke(invoke_type, expr)[源代码]

基类:SootExpression

Virtual = 'virtual'
Static = 'static'
Special = 'special'
__init__(invoke_type, expr)[源代码]
class angr.analyses.disassembly.SootStatement(block_addr, raw_stmt)[源代码]

基类:DisassemblyPiece

__init__(block_addr, raw_stmt)[源代码]
property stmt_idx
class angr.analyses.disassembly.Opcode(parentinsn)[源代码]

基类:DisassemblyPiece

__init__(parentinsn)[源代码]
class angr.analyses.disassembly.Operand(op_num, children, parentinsn)[源代码]

基类:DisassemblyPiece

__init__(op_num, children, parentinsn)[源代码]
property cs_operand
static build(operand_type, op_num, children, parentinsn)[源代码]
class angr.analyses.disassembly.ConstantOperand(op_num, children, parentinsn)[源代码]

基类:Operand

class angr.analyses.disassembly.RegisterOperand(op_num, children, parentinsn)[源代码]

基类:Operand

property register
class angr.analyses.disassembly.MemoryOperand(op_num, children, parentinsn)[源代码]

基类:Operand

__init__(op_num, children, parentinsn)[源代码]
class angr.analyses.disassembly.OperandPiece[源代码]

基类:DisassemblyPiece

addr = None
parentop = None
ident = None
class angr.analyses.disassembly.Register(reg, prefix='')[源代码]

基类:OperandPiece

__init__(reg, prefix='')[源代码]
class angr.analyses.disassembly.Value(val, render_with_sign)[源代码]

基类:OperandPiece

__init__(val, render_with_sign)[源代码]
property project
class angr.analyses.disassembly.Comment(addr, text)[源代码]

基类:DisassemblyPiece

__init__(addr, text)[源代码]
height(formatting)[源代码]
class angr.analyses.disassembly.FuncComment(func)[源代码]

基类:DisassemblyPiece

__init__(func)[源代码]
class angr.analyses.disassembly.Disassembly(function=None, ranges=None, thumb=False, include_ir=False, block_bytes=None)[源代码]

基类:Analysis

Produce formatted machine code disassembly.

参数:
__init__(function=None, ranges=None, thumb=False, include_ir=False, block_bytes=None)[源代码]
参数:
func_lookup(block)[源代码]
parse_block(block)[源代码]

Parse instructions for a given block node

返回类型:

None

参数:

block (BlockNode)

render(formatting=None, show_edges=True, show_addresses=True, show_bytes=False, ascii_only=None, color=True)[源代码]

Render the disassembly to a string, with optional edges and addresses.

Color will be added by default, if enabled. To disable color pass an empty formatting dict.

返回类型:

str

参数:
angr.analyses.disassembly_utils.decode_instruction(arch, instr)[源代码]
exception angr.analyses.reassembler.BinaryError[源代码]

基类:Exception

exception angr.analyses.reassembler.InstructionError[源代码]

基类:BinaryError

exception angr.analyses.reassembler.ReassemblerFailureNotice[源代码]

基类:BinaryError

angr.analyses.reassembler.string_escape(s)[源代码]
angr.analyses.reassembler.fill_reg_map()[源代码]
angr.analyses.reassembler.split_operands(s)[源代码]
angr.analyses.reassembler.is_hex(s)[源代码]
class angr.analyses.reassembler.Label(binary, name, original_addr=None)[源代码]

基类:object

g_label_ctr = count(0)
__init__(binary, name, original_addr=None)[源代码]
property operand_str
property offset
static new_label(binary, name=None, function_name=None, original_addr=None, data_label=False)[源代码]
class angr.analyses.reassembler.DataLabel(binary, original_addr, name=None)[源代码]

基类:Label

__init__(binary, original_addr, name=None)[源代码]
property operand_str
class angr.analyses.reassembler.FunctionLabel(binary, function_name, original_addr, plt=False)[源代码]

基类:Label

__init__(binary, function_name, original_addr, plt=False)[源代码]
property function_name
property operand_str
class angr.analyses.reassembler.ObjectLabel(binary, symbol_name, original_addr, plt=False)[源代码]

基类:Label

__init__(binary, symbol_name, original_addr, plt=False)[源代码]
property symbol_name
property operand_str
class angr.analyses.reassembler.NotypeLabel(binary, symbol_name, original_addr, plt=False)[源代码]

基类:Label

__init__(binary, symbol_name, original_addr, plt=False)[源代码]
property symbol_name
property operand_str
class angr.analyses.reassembler.SymbolManager(binary, cfg)[源代码]

基类:object

SymbolManager manages all symbols in the binary.

__init__(binary, cfg)[源代码]

Constructor.

参数:
返回:

None

get_unique_symbol_name(symbol_name)[源代码]
new_label(addr, name=None, is_function=None, force=False)[源代码]
label_got(addr, label)[源代码]

Mark a certain label as assigned (to an instruction or a block of data).

参数:
返回:

None

class angr.analyses.reassembler.Operand(binary, insn_addr, insn_size, capstone_operand, operand_str, mnemonic, operand_offset, syntax=None)[源代码]

基类:object

__init__(binary, insn_addr, insn_size, capstone_operand, operand_str, mnemonic, operand_offset, syntax=None)[源代码]

Constructor.

参数:
  • binary (Reassembler) -- The Binary analysis.

  • insn_addr (int) -- Address of the instruction.

  • capstone_operand

  • operand_str (str) -- the string representation of this operand

  • mnemonic (str) -- Mnemonic of the instruction that this operand belongs to.

  • operand_offset (int) -- offset of the operand into the instruction.

  • syntax (str) -- Provide a way to override the default syntax coming from binary.

返回:

None

assembly()[源代码]
property is_immediate
property symbolized
class angr.analyses.reassembler.Instruction(binary, addr, size, insn_bytes, capstone_instr)[源代码]

基类:object

High-level representation of an instruction in the binary

__init__(binary, addr, size, insn_bytes, capstone_instr)[源代码]
参数:
  • binary (Reassembler) -- The Binary analysis

  • addr (int) -- Address of the instruction

  • size (int) -- Size of the instruction

  • insn_bytes (str) -- Instruction bytes

  • capstone_instr -- Capstone Instr object.

返回:

None

assign_labels()[源代码]
dbg_comments()[源代码]
assembly(comments=False, symbolized=True)[源代码]
返回:

class angr.analyses.reassembler.BasicBlock(binary, addr, size, x86_getpc_retsite=False)[源代码]

基类:object

BasicBlock represents a basic block in the binary.

参数:

x86_getpc_retsite (bool)

__init__(binary, addr, size, x86_getpc_retsite=False)[源代码]

Constructor.

参数:
  • binary (Reassembler) -- The Binary analysis.

  • addr (int) -- Address of the block

  • size (int) -- Size of the block

  • x86_getpc_retsite (bool)

返回:

None

assign_labels()[源代码]
assembly(comments=False, symbolized=True)[源代码]
instruction_addresses()[源代码]
class angr.analyses.reassembler.Procedure(binary, function=None, addr=None, size=None, name=None, section='.text', asm_code=None)[源代码]

基类:object

Procedure in the binary.

__init__(binary, function=None, addr=None, size=None, name=None, section='.text', asm_code=None)[源代码]

Constructor.

参数:
  • binary (Reassembler) -- The Binary analysis.

  • function (angr.knowledge.Function) -- The function it represents

  • addr (int) -- Address of the function. Not required if function is provided.

  • size (int) -- Size of the function. Not required if function is provided.

  • section (str) -- Which section this function comes from.

返回:

None

property name

Get function name from the labels of the very first block. :return: Function name if there is any, None otherwise :rtype: string

property is_plt

If this function is a PLT entry or not. :return: True if this function is a PLT entry, False otherwise :rtype: bool

assign_labels()[源代码]
assembly(comments=False, symbolized=True)[源代码]

Get the assembly manifest of the procedure.

参数:
  • comments

  • symbolized

返回:

A list of tuples (address, basic block assembly), ordered by basic block addresses

返回类型:

list

instruction_addresses()[源代码]

Get all instruction addresses in the binary.

返回:

A list of sorted instruction addresses.

返回类型:

list

class angr.analyses.reassembler.ProcedureChunk(project, addr, size)[源代码]

基类:Procedure

Procedure chunk.

__init__(project, addr, size)[源代码]

Constructor.

参数:
  • project

  • addr

  • size

返回:

class angr.analyses.reassembler.Data(binary, memory_data=None, section=None, section_name=None, name=None, size=None, sort=None, addr=None, initial_content=None)[源代码]

基类:object

__init__(binary, memory_data=None, section=None, section_name=None, name=None, size=None, sort=None, addr=None, initial_content=None)[源代码]
property content
shrink(new_size)[源代码]

Reduce the size of this block

参数:

new_size (int) -- The new size

返回:

None

desymbolize()[源代码]

We believe this was a pointer and symbolized it before. Now we want to desymbolize it.

The following actions are performed: - Reload content from memory - Mark the sort as 'unknown'

返回:

None

assign_labels()[源代码]
assembly(comments=False, symbolized=True)[源代码]
class angr.analyses.reassembler.Relocation(addr, ref_addr, sort)[源代码]

基类:object

__init__(addr, ref_addr, sort)[源代码]
class angr.analyses.reassembler.Reassembler(syntax='intel', remove_cgc_attachments=True, log_relocations=True)[源代码]

基类:Analysis

High-level representation of a binary with a linear representation of all instructions and data regions. After calling "symbolize", it essentially acts as a binary reassembler.

Tested on CGC, x86 and x86-64 binaries.

Disclaimer: The reassembler is an empirical solution. Don't be surprised if it does not work on some binaries.

__init__(syntax='intel', remove_cgc_attachments=True, log_relocations=True)[源代码]
property instructions

Get a list of all instructions in the binary

返回:

A list of (address, instruction)

返回类型:

tuple

property relocations
property inserted_asm_before_label
property inserted_asm_after_label
property main_executable_regions

return:

property main_nonexecutable_regions

return:

section_alignment(section_name)[源代码]

Get the alignment for the specific section. If the section is not found, 16 is used as default.

参数:

section_name (str) -- The section.

返回:

The alignment in bytes.

返回类型:

int

main_executable_regions_contain(addr)[源代码]
参数:

addr

返回:

main_executable_region_limbos_contain(addr)[源代码]

Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes after the beginning of the section. We take care of that here.

参数:

addr (int) -- The address to check.

返回:

A 2-tuple of (bool, the closest base address)

返回类型:

tuple

main_nonexecutable_regions_contain(addr)[源代码]
参数:

addr (int) -- The address to check.

返回:

True if the address is inside a non-executable region, False otherwise.

返回类型:

bool

main_nonexecutable_region_limbos_contain(addr, tolerance_before=64, tolerance_after=64)[源代码]

Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes after the beginning of the section. We take care of that here.

参数:

addr (int) -- The address to check.

返回:

A 2-tuple of (bool, the closest base address)

返回类型:

tuple

register_instruction_reference(insn_addr, ref_addr, sort, operand_offset)[源代码]
register_data_reference(data_addr, ref_addr)[源代码]
add_label(name, addr)[源代码]

Add a new label to the symbol manager.

参数:
  • name (str) -- Name of the label.

  • addr (int) -- Address of the label.

返回:

None

insert_asm(addr, asm_code, before_label=False)[源代码]

Insert some assembly code at the specific address. There must be an instruction starting at that address.

参数:
  • addr (int) -- Address of insertion

  • asm_code (str) -- The assembly code to insert

返回:

None

append_procedure(name, asm_code)[源代码]

Add a new procedure with specific name and assembly code.

参数:
  • name (str) -- The name of the new procedure.

  • asm_code (str) -- The assembly code of the procedure

返回:

None

append_data(name, initial_content, size, readonly=False, sort='unknown')[源代码]

Append a new data entry into the binary with specific name, content, and size.

参数:
  • name (str) -- Name of the data entry. Will be used as the label.

  • initial_content (bytes) -- The initial content of the data entry.

  • size (int) -- Size of the data entry.

  • readonly (bool) -- If the data entry belongs to the readonly region.

  • sort (str) -- Type of the data.

返回:

None

remove_instruction(ins_addr)[源代码]
参数:

ins_addr

返回:

randomize_procedures()[源代码]
返回:

symbolize()[源代码]
assembly(comments=False, symbolized=True)[源代码]
remove_cgc_attachments()[源代码]

Remove CGC attachments.

返回:

True if CGC attachments are found and removed, False otherwise

返回类型:

bool

remove_unnecessary_stuff()[源代码]

Remove unnecessary functions and data

返回:

None

remove_unnecessary_stuff_glibc()[源代码]
fast_memory_load(addr, size, data_type, endness='Iend_LE')[源代码]

Load memory bytes from loader's memory backend.

参数:
  • addr (int) -- The address to begin memory loading.

  • size (int) -- Size in bytes.

  • data_type -- Type of the data.

  • endness (str) -- Endianness of this memory load.

返回:

Data read out of the memory.

返回类型:

int or bytes or str or None

class angr.analyses.congruency_check.CongruencyCheck(throw=False)[源代码]

基类:Analysis

This is an analysis to ensure that angr executes things identically with different execution backends (i.e., unicorn vs vex).

__init__(throw=False)[源代码]

Initializes a CongruencyCheck analysis.

参数:

throw -- whether to raise an exception if an incongruency is found.

set_state_options(left_add_options=None, left_remove_options=None, right_add_options=None, right_remove_options=None)[源代码]

Checks that the specified state options result in the same states over the next depth states.

set_states(left_state, right_state)[源代码]

Checks that the specified paths stay the same over the next depth states.

set_simgr(simgr)[源代码]
run(depth=None)[源代码]

Checks that the paths in the specified path group stay the same over the next depth bytes.

The path group should have a "left" and a "right" stash, each with a single path.

compare_path_group(pg)[源代码]
compare_states(sl, sr)[源代码]

Compares two states for similarity.

compare_paths(pl, pr)[源代码]
class angr.analyses.static_hooker.StaticHooker(library, binary=None)[源代码]

基类:Analysis

This analysis works on statically linked binaries - it finds the library functions statically linked into the binary and hooks them with the appropriate simprocedures.

Right now it only works on unstripped binaries, but hey! There's room to grow!

__init__(library, binary=None)[源代码]
class angr.analyses.binary_optimizer.ConstantPropagation(constant, constant_assignment_loc, constant_consuming_loc)[源代码]

基类:object

__init__(constant, constant_assignment_loc, constant_consuming_loc)[源代码]
class angr.analyses.binary_optimizer.RedundantStackVariable(argument, stack_variable, stack_variable_consuming_locs)[源代码]

基类:object

__init__(argument, stack_variable, stack_variable_consuming_locs)[源代码]
class angr.analyses.binary_optimizer.RegisterReallocation(stack_variable, register_variable, stack_variable_sources, stack_variable_consumers, prologue_addr, prologue_size, epilogue_addr, epilogue_size)[源代码]

基类:object

__init__(stack_variable, register_variable, stack_variable_sources, stack_variable_consumers, prologue_addr, prologue_size, epilogue_addr, epilogue_size)[源代码]

Constructor.

参数:
class angr.analyses.binary_optimizer.DeadAssignment(pv)[源代码]

基类:object

__init__(pv)[源代码]

Constructor.

参数:

pv (angr.analyses.ddg.ProgramVariable) -- The assignment to remove.

class angr.analyses.binary_optimizer.BinaryOptimizer(cfg, techniques)[源代码]

基类:Analysis

This is a collection of binary optimization techniques we used in Mechanical Phish during the finals of Cyber Grand Challenge. It focuses on dealing with some serious speed-impacting code constructs, and sort of worked on some CGC binaries compiled with O0. Use this analysis as a reference of how to use data dependency graph and such.

There is no guarantee that BinaryOptimizer will ever work on non-CGC binaries. Feel free to give us PR or MR, but please do not ask for support of non-CGC binaries.

BLOCKS_THRESHOLD = 500
__init__(cfg, techniques)[源代码]
optimize()[源代码]
project: Project
kb: KnowledgeBase
class angr.analyses.callee_cleanup_finder.CalleeCleanupFinder(starts=None, hook_all=False)[源代码]

基类:Analysis

__init__(starts=None, hook_all=False)[源代码]
analyze(addr)[源代码]
class angr.analyses.dominance_frontier.DominanceFrontier(func, func_graph=None, entry=None, exception_edges=False)[源代码]

基类:Analysis

Computes the dominance frontier of all nodes in a function graph, and provides an easy-to-use interface for querying the frontier information.

__init__(func, func_graph=None, entry=None, exception_edges=False)[源代码]
class angr.analyses.init_finder.SimEngineInitFinderVEX(project, replacements, overlay, pointers_only=False)[源代码]

基类:SimEngineNostmtVEX[None, Base | int | None, None]

The VEX engine class for InitFinder.

__init__(project, replacements, overlay, pointers_only=False)[源代码]
static is_concrete(expr)[源代码]
返回类型:

bool

class angr.analyses.init_finder.InitializationFinder(func=None, func_graph=None, block=None, max_iterations=1, replacements=None, overlay=None, pointers_only=False)[源代码]

基类:ForwardAnalysis, Analysis

Finds possible initializations for global data sections and generate an overlay to be used in other analyses later on.

__init__(func=None, func_graph=None, block=None, max_iterations=1, replacements=None, overlay=None, pointers_only=False)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

返回:

None

class angr.analyses.xrefs.SimEngineXRefsVEX(xref_manager, project, replacements=None)[源代码]

基类:SimEngineNostmtVEX[None, None, None]

The VEX engine class for XRefs analysis.

__init__(xref_manager, project, replacements=None)[源代码]
add_xref(xref_type, from_loc, to_loc)[源代码]
static extract_value_if_concrete(expr)[源代码]

Extract the concrete value from expr if it is a concrete claripy AST.

参数:

expr -- A claripy AST.

返回类型:

int | None

返回:

A concrete value or None if nothing concrete can be extracted.

class angr.analyses.xrefs.XRefsAnalysis(func=None, func_graph=None, block=None, max_iterations=1, replacements=None)[源代码]

基类:ForwardAnalysis, Analysis

XRefsAnalysis recovers in-depth x-refs (cross-references) in disassembly code.

Here is an example:

.text:
000023C8                 LDR     R2, =time_now
000023CA                 LDR     R3, [R2]
000023CC                 ADDS    R3, #1
000023CE                 STR     R3, [R2]
000023D0                 BX      LR

.bss:
1FFF36F4 time_now        % 4

You will have the following x-refs for time_now:

23c8 - offset
23ca - read access
23ce - write access
__init__(func=None, func_graph=None, block=None, max_iterations=1, replacements=None)[源代码]

Constructor

参数:
  • order_jobs (bool) -- If all jobs should be ordered or not.

  • allow_merging (bool) -- If job merging is allowed.

  • allow_widening (bool) -- If job widening is allowed.

  • graph_visitor (GraphVisitor or None) -- A graph visitor to provide successors.

返回:

None

class angr.analyses.proximity_graph.ProxiNodeTypes[源代码]

基类:object

Node Type Enums

Empty = 0
String = 1
Function = 2
FunctionCall = 3
Integer = 4
Unknown = 5
Variable = 6
class angr.analyses.proximity_graph.BaseProxiNode(type_, ref_at=None)[源代码]

基类:object

Base class for all nodes in a proximity graph.

参数:
__init__(type_, ref_at=None)[源代码]
参数:
class angr.analyses.proximity_graph.FunctionProxiNode(func, ref_at=None)[源代码]

基类:BaseProxiNode

Proximity node showing current and expanded function calls in graph.

参数:

ref_at (set[int] | None)

__init__(func, ref_at=None)[源代码]
参数:

ref_at (set[int] | None)

class angr.analyses.proximity_graph.VariableProxiNode(addr, name, ref_at=None)[源代码]

基类:BaseProxiNode

Variable arg node

参数:

ref_at (set[int] | None)

__init__(addr, name, ref_at=None)[源代码]
参数:

ref_at (set[int] | None)

class angr.analyses.proximity_graph.StringProxiNode(addr, content, ref_at=None)[源代码]

基类:BaseProxiNode

String arg node

参数:

ref_at (set[int] | None)

__init__(addr, content, ref_at=None)[源代码]
参数:

ref_at (set[int] | None)

class angr.analyses.proximity_graph.CallProxiNode(callee, ref_at=None, args=None)[源代码]

基类:BaseProxiNode

Call node

参数:
__init__(callee, ref_at=None, args=None)[源代码]
参数:
class angr.analyses.proximity_graph.IntegerProxiNode(value, ref_at=None)[源代码]

基类:BaseProxiNode

Int arg node

参数:
__init__(value, ref_at=None)[源代码]
参数:
class angr.analyses.proximity_graph.UnknownProxiNode(dummy_value)[源代码]

基类:BaseProxiNode

Unknown arg node

参数:

dummy_value (str)

__init__(dummy_value)[源代码]
参数:

dummy_value (str)

class angr.analyses.proximity_graph.ProximityGraphAnalysis(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]

基类:Analysis

Generate a proximity graph.

参数:
__init__(func, cfg_model, xrefs, decompilation=None, expand_funcs=None)[源代码]
参数:

Defines analysis that will generate a dynamic data-dependency graph

class angr.analyses.data_dep.data_dependency_analysis.NodalAnnotation(node)[源代码]

基类:Annotation

Allows a node to be stored as an annotation to a BV in a DefaultMemory instance

参数:

node (BaseDepNode)

__init__(node)[源代码]
参数:

node (BaseDepNode)

property relocatable: bool

Can not be relocated in a simplification

property eliminatable

Can not be eliminated in a simplification

class angr.analyses.data_dep.data_dependency_analysis.DataDependencyGraphAnalysis(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]

基类:Analysis

This is a DYNAMIC data dependency graph that utilizes a given SimState to produce a DDG graph that is accurate to the path the program took during execution.

This analysis utilizes the SimActionData objects present in the provided SimState's action history to generate the dependency graph.

参数:
__init__(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]
参数:
  • end_state (SimState) -- Simulation state used to extract all SimActionData

  • start_from (Optional[int]) -- An address or None, Specifies where to start generation of DDG

  • end_at (Optional[int]) -- An address or None, Specifies where to end generation of DDG

  • block_addrs (list[int] | None) -- List of block addresses that the DDG analysis should be run on

  • block_addrs

property graph: DiGraph | None
property simplified_graph: DiGraph | None
property sub_graph: DiGraph | None
get_data_dep(g_node, include_tmp_nodes, backwards)[源代码]
返回类型:

DiGraph | None

参数:
class angr.analyses.data_dep.sim_act_location.SimActLocation(bbl_addr, ins_addr, stmt_idx)[源代码]

基类:object

Structure-like class used to bundle the instruction address and statement index of a given SimAction in order to uniquely identify a given SimAction

参数:
  • bbl_addr (int)

  • ins_addr (int)

  • stmt_idx (int)

__init__(bbl_addr, ins_addr, stmt_idx)[源代码]
参数:
  • bbl_addr (int)

  • ins_addr (int)

  • stmt_idx (int)

class angr.analyses.data_dep.sim_act_location.ParsedInstruction(ins_addr, min_stmt_idx, max_stmt_idx)[源代码]

基类:object

Used by parser to facilitate linking with recent ancestors in an efficient manner

参数:
  • ins_addr (int)

  • min_stmt_idx (int)

  • max_stmt_idx (int)

__init__(ins_addr, min_stmt_idx, max_stmt_idx)[源代码]
参数:
  • ins_addr (int)

  • min_stmt_idx (int)

  • max_stmt_idx (int)

class angr.analyses.data_dep.dep_nodes.DepNodeTypes[源代码]

基类:object

Enumeration of types of BaseDepNode supported by this analysis

Memory = 1
Register = 2
Tmp = 3
Constant = 4
class angr.analyses.data_dep.dep_nodes.BaseDepNode(type_, sim_act)[源代码]

基类:object

Base class for all nodes in a data-dependency graph

参数:
__init__(type_, sim_act)[源代码]
参数:
value_tuple()[源代码]
返回类型:

tuple[BV, int]

返回:

A tuple containing the node's value as a BV and as an evaluated integer

property ast: BV
property type: int

Getter :return: An integer defined in DepNodeTypes, represents the subclass type of this DepNode.

class angr.analyses.data_dep.dep_nodes.ConstantDepNode(sim_act, value)[源代码]

基类:BaseDepNode

Used to create a DepNode that will hold a constant, numeric value Uniquely identified by its value

参数:
__init__(sim_act, value)[源代码]
参数:
class angr.analyses.data_dep.dep_nodes.MemDepNode(sim_act, addr)[源代码]

基类:BaseDepNode

Used to represent SimActions of type MEM

参数:
__init__(sim_act, addr)[源代码]
参数:
property width: int
classmethod cast_to_mem(base_dep_node)[源代码]

Casts a BaseDepNode into a MemDepNode

参数:

base_dep_node (BaseDepNode)

class angr.analyses.data_dep.dep_nodes.VarDepNode(type_, sim_act, reg, arch_name='')[源代码]

基类:BaseDepNode

Abstract class for representing SimActions of TYPE reg or tmp

参数:
__init__(type_, sim_act, reg, arch_name='')[源代码]
参数:
property display_name: str
class angr.analyses.data_dep.dep_nodes.TmpDepNode(sim_act, reg, arch_name='')[源代码]

基类:VarDepNode

Used to represent SimActions of type TMP

参数:
__init__(sim_act, reg, arch_name='')[源代码]
参数:
class angr.analyses.data_dep.dep_nodes.RegDepNode(sim_act, reg, arch_name='')[源代码]

基类:VarDepNode

Base class for representing SimActions of TYPE reg

参数:
__init__(sim_act, reg, arch_name='')[源代码]
参数:
property reg_size: int
class angr.analyses.data_dep.BaseDepNode(type_, sim_act)[源代码]

基类:object

Base class for all nodes in a data-dependency graph

参数:
__init__(type_, sim_act)[源代码]
参数:
value_tuple()[源代码]
返回类型:

tuple[BV, int]

返回:

A tuple containing the node's value as a BV and as an evaluated integer

property ast: BV
property type: int

Getter :return: An integer defined in DepNodeTypes, represents the subclass type of this DepNode.

class angr.analyses.data_dep.ConstantDepNode(sim_act, value)[源代码]

基类:BaseDepNode

Used to create a DepNode that will hold a constant, numeric value Uniquely identified by its value

参数:
__init__(sim_act, value)[源代码]
参数:
class angr.analyses.data_dep.DataDependencyGraphAnalysis(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]

基类:Analysis

This is a DYNAMIC data dependency graph that utilizes a given SimState to produce a DDG graph that is accurate to the path the program took during execution.

This analysis utilizes the SimActionData objects present in the provided SimState's action history to generate the dependency graph.

参数:
__init__(end_state, start_from=None, end_at=None, block_addrs=None)[源代码]
参数:
  • end_state (SimState) -- Simulation state used to extract all SimActionData

  • start_from (Optional[int]) -- An address or None, Specifies where to start generation of DDG

  • end_at (Optional[int]) -- An address or None, Specifies where to end generation of DDG

  • block_addrs (list[int] | None) -- List of block addresses that the DDG analysis should be run on

  • block_addrs

property graph: DiGraph | None
property simplified_graph: DiGraph | None
property sub_graph: DiGraph | None
get_data_dep(g_node, include_tmp_nodes, backwards)[源代码]
返回类型:

DiGraph | None

参数:
class angr.analyses.data_dep.DepNodeTypes[源代码]

基类:object

Enumeration of types of BaseDepNode supported by this analysis

Memory = 1
Register = 2
Tmp = 3
Constant = 4
class angr.analyses.data_dep.MemDepNode(sim_act, addr)[源代码]

基类:BaseDepNode

Used to represent SimActions of type MEM

参数:
__init__(sim_act, addr)[源代码]
参数:
property width: int
classmethod cast_to_mem(base_dep_node)[源代码]

Casts a BaseDepNode into a MemDepNode

参数:

base_dep_node (BaseDepNode)

class angr.analyses.data_dep.RegDepNode(sim_act, reg, arch_name='')[源代码]

基类:VarDepNode

Base class for representing SimActions of TYPE reg

参数:
__init__(sim_act, reg, arch_name='')[源代码]
参数:
property reg_size: int
class angr.analyses.data_dep.TmpDepNode(sim_act, reg, arch_name='')[源代码]

基类:VarDepNode

Used to represent SimActions of type TMP

参数:
__init__(sim_act, reg, arch_name='')[源代码]
参数:
class angr.analyses.data_dep.VarDepNode(type_, sim_act, reg, arch_name='')[源代码]

基类:BaseDepNode

Abstract class for representing SimActions of TYPE reg or tmp

参数:
__init__(type_, sim_act, reg, arch_name='')[源代码]
参数:
property display_name: str
exception angr.blade.BadJumpkindNotification[源代码]

基类:Exception

Notifies the caller that the jumpkind is bad (e.g., Ijk_NoDecode)

class angr.blade.Blade(graph, dst_run, dst_stmt_idx, direction='backward', project=None, cfg=None, ignore_sp=False, ignore_bp=False, ignored_regs=None, max_level=3, base_state=None, stop_at_calls=False, cross_insn_opt=False, max_predecessors=10, include_imarks=True)[源代码]

基类: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.

参数:
  • 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)[源代码]
参数:
  • 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)

返回:

None

property slice
dbg_repr(arch=None)[源代码]
class angr.slicer.SimLightState(temps=None, regs=None, stack_offsets=None, options=None)[源代码]

基类:object

Represents a program state. Only used in SimSlicer.

__init__(temps=None, regs=None, stack_offsets=None, options=None)[源代码]
temps
regs
stack_offsets
options
class angr.slicer.SimSlicer(arch, statements, target_tmps=None, target_regs=None, target_stack_offsets=None, inslice_callback=None, inslice_callback_infodict=None, include_imarks=True)[源代码]

基类:object

A super lightweight intra-IRSB slicing class.

参数:

include_imarks (bool)

__init__(arch, statements, target_tmps=None, target_regs=None, target_stack_offsets=None, inslice_callback=None, inslice_callback_infodict=None, include_imarks=True)[源代码]
参数:

include_imarks (bool)

class angr.annocfg.AnnotatedCFG(project, cfg=None, detect_loops=False)[源代码]

基类:object

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

__init__(project, cfg=None, detect_loops=False)[源代码]

Constructor.

参数:
  • project -- The angr Project instance

  • cfg -- Control flow graph.

  • detect_loops

from_digraph(digraph)[源代码]

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

Tuples like (block address, statement ID)

Those nodes are connected by edges indicating the execution flow.

参数:

digraph (networkx.DiGraph) -- A networkx.DiGraph object

get_addr(run)[源代码]
add_block_to_whitelist(block)[源代码]
add_statements_to_whitelist(block, stmt_ids)[源代码]
add_exit_to_whitelist(run_from, run_to)[源代码]
set_last_statement(block_addr, stmt_id)[源代码]
add_loop(loop_tuple)[源代码]

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

should_take_exit(addr_from, addr_to)[源代码]
should_execute_statement(addr, stmt_id)[源代码]
get_run(addr)[源代码]
get_whitelisted_statements(addr)[源代码]
返回类型:

list[int] | None

返回:

True if all statements are whitelisted

get_last_statement_index(addr)[源代码]

Get the statement index of the last statement to execute in the basic block specified by addr.

参数:

addr (int) -- Address of the basic block.

返回:

The statement index of the last statement to be executed in the block. Usually if the default exit is taken, it will be the last statement to execute. If the block is not in the slice or we should never take any exit going to this block, None is returned.

返回类型:

int or None

get_loops()[源代码]
get_targets(source_addr)[源代码]
dbg_repr()[源代码]
dbg_print_irsb(irsb_addr, project=None)[源代码]

Pretty-print an IRSB with whitelist information

keep_path(path)[源代码]

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

merge_points(path)[源代码]
successor_func(path)[源代码]

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

参数:

path -- A Path instance.

返回:

A list of all feasible Path successors.

angr.codenode.repr_addr(addr)[源代码]
class angr.codenode.CodeNode(addr, size, graph=None, thumb=False)[源代码]

基类:object

参数:
__init__(addr, size, graph=None, thumb=False)[源代码]
参数:
addr: int
size: int
thumb
set_graph(graph)[源代码]
successors()[源代码]
返回类型:

list[CodeNode]

predecessors()[源代码]
is_hook = None
class angr.codenode.BlockNode(addr, size, bytestr=None, **kwargs)[源代码]

基类:CodeNode

参数:
is_hook = False
__init__(addr, size, bytestr=None, **kwargs)[源代码]
参数:

addr (int)

bytestr
class angr.codenode.SootBlockNode(addr, size, stmts, **kwargs)[源代码]

基类:BlockNode

参数:
__init__(addr, size, stmts, **kwargs)[源代码]
stmts
class angr.codenode.HookNode(addr, size, sim_procedure, **kwargs)[源代码]

基类:CodeNode

参数:
is_hook = True
__init__(addr, size, sim_procedure, **kwargs)[源代码]
参数:

sim_procedure (type) -- the the sim_procedure class

sim_procedure
class angr.codenode.SyscallNode(addr, size, sim_procedure, **kwargs)[源代码]

基类:HookNode

参数:
is_hook = False
sim_procedure

SimOS

Manage OS-level configuration.

class angr.simos.SimCGC(project, **kwargs)[源代码]

基类:SimUserland

Environment configuration for the CGC DECREE platform

__init__(project, **kwargs)[源代码]
state_blank(flag_page=None, allocate_stack_page_count=256, **kwargs)[源代码]
参数:
  • flag_page -- Flag page content, either a string or a list of BV8s

  • allocate_stack_page_count -- Number of pages to pre-allocate for stack

state_entry(add_options=None, **kwargs)[源代码]
class angr.simos.SimJavaVM(*args, **kwargs)[源代码]

基类:SimOS

__init__(*args, **kwargs)[源代码]
state_blank(addr=None, **kwargs)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

state_entry(args=None, **kwargs)[源代码]

Create an entry state.

参数:

args -- List of SootArgument values (optional).

static generate_symbolic_cmd_line_arg(state)[源代码]

Generates a new symbolic cmd line argument string. :return: The string reference.

state_call(addr, *args, **kwargs)[源代码]

Create a native or a Java call state.

参数:
  • addr -- Soot or native addr of the invoke target.

  • args -- List of SootArgument values.

static get_default_value_by_type(type_, state)[源代码]

Java specify defaults values for primitive and reference types. This method returns the default value for a given type.

参数:
  • type (str) -- Name of type.

  • state (SimState) -- Current SimState.

返回:

Default value for this type.

static cast_primitive(state, value, to_type)[源代码]

Cast the value of primitive types.

参数:
  • value -- Bitvector storing the primitive value.

  • to_type -- Name of the targeted type.

返回:

Resized value.

static init_static_field(state, field_class_name, field_name, field_type)[源代码]

Initialize the static field with an allocated, but not initialized, object of the given type.

参数:
  • state -- State associated to the field.

  • field_class_name -- Class containing the field.

  • field_name -- Name of the field.

  • field_type -- Type of the field and the new object.

static get_cmd_line_args(state)[源代码]
get_addr_of_native_method(soot_method)[源代码]

Get address of the implementation from a native declared Java function.

参数:

soot_method -- Method descriptor of a native declared function.

返回:

CLE address of the given method.

get_native_type(java_type)[源代码]

Maps the Java type to a SimTypeReg representation of its native counterpart. This type can be used to indicate the (well-defined) size of native JNI types.

返回:

A SymTypeReg with the JNI size of the given type.

property native_arch

Arch of the native simos.

Type:

return

get_native_cc()[源代码]
返回:

SimCC object for the native simos.

class angr.simos.SimLinux(project, **kwargs)[源代码]

基类:SimUserland

OS-specific configuration for *nix-y OSes.

__init__(project, **kwargs)[源代码]
configure_project()[源代码]

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

syscall_abi(state)[源代码]

Optionally, override this function to determine which abi is being used for the state's current syscall.

state_blank(fs=None, concrete_fs=False, chroot=None, cwd=None, pathsep=b'/', thread_idx=None, init_libc=False, **kwargs)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

state_entry(args=None, env=None, argc=None, **kwargs)[源代码]
set_entry_register_values(state)[源代码]
state_full_init(**kwargs)[源代码]
prepare_function_symbol(symbol_name, basic_addr=None)[源代码]

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.

initialize_segment_register_x64(state, concrete_target)[源代码]

Set the fs register in the angr to the value of the fs register in the concrete process

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

None

initialize_gdt_x86(state, concrete_target)[源代码]

Create a GDT in the state memory and populate the segment registers. Rehook the vsyscall address using the real value in the concrete process memory

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

get_segment_register_name()[源代码]
class angr.simos.SimOS(project, name=None)[源代码]

基类:object

A class describing OS/arch-level configuration.

参数:

project (angr.Project)

__init__(project, name=None)[源代码]
参数:

project (Project)

configure_project()[源代码]

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)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

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

This function prepares a state that is executing a call instruction. If given an initial_state, it copies over all of the critical registers to it from the calling_state. Otherwise, it prepares the calling_state for action.

This is mostly used to create minimalistic for CFG generation. Some ABIs, such as MIPS PIE and x86 PIE, require certain information to be maintained in certain registers. For example, for PIE MIPS, this function transfer t9, gp, and ra to the new state.

prepare_function_symbol(symbol_name, basic_addr=None)[源代码]

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)[源代码]

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.

参数:
  • 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)[源代码]
syscall_abi(state)[源代码]
返回类型:

str

syscall_cc(state)[源代码]
返回类型:

SimCCSyscall | None

is_syscall_addr(addr)[源代码]
syscall_from_addr(addr, allow_unsupported=True)[源代码]
syscall_from_number(number, allow_unsupported=True, abi=None)[源代码]
setup_gdt(state, gdt)[源代码]

Write the GlobalDescriptorTable object in the current state memory

参数:
  • state -- state in which to write the GDT

  • gdt -- GlobalDescriptorTable object

返回:

generate_gdt(fs, gs, fs_size=4294967295, gs_size=4294967295)[源代码]

Generate a GlobalDescriptorTable object and populate it using the value of the gs and fs register

参数:
  • 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

返回:

gdt a GlobalDescriptorTable object

class angr.simos.SimSnimmucNxp(project, name=None, **kwargs)[源代码]

基类:SimOS

This class implements the "OS" for a bare-metal firmware used at an imaginary company.

参数:

project (Project)

__init__(project, name=None, **kwargs)[源代码]
参数:

project (Project)

configure_project()[源代码]

Configure the project to set up global settings (like SimProcedures).

class angr.simos.SimUserland(project, syscall_library=None, syscall_addr_alignment=4, **kwargs)[源代码]

基类:SimOS

This is a base class for any SimOS that wants to support syscalls.

It uses the CLE kernel object to provide addresses for syscalls. Syscalls will be emulated as a jump to one of these addresses, where a SimProcedure from the syscall library provided at construction time will be executed.

__init__(project, syscall_library=None, syscall_addr_alignment=4, **kwargs)[源代码]
configure_project(abi_list=None)[源代码]

Configure the project to set up global settings (like SimProcedures).

syscall_cc(state)[源代码]
返回类型:

SimCCSyscall

syscall(state, allow_unsupported=True)[源代码]

Given a state, return the procedure corresponding to the current syscall. This procedure will have .syscall_number, .display_name, and .addr set.

参数:
  • state -- The state to get the syscall number from

  • allow_unsupported -- Whether to return a "dummy" sycall instead of raising an unsupported exception

syscall_abi(state)[源代码]

Optionally, override this function to determine which abi is being used for the state's current syscall.

is_syscall_addr(addr)[源代码]

Return whether or not the given address corresponds to a syscall implementation.

syscall_from_addr(addr, allow_unsupported=True)[源代码]

Get a syscall SimProcedure from an address.

参数:
  • addr -- The address to convert to a syscall SimProcedure

  • allow_unsupported -- Whether to return a dummy procedure for an unsupported syscall instead of raising an exception.

返回:

The SimProcedure for the syscall, or None if the address is not a syscall address.

syscall_from_number(number, allow_unsupported=True, abi=None)[源代码]

Get a syscall SimProcedure from its number.

参数:
  • number -- The syscall number

  • allow_unsupported -- Whether to return a "stub" syscall for unsupported numbers instead of throwing an error

  • abi -- The name of the abi to use. If None, will assume that the abis have disjoint numbering schemes and pick the right one.

返回:

The SimProcedure for the syscall

class angr.simos.SimWindows(project)[源代码]

基类:SimOS

Environment for the Windows Win32 subsystem. Does not support syscalls currently.

__init__(project)[源代码]
configure_project()[源代码]

Configure the project to set up global settings (like SimProcedures).

state_entry(args=None, env=None, argc=None, **kwargs)[源代码]
state_blank(thread_idx=None, **kwargs)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

handle_exception(successors, engine, exception)[源代码]

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.

参数:
  • successors -- The SimSuccessors object currently being executed on

  • engine -- The engine that was processing this step

  • exception -- The actual exception object

initialize_segment_register_x64(state, concrete_target)[源代码]

Set the gs register in the angr to the value of the fs register in the concrete process

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

None

initialize_gdt_x86(state, concrete_target)[源代码]

Create a GDT in the state memory and populate the segment registers.

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

the created GlobalDescriptorTable object

get_segment_register_name()[源代码]
class angr.simos.simos.SimOS(project, name=None)[源代码]

基类:object

A class describing OS/arch-level configuration.

参数:

project (angr.Project)

__init__(project, name=None)[源代码]
参数:

project (Project)

configure_project()[源代码]

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)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

state_entry(**kwargs)[源代码]
state_full_init(**kwargs)[源代码]
state_call(addr, *args, **kwargs)[源代码]
prepare_call_state(calling_state, initial_state=None, preserve_registers=(), preserve_memory=())[源代码]

This function prepares a state that is executing a call instruction. If given an initial_state, it copies over all of the critical registers to it from the calling_state. Otherwise, it prepares the calling_state for action.

This is mostly used to create minimalistic for CFG generation. Some ABIs, such as MIPS PIE and x86 PIE, require certain information to be maintained in certain registers. For example, for PIE MIPS, this function transfer t9, gp, and ra to the new state.

prepare_function_symbol(symbol_name, basic_addr=None)[源代码]

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)[源代码]

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.

参数:
  • 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)[源代码]
syscall_abi(state)[源代码]
返回类型:

str

syscall_cc(state)[源代码]
返回类型:

SimCCSyscall | None

is_syscall_addr(addr)[源代码]
syscall_from_addr(addr, allow_unsupported=True)[源代码]
syscall_from_number(number, allow_unsupported=True, abi=None)[源代码]
setup_gdt(state, gdt)[源代码]

Write the GlobalDescriptorTable object in the current state memory

参数:
  • state -- state in which to write the GDT

  • gdt -- GlobalDescriptorTable object

返回:

generate_gdt(fs, gs, fs_size=4294967295, gs_size=4294967295)[源代码]

Generate a GlobalDescriptorTable object and populate it using the value of the gs and fs register

参数:
  • 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

返回:

gdt a GlobalDescriptorTable object

class angr.simos.simos.GlobalDescriptorTable(addr, limit, table, gdt_sel, cs_sel, ds_sel, es_sel, ss_sel, fs_sel, gs_sel)[源代码]

基类:object

GlobalDescriptorTable object to store the GDT table and the segment registers values

__init__(addr, limit, table, gdt_sel, cs_sel, ds_sel, es_sel, ss_sel, fs_sel, gs_sel)[源代码]
class angr.simos.linux.SimLinux(project, **kwargs)[源代码]

基类:SimUserland

OS-specific configuration for *nix-y OSes.

__init__(project, **kwargs)[源代码]
configure_project()[源代码]

Configure the project to set up global settings (like SimProcedures).

syscall_abi(state)[源代码]

Optionally, override this function to determine which abi is being used for the state's current syscall.

state_blank(fs=None, concrete_fs=False, chroot=None, cwd=None, pathsep=b'/', thread_idx=None, init_libc=False, **kwargs)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

state_entry(args=None, env=None, argc=None, **kwargs)[源代码]
set_entry_register_values(state)[源代码]
state_full_init(**kwargs)[源代码]
prepare_function_symbol(symbol_name, basic_addr=None)[源代码]

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.

initialize_segment_register_x64(state, concrete_target)[源代码]

Set the fs register in the angr to the value of the fs register in the concrete process

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

None

initialize_gdt_x86(state, concrete_target)[源代码]

Create a GDT in the state memory and populate the segment registers. Rehook the vsyscall address using the real value in the concrete process memory

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

get_segment_register_name()[源代码]
class angr.simos.cgc.SimCGC(project, **kwargs)[源代码]

基类:SimUserland

Environment configuration for the CGC DECREE platform

__init__(project, **kwargs)[源代码]
state_blank(flag_page=None, allocate_stack_page_count=256, **kwargs)[源代码]
参数:
  • flag_page -- Flag page content, either a string or a list of BV8s

  • allocate_stack_page_count -- Number of pages to pre-allocate for stack

state_entry(add_options=None, **kwargs)[源代码]
class angr.simos.userland.SimUserland(project, syscall_library=None, syscall_addr_alignment=4, **kwargs)[源代码]

基类:SimOS

This is a base class for any SimOS that wants to support syscalls.

It uses the CLE kernel object to provide addresses for syscalls. Syscalls will be emulated as a jump to one of these addresses, where a SimProcedure from the syscall library provided at construction time will be executed.

__init__(project, syscall_library=None, syscall_addr_alignment=4, **kwargs)[源代码]
configure_project(abi_list=None)[源代码]

Configure the project to set up global settings (like SimProcedures).

syscall_cc(state)[源代码]
返回类型:

SimCCSyscall

syscall(state, allow_unsupported=True)[源代码]

Given a state, return the procedure corresponding to the current syscall. This procedure will have .syscall_number, .display_name, and .addr set.

参数:
  • state -- The state to get the syscall number from

  • allow_unsupported -- Whether to return a "dummy" sycall instead of raising an unsupported exception

syscall_abi(state)[源代码]

Optionally, override this function to determine which abi is being used for the state's current syscall.

is_syscall_addr(addr)[源代码]

Return whether or not the given address corresponds to a syscall implementation.

syscall_from_addr(addr, allow_unsupported=True)[源代码]

Get a syscall SimProcedure from an address.

参数:
  • addr -- The address to convert to a syscall SimProcedure

  • allow_unsupported -- Whether to return a dummy procedure for an unsupported syscall instead of raising an exception.

返回:

The SimProcedure for the syscall, or None if the address is not a syscall address.

syscall_from_number(number, allow_unsupported=True, abi=None)[源代码]

Get a syscall SimProcedure from its number.

参数:
  • number -- The syscall number

  • allow_unsupported -- Whether to return a "stub" syscall for unsupported numbers instead of throwing an error

  • abi -- The name of the abi to use. If None, will assume that the abis have disjoint numbering schemes and pick the right one.

返回:

The SimProcedure for the syscall

class angr.simos.windows.SecurityCookieInit(value)[源代码]

基类:Enum

An enumeration.

NONE = 0
RANDOM = 1
STATIC = 2
SYMBOLIC = 3
class angr.simos.windows.SimWindows(project)[源代码]

基类:SimOS

Environment for the Windows Win32 subsystem. Does not support syscalls currently.

__init__(project)[源代码]
configure_project()[源代码]

Configure the project to set up global settings (like SimProcedures).

state_entry(args=None, env=None, argc=None, **kwargs)[源代码]
state_blank(thread_idx=None, **kwargs)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

handle_exception(successors, engine, exception)[源代码]

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.

参数:
  • successors -- The SimSuccessors object currently being executed on

  • engine -- The engine that was processing this step

  • exception -- The actual exception object

initialize_segment_register_x64(state, concrete_target)[源代码]

Set the gs register in the angr to the value of the fs register in the concrete process

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

None

initialize_gdt_x86(state, concrete_target)[源代码]

Create a GDT in the state memory and populate the segment registers.

参数:
  • state -- state which will be modified

  • concrete_target -- concrete target that will be used to read the fs register

返回:

the created GlobalDescriptorTable object

get_segment_register_name()[源代码]
class angr.simos.javavm.SimJavaVM(*args, **kwargs)[源代码]

基类:SimOS

__init__(*args, **kwargs)[源代码]
state_blank(addr=None, **kwargs)[源代码]

Initialize a blank state.

All parameters are optional.

参数:
  • 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.

返回:

The initialized SimState.

Any additional arguments will be passed to the SimState constructor

state_entry(args=None, **kwargs)[源代码]

Create an entry state.

参数:

args -- List of SootArgument values (optional).

static generate_symbolic_cmd_line_arg(state)[源代码]

Generates a new symbolic cmd line argument string. :return: The string reference.

state_call(addr, *args, **kwargs)[源代码]

Create a native or a Java call state.

参数:
  • addr -- Soot or native addr of the invoke target.

  • args -- List of SootArgument values.

static get_default_value_by_type(type_, state)[源代码]

Java specify defaults values for primitive and reference types. This method returns the default value for a given type.

参数:
  • type (str) -- Name of type.

  • state (SimState) -- Current SimState.

返回:

Default value for this type.

static cast_primitive(state, value, to_type)[源代码]

Cast the value of primitive types.

参数:
  • value -- Bitvector storing the primitive value.

  • to_type -- Name of the targeted type.

返回:

Resized value.

static init_static_field(state, field_class_name, field_name, field_type)[源代码]

Initialize the static field with an allocated, but not initialized, object of the given type.

参数:
  • state -- State associated to the field.

  • field_class_name -- Class containing the field.

  • field_name -- Name of the field.

  • field_type -- Type of the field and the new object.

static get_cmd_line_args(state)[源代码]
get_addr_of_native_method(soot_method)[源代码]

Get address of the implementation from a native declared Java function.

参数:

soot_method -- Method descriptor of a native declared function.

返回:

CLE address of the given method.

get_native_type(java_type)[源代码]

Maps the Java type to a SimTypeReg representation of its native counterpart. This type can be used to indicate the (well-defined) size of native JNI types.

返回:

A SymTypeReg with the JNI size of the given type.

property native_arch

Arch of the native simos.

Type:

return

get_native_cc()[源代码]
返回:

SimCC object for the native simos.

angr.simos.javavm.prepare_native_return_state(native_state)[源代码]

Hook target for native function call returns.

Recovers and stores the return value from native memory and toggles the state, s.t. execution continues in the Soot engine.

Note: Redirection needed for pickling.

Function Signature Matching

class angr.flirt.FlirtSignature(arch, platform, sig_name, sig_path, unique_strings=None, compiler=None, compiler_version=None, os_name=None, os_version=None)[源代码]

基类:object

This class describes a FLIRT signature.

参数:
  • arch (str)

  • platform (str)

  • sig_name (str)

  • sig_path (str)

  • unique_strings (set[str] | None)

  • compiler (str | None)

  • compiler_version (str | None)

  • os_name (str | None)

  • os_version (str | None)

__init__(arch, platform, sig_name, sig_path, unique_strings=None, compiler=None, compiler_version=None, os_name=None, os_version=None)[源代码]
参数:
  • arch (str)

  • platform (str)

  • sig_name (str)

  • sig_path (str)

  • unique_strings (set[str] | None)

  • compiler (str | None)

  • compiler_version (str | None)

  • os_name (str | None)

  • os_version (str | None)

angr.flirt.FS

FlirtSignature 的别名

angr.flirt.load_signatures(path)[源代码]

Recursively load all FLIRT signatures under a specific path.

参数:

path (str) -- Location of FLIRT signatures.

返回类型:

None

angr.flirt.build_sig.get_basic_info(ar_path)[源代码]

Get basic information of the archive file.

返回类型:

dict[str, str]

参数:

ar_path (str)

angr.flirt.build_sig.get_unique_strings(ar_path)[源代码]

For Linux libraries, this method requires ar (from binutils), nm (from binutils), and strings.

返回类型:

list[str]

参数:

ar_path (str)

angr.flirt.build_sig.run_pelf(pelf_path, ar_path, output_path)[源代码]
参数:
  • pelf_path (str)

  • ar_path (str)

  • output_path (str)

angr.flirt.build_sig.run_sigmake(sigmake_path, sig_name, pat_path, sig_path)[源代码]
参数:
  • sigmake_path (str)

  • sig_name (str)

  • pat_path (str)

  • sig_path (str)

angr.flirt.build_sig.process_exc_file(exc_path)[源代码]

We are doing the stupidest thing possible: For each batch of conflicts, we pick the most likely result based on a set of predefined rules.

TODO: Add caller-callee-based de-duplication.

参数:

exc_path (str)

angr.flirt.build_sig.main()[源代码]

Utils

angr.utils.is_pyinstaller()[源代码]

Detect if we are currently running as a PyInstaller-packaged program.

返回类型:

bool

返回:

True if we are running as a PyInstaller-packaged program. False if we are running in Python directly (e.g., development mode).

angr.utils.looks_like_sql(s)[源代码]

Determine if string s looks like an SQL query.

参数:

s (str) -- The string to detect.

返回类型:

bool

返回:

True if the string looks like an SQL, False otherwise.

angr.utils.timethis(func)[源代码]
angr.utils.algo.binary_insert(lst, elem, key, lo=0, hi=None)[源代码]

Insert an element into a sorted list, and keep the list sorted.

The major difference from bisect.bisect_left is that this function supports a key method, so user doesn't have to create the key array for each insertion.

参数:
  • lst (list) -- The list. Must be pre-ordered.

  • element (object) -- An element to insert into the list.

  • key (func) -- A method to get the key for each element in the list.

  • lo (int) -- Lower bound of the search.

  • hi (int) -- Upper bound of the search.

  • elem (Any)

返回类型:

None

返回:

None

angr.utils.constants.is_alignment_mask(n)[源代码]
class angr.utils.cowdict.ChainMapCOW(*args, collapse_threshold=None)[源代码]

基类:ChainMap

Implements a copy-on-write version of ChainMap that supports auto-collapsing.

__init__(*args, collapse_threshold=None)[源代码]

Initialize a ChainMap by setting maps to the given mappings. If no mappings are provided, a single empty dictionary is used.

copy()[源代码]

New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]

clean()[源代码]
class angr.utils.cowdict.DefaultChainMapCOW(*args, default_factory=None, collapse_threshold=None)[源代码]

基类:ChainMapCOW

Implements a copy-on-write version of ChainMap with default values that supports auto-collapsing.

__init__(*args, default_factory=None, collapse_threshold=None)[源代码]

Initialize a ChainMap by setting maps to the given mappings. If no mappings are provided, a single empty dictionary is used.

clean()[源代码]
class angr.utils.dynamic_dictlist.DynamicDictList(max_size=None, content=None)[源代码]

基类:Generic[VT]

A list-like container class that internally uses dicts to store values when the number of values is less than the threshold LIST2DICT_THRESHOLD. Keys must be ints.

The default thresholds are determined according to experiments described at https://github.com/angr/angr/pull/3471#issuecomment-1236515950.

参数:
__init__(max_size=None, content=None)[源代码]
参数:
list_content: list[TypeVar(VT)] | None
max_size
dict_content: dict[int, TypeVar(VT)] | None
real_length()[源代码]
返回类型:

int

angr.utils.enums_conv.cfg_jumpkind_to_pb(jk)[源代码]
angr.utils.enums_conv.func_edge_type_to_pb(jk)[源代码]
angr.utils.enums_conv.cfg_jumpkind_from_pb(pb)[源代码]
angr.utils.enums_conv.func_edge_type_from_pb(pb)[源代码]
angr.utils.env.is_pyinstaller()[源代码]

Detect if we are currently running as a PyInstaller-packaged program.

返回类型:

bool

返回:

True if we are running as a PyInstaller-packaged program. False if we are running in Python directly (e.g., development mode).

angr.utils.graph.shallow_reverse(g)[源代码]

Make a shallow copy of a directional graph and reverse the edges. This is a workaround to solve the issue that one cannot easily make a shallow reversed copy of a graph in NetworkX 2, since networkx.reverse(copy=False) now returns a GraphView, and GraphViews are always read-only.

参数:

g (networkx.DiGraph) -- The graph to reverse.

返回类型:

DiGraph

返回:

A new networkx.DiGraph that has all nodes and all edges of the original graph, with edges reversed.

angr.utils.graph.inverted_idoms(graph)[源代码]

Invert the given graph and generate the immediate dominator tree on the inverted graph. This is useful for computing post-dominators.

参数:

graph (DiGraph) -- The graph to invert and generate immediate dominator tree for.

返回类型:

tuple[DiGraph, dict | None]

返回:

A tuple of the inverted graph and the immediate dominator tree.

angr.utils.graph.to_acyclic_graph(graph, ordered_nodes=None, loop_heads=None)[源代码]

Convert a given DiGraph into an acyclic graph.

参数:
  • graph (DiGraph) -- The graph to convert.

  • ordered_nodes (Optional[list]) -- A list of nodes sorted in a topological order.

  • loop_heads (Optional[list]) -- A list of known loop head nodes.

返回类型:

DiGraph

返回:

The converted acyclic graph.

angr.utils.graph.dfs_back_edges(graph, start_node)[源代码]

Perform an iterative DFS traversal of the graph, returning back edges.

参数:
  • graph -- The graph to traverse.

  • start_node -- The node where to start the traversal.

返回:

An iterator of 'backward' edges.

angr.utils.graph.subgraph_between_nodes(graph, source, frontier, include_frontier=False)[源代码]

For a directed graph, return a subgraph that includes all nodes going from a source node to a target node.

参数:
  • graph (networkx.DiGraph) -- The directed graph.

  • source -- The source node.

  • frontier (list) -- A collection of target nodes.

  • include_frontier (bool) -- Should nodes in frontier be included in the subgraph.

返回:

A subgraph.

返回类型:

networkx.DiGraph

angr.utils.graph.dominates(idom, dominator_node, node)[源代码]
angr.utils.graph.compute_dominance_frontier(graph, domtree)[源代码]

Compute a dominance frontier based on the given post-dominator tree.

This implementation is based on figure 2 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc.

参数:
  • graph -- The graph where we want to compute the dominance frontier.

  • domtree -- The dominator tree

返回:

A dict of dominance frontier

class angr.utils.graph.TemporaryNode(label)[源代码]

基类:object

A temporary node.

Used as the start node and end node in post-dominator tree generation. Also used in some test cases.

__init__(label)[源代码]
class angr.utils.graph.ContainerNode(obj)[源代码]

基类:object

A container node.

Only used in dominator tree generation. We did this so we can set the index property without modifying the original object.

__init__(obj)[源代码]
index
property obj
class angr.utils.graph.Dominators(graph, entry_node, successors_func=None, reverse=False)[源代码]

基类:object

Describes dominators in a graph.

__init__(graph, entry_node, successors_func=None, reverse=False)[源代码]
dom: DiGraph
class angr.utils.graph.PostDominators(graph, entry_node, successors_func=None)[源代码]

基类:Dominators

Describe post-dominators in a graph.

__init__(graph, entry_node, successors_func=None)[源代码]
property post_dom: DiGraph
class angr.utils.graph.SCCPlaceholder(scc_id)[源代码]

基类:object

Describes a placeholder for strongly-connected-components in a graph.

__init__(scc_id)[源代码]
scc_id
class angr.utils.graph.GraphUtils[源代码]

基类:object

A helper class with some static methods and algorithms implemented, that in fact, might take more than just normal CFGs.

static find_merge_points(function_addr, function_endpoints, graph)[源代码]

Given a local transition graph of a function, find all merge points inside, and then perform a quasi-topological sort of those merge points.

A merge point might be one of the following cases: - two or more paths come together, and ends at the same address. - end of the current function

参数:
  • function_addr (int) -- Address of the function.

  • function_endpoints (list) -- Endpoints of the function. They typically come from Function.endpoints.

  • graph (networkx.DiGraph) -- A local transition graph of a function. Normally it comes from Function.graph.

返回:

A list of ordered addresses of merge points.

返回类型:

list

static find_widening_points(function_addr, function_endpoints, graph)[源代码]

Given a local transition graph of a function, find all widening points inside.

Correctly choosing widening points is very important in order to not lose too much information during static analysis. We mainly consider merge points that has at least one loop back edges coming in as widening points.

参数:
  • function_addr (int) -- Address of the function.

  • function_endpoints (list) -- Endpoints of the function, typically coming from Function.endpoints.

  • graph (networkx.DiGraph) -- A local transition graph of a function, normally Function.graph.

返回:

A list of addresses of widening points.

返回类型:

list

static reverse_post_order_sort_nodes(graph, nodes=None)[源代码]

Sort a given set of nodes in reverse post ordering.

参数:
  • graph (networkx.DiGraph) -- A local transition graph of a function.

  • nodes (iterable) -- A collection of nodes to sort.

返回:

A list of sorted nodes.

返回类型:

list

static quasi_topological_sort_nodes(graph, nodes=None, loop_heads=None)[源代码]

Sort a given set of nodes from a graph based on the following rules:

# - if A -> B and not B -> A, then we have A < B # - if A -> B and B -> A, then the ordering is undefined

Following the above rules gives us a quasi-topological sorting of nodes in the graph. It also works for cyclic graphs.

参数:
  • graph (DiGraph) -- A local transition graph of the function.

  • nodes (Optional[list]) -- A list of nodes to sort. None if you want to sort all nodes inside the graph.

  • loop_heads (Optional[list]) -- A list of nodes that should be treated loop heads.

返回类型:

list

返回:

A list of ordered nodes.

static loop_nesting_forest(graph, start_node)[源代码]

Generates the loop-nesting forest for the provided directional graph. This is not the algorithm proposed by Ramalingam.

参数:
  • graph (DiGraph) -- the graph to generate the loop-nesting forest for.

  • start_node -- the node to start traversing the graph from.

返回类型:

OrderedDict[Any, DiGraph]

返回:

An ordered dict of loop heads to their corresponding loop nodes.

angr.utils.lazy_import.lazy_import(name)[源代码]
angr.utils.loader.is_pc(project, ins_addr, addr)[源代码]

Check if the given address is program counter (PC) or not. This function is for handling the case on some bizarre architectures where PC is always the currently executed instruction address plus a constant value.

参数:
  • project (Project) -- An angr Project instance.

  • ins_addr (int) -- The address of an instruction. We calculate PC using this instruction address.

  • addr (int) -- The address to check against.

返回类型:

bool

返回:

True if the given instruction address is the PC, False otherwise.

angr.utils.loader.is_in_readonly_section(project, addr)[源代码]

Check if the specified address is inside a read-only section.

参数:
  • project (Project) -- An angr Project instance.

  • addr (int) -- The address to check.

返回类型:

bool

返回:

True if the given address belongs to a read-only section, False otherwise.

angr.utils.loader.is_in_readonly_segment(project, addr)[源代码]

Check if the specified address is inside a read-only segment.

参数:
  • project (Project) -- An angr Project instance.

  • addr (int) -- The address to check.

返回类型:

bool

返回:

True if the given address belongs to a read-only segment, False otherwise.

angr.utils.library.get_function_name(s)[源代码]

Get the function name from a C-style function declaration string.

参数:

s (str) -- A C-style function declaration string.

返回:

The function name.

返回类型:

str

angr.utils.library.register_kernel_types()[源代码]
angr.utils.library.convert_cproto_to_py(c_decl)[源代码]

Convert a C-style function declaration string to its corresponding SimTypes-based Python representation.

参数:

c_decl (str) -- The C-style function declaration string.

返回类型:

tuple[str, SimTypeFunction, str]

返回:

A tuple of the function name, the prototype, and a string representing the SimType-based Python representation.

angr.utils.library.convert_cppproto_to_py(cpp_decl, with_param_names=False)[源代码]

Pre-process a C++-style function declaration string to its corresponding SimTypes-based Python representation.

参数:
  • cpp_decl (str) -- The C++-style function declaration string.

  • with_param_names (bool)

返回类型:

tuple[str | None, SimTypeCppFunction | None, str | None]

返回:

A tuple of the function name, the prototype, and a string representing the SimType-based Python representation.

angr.utils.library.parsedcprotos2py(parsed_cprotos, fd_spots=frozenset({}), remove_sys_prefix=False)[源代码]

Parse a list of C function declarations and output to Python code that can be embedded into angr.procedures.definitions.

>>> # parse the list of glibc C prototypes and output to a file
>>> from angr.procedures.definitions import glibc
>>> with open("glibc_protos", "w") as f: f.write(cprotos2py(glibc._libc_c_decls))
参数:

parsed_cprotos (list[tuple[str, SimTypeFunction, str]]) -- A list of tuples where each tuple is (function name, parsed C function prototype, the original function declaration).

返回类型:

str

返回:

A Python string.

angr.utils.library.cprotos2py(cprotos, fd_spots=frozenset({}), remove_sys_prefix=False)[源代码]

Parse a list of C function declarations and output to Python code that can be embedded into angr.procedures.definitions.

>>> # parse the list of glibc C prototypes and output to a file
>>> from angr.procedures.definitions import glibc
>>> with open("glibc_protos", "w") as f: f.write(cprotos2py(glibc._libc_c_decls))
参数:

cprotos (list[str]) -- A list of C prototype strings.

返回类型:

str

返回:

A Python string.

angr.utils.library.get_cpp_function_name(demangled_name, specialized=True, qualified=True)[源代码]
angr.utils.timing.print_timing_total()[源代码]
angr.utils.timing.timethis(func)[源代码]
angr.utils.formatting.setup_terminal()[源代码]

Check if we are running in a TTY. If so, make sure the terminal supports ANSI escape sequences. If not, disable colorized output. Sets global ansi_color_enabled to True if colorized output should be enabled by default.

angr.utils.formatting.ansi_color(s, color)[源代码]

Colorize string s by wrapping in ANSI escape sequence for given color.

This function does not consider whether escape sequences are functional or not; it is up to the caller to determine if its appropriate. Check global ansi_color_enabled value in this module.

返回类型:

str

参数:
angr.utils.formatting.add_edge_to_buffer(buf, ref, start, end, formatter=None, dashed=False, ascii_only=None)[源代码]

Draw an edge by adding Unicode box and arrow glyphs to beginning of each line in a list of lines.

参数:
  • buf (Sequence[str]) -- Output buffer, used to render formatted edges.

  • ref (Sequence[str]) -- Reference buffer, used to calculate edge depth.

  • start (int) -- Start line.

  • end (int) -- End line, where arrow points.

  • formatter (Optional[Callable[[str], str]]) -- Optional callback function used to format the edge before writing it to output buffer.

  • dashed (bool) -- Render edge line dashed instead of solid.

  • ascii_only (Optional[bool]) -- Render edge using ASCII characters only. If unspecified, guess by stdout encoding.

返回:

class angr.utils.mp.Closure(f: Callable[..., None], args: list[Any], kwargs: dict[str, Any])[源代码]

基类:NamedTuple

A pickle-able lambda; note that f, args, and kwargs must be pickleable

参数:
f: Callable[..., None]

Alias for field number 0

args: list[Any]

Alias for field number 1

kwargs: dict[str, Any]

Alias for field number 2

class angr.utils.mp.Initializer(*, _manual=True)[源代码]

基类:object

A singleton class with global state used to initialize a multiprocessing.Process

参数:

_manual (bool)

classmethod get()[源代码]

A wrapper around init since this class is a singleton

返回类型:

Initializer

__init__(*, _manual=True)[源代码]
参数:

_manual (bool)

register(f, *args, **kwargs)[源代码]

A shortcut for adding Closures as initializers

返回类型:

None

参数:
initialize()[源代码]

Initialize a multiprocessing.Process Set the current global initializer to the same state as this initializer, then calls each initializer

返回类型:

None

angr.utils.mp.mp_context()[源代码]

Errors

exception angr.errors.AngrError[源代码]

基类:Exception

exception angr.errors.AngrRuntimeError[源代码]

基类:RuntimeError

exception angr.errors.AngrValueError[源代码]

基类:AngrError, ValueError

exception angr.errors.AngrLifterError[源代码]

基类:AngrError

exception angr.errors.AngrExitError[源代码]

基类:AngrError

exception angr.errors.AngrPathError[源代码]

基类:AngrError

exception angr.errors.AngrVaultError[源代码]

基类:AngrError

exception angr.errors.PathUnreachableError[源代码]

基类:AngrPathError

exception angr.errors.SimulationManagerError[源代码]

基类:AngrError

exception angr.errors.AngrInvalidArgumentError[源代码]

基类:AngrError

exception angr.errors.AngrSurveyorError[源代码]

基类:AngrError

exception angr.errors.AngrAnalysisError[源代码]

基类:AngrError

exception angr.errors.AngrBladeError[源代码]

基类:AngrError

exception angr.errors.AngrBladeSimProcError[源代码]

基类:AngrBladeError

exception angr.errors.AngrAnnotatedCFGError[源代码]

基类:AngrError

exception angr.errors.AngrBackwardSlicingError[源代码]

基类:AngrError

exception angr.errors.AngrCallableError[源代码]

基类:AngrSurveyorError

exception angr.errors.AngrCallableMultistateError[源代码]

基类:AngrCallableError

exception angr.errors.AngrSyscallError[源代码]

基类:AngrError

exception angr.errors.AngrSimOSError[源代码]

基类:AngrError

exception angr.errors.AngrAssemblyError[源代码]

基类:AngrError

exception angr.errors.AngrTypeError[源代码]

基类:AngrError, TypeError

exception angr.errors.AngrMissingTypeError[源代码]

基类:AngrTypeError

exception angr.errors.AngrIncongruencyError[源代码]

基类:AngrAnalysisError

exception angr.errors.AngrForwardAnalysisError[源代码]

基类:AngrError

exception angr.errors.AngrSkipJobNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.errors.AngrDelayJobNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.errors.AngrJobMergingFailureNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.errors.AngrJobWideningFailureNotice[源代码]

基类:AngrForwardAnalysisError

exception angr.errors.AngrCFGError[源代码]

基类:AngrError

exception angr.errors.AngrVFGError[源代码]

基类:AngrError

exception angr.errors.AngrVFGRestartAnalysisNotice[源代码]

基类:AngrVFGError

exception angr.errors.AngrDataGraphError[源代码]

基类:AngrAnalysisError

exception angr.errors.AngrDDGError[源代码]

基类:AngrAnalysisError

exception angr.errors.AngrLoopAnalysisError[源代码]

基类:AngrAnalysisError

exception angr.errors.AngrExplorationTechniqueError[源代码]

基类:AngrError

exception angr.errors.AngrExplorerError[源代码]

基类:AngrExplorationTechniqueError

exception angr.errors.AngrDirectorError[源代码]

基类:AngrExplorationTechniqueError

exception angr.errors.AngrTracerError[源代码]

基类:AngrExplorationTechniqueError

exception angr.errors.AngrVariableRecoveryError[源代码]

基类:AngrAnalysisError

exception angr.errors.AngrDBError[源代码]

基类:AngrError

exception angr.errors.AngrCorruptDBError[源代码]

基类:AngrDBError

exception angr.errors.AngrIncompatibleDBError[源代码]

基类:AngrDBError

exception angr.errors.TracerEnvironmentError[源代码]

基类:AngrError

exception angr.errors.SimError[源代码]

基类:Exception

bbl_addr = None
stmt_idx = None
ins_addr = None
executed_instruction_count = None
guard = None
record_state(state)[源代码]
exception angr.errors.SimStateError[源代码]

基类:SimError

exception angr.errors.SimMergeError[源代码]

基类:SimStateError

exception angr.errors.SimMemoryError[源代码]

基类:SimStateError

exception angr.errors.SimMemoryMissingError(missing_addr, missing_size, *args)[源代码]

基类:SimMemoryError

__init__(missing_addr, missing_size, *args)[源代码]
exception angr.errors.SimAbstractMemoryError[源代码]

基类:SimMemoryError

exception angr.errors.SimRegionMapError[源代码]

基类:SimMemoryError

exception angr.errors.SimMemoryLimitError[源代码]

基类:SimMemoryError

exception angr.errors.SimMemoryAddressError[源代码]

基类:SimMemoryError

exception angr.errors.SimFastMemoryError[源代码]

基类:SimMemoryError

exception angr.errors.SimEventError[源代码]

基类:SimStateError

exception angr.errors.SimPosixError[源代码]

基类:SimStateError

exception angr.errors.SimFilesystemError[源代码]

基类:SimError

exception angr.errors.SimSymbolicFilesystemError[源代码]

基类:SimFilesystemError

exception angr.errors.SimFileError[源代码]

基类:SimMemoryError, SimFilesystemError

exception angr.errors.SimHeapError[源代码]

基类:SimStateError

exception angr.errors.SimUnsupportedError[源代码]

基类:SimError

exception angr.errors.SimSolverError[源代码]

基类:SimError

exception angr.errors.SimSolverModeError[源代码]

基类:SimSolverError

exception angr.errors.SimSolverOptionError[源代码]

基类:SimSolverError

exception angr.errors.SimValueError[源代码]

基类:SimSolverError

exception angr.errors.SimUnsatError[源代码]

基类:SimValueError

exception angr.errors.SimOperationError[源代码]

基类:SimError

exception angr.errors.UnsupportedIROpError[源代码]

基类:SimOperationError, SimUnsupportedError

exception angr.errors.SimExpressionError[源代码]

基类:SimError

exception angr.errors.UnsupportedIRExprError[源代码]

基类:SimExpressionError, SimUnsupportedError

exception angr.errors.SimCCallError[源代码]

基类:SimExpressionError

exception angr.errors.UnsupportedCCallError[源代码]

基类:SimCCallError, SimUnsupportedError

exception angr.errors.SimUninitializedAccessError(expr_type, expr)[源代码]

基类:SimExpressionError

__init__(expr_type, expr)[源代码]
exception angr.errors.SimStatementError[源代码]

基类:SimError

exception angr.errors.UnsupportedIRStmtError[源代码]

基类:SimStatementError, SimUnsupportedError

exception angr.errors.UnsupportedDirtyError[源代码]

基类:UnsupportedIRStmtError, SimUnsupportedError

exception angr.errors.SimMissingTempError[源代码]

基类:SimValueError, IndexError

exception angr.errors.SimEngineError[源代码]

基类:SimError

exception angr.errors.SimIRSBError[源代码]

基类:SimEngineError

exception angr.errors.SimTranslationError[源代码]

基类:SimEngineError

exception angr.errors.SimProcedureError[源代码]

基类:SimEngineError

exception angr.errors.SimProcedureArgumentError[源代码]

基类:SimProcedureError

exception angr.errors.SimShadowStackError[源代码]

基类:SimProcedureError

exception angr.errors.SimFastPathError[源代码]

基类:SimEngineError

exception angr.errors.SimIRSBNoDecodeError[源代码]

基类:SimIRSBError

exception angr.errors.AngrUnsupportedSyscallError[源代码]

基类:AngrSyscallError, SimProcedureError, SimUnsupportedError

angr.errors.UnsupportedSyscallError

AngrUnsupportedSyscallError 的别名

exception angr.errors.SimReliftException(state)[源代码]

基类:SimEngineError

__init__(state)[源代码]
exception angr.errors.SimSlicerError[源代码]

基类:SimError

exception angr.errors.SimActionError[源代码]

基类:SimError

exception angr.errors.SimCCError[源代码]

基类:SimError

exception angr.errors.SimUCManagerError[源代码]

基类:SimError

exception angr.errors.SimUCManagerAllocationError[源代码]

基类:SimUCManagerError

exception angr.errors.SimUnicornUnsupport[源代码]

基类:SimError

exception angr.errors.SimUnicornError[源代码]

基类:SimError

exception angr.errors.SimUnicornSymbolic[源代码]

基类:SimError

exception angr.errors.SimEmptyCallStackError[源代码]

基类:SimError

exception angr.errors.SimStateOptionsError[源代码]

基类:SimError

exception angr.errors.SimException[源代码]

基类:SimError

exception angr.errors.SimSegfaultException(addr, reason, original_addr=None)[源代码]

基类:SimException, SimMemoryError

__init__(addr, reason, original_addr=None)[源代码]
angr.errors.SimSegfaultError

SimSegfaultException 的别名

exception angr.errors.SimZeroDivisionException[源代码]

基类:SimException, SimOperationError

exception angr.errors.AngrNoPluginError[源代码]

基类:AngrError

exception angr.errors.SimConcreteMemoryError[源代码]

基类:AngrError

exception angr.errors.SimConcreteRegisterError[源代码]

基类:AngrError

exception angr.errors.SimConcreteBreakpointError[源代码]

基类:AngrError

exception angr.errors.AngrDecompilationError[源代码]

基类:AngrError

exception angr.errors.UnsupportedNodeTypeError[源代码]

基类:AngrError, NotImplementedError

Distributed analysis

angr.distributed provides a simple implementation for conducting long-running symbolic-execution-based tasks.

class angr.distributed.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)[源代码]

基类:object

Server implements the analysis server with a series of control interfaces exposed.

变量:
  • 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)[源代码]
inc_active_workers()[源代码]
dec_active_workers()[源代码]
stop()[源代码]
property active_workers
property stopped
on_worker_exit(worker_id, stashes)[源代码]
run()[源代码]
class angr.distributed.server.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)[源代码]

基类:object

Server implements the analysis server with a series of control interfaces exposed.

变量:
  • 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)[源代码]
inc_active_workers()[源代码]
dec_active_workers()[源代码]
stop()[源代码]
property active_workers
property stopped
on_worker_exit(worker_id, stashes)[源代码]
run()[源代码]
class angr.distributed.worker.BadStatesDropper(vault, db)[源代码]

基类:ExplorationTechnique

Dumps and drops states that are not "active".

__init__(vault, db)[源代码]
step(simgr, stash='active', **kwargs)[源代码]

Hook the process of stepping a stash forward. Should call simgr.step(stash, **kwargs) in order to do the actual processing.

参数:
class angr.distributed.worker.ExplorationStatusNotifier(server_state)[源代码]

基类:ExplorationTechnique

Force the exploration to stop if the server.stop is True.

参数:

server_state (dict)

__init__(server_state)[源代码]
参数:

server_state (dict)

step(simgr, stash='active', **kwargs)[源代码]

Hook the process of stepping a stash forward. Should call simgr.step(stash, **kwargs) in order to do the actual processing.

参数:
class angr.distributed.worker.Worker(worker_id, server, server_state, recursion_limit=None, techniques=None, add_options=None, remove_options=None)[源代码]

基类:object

Worker implements a worker thread/process for conducting a task.

__init__(worker_id, server, server_state, recursion_limit=None, techniques=None, add_options=None, remove_options=None)[源代码]
start()[源代码]
run(initializer)[源代码]
参数:

initializer (Initializer)